Home > OS >  Unable to get data from remote json using jQuery ajax()
Unable to get data from remote json using jQuery ajax()

Time:09-29

Helle there, I would like to take the value "localidade" in this json: https://viacep.com.br/ws/35400000/json but unfortunataly my code is not working and I do not know why. My PHP code is:

<script type="text/javascript">
    function calculate(cep){
        var URL = "https://viacep.com.br/ws/";
        URL  = cep;
        URL  = "/json/";
        
        $.ajax({
            type: "GET",
            dataType: "JSON",
            url: URL,
            success: function(data){
                alert(data["localidade"])
            }
        });
    }

    <?php
        $cep = 35400000;
        echo "calculate($cep);";
    ?>
</script>

Someone can help me?

CodePudding user response:

Your code is right but you are using PHP in js to call a method there are 2 ways 1st: pass value from PHP to js and call method from js

<script type="text/javascript">
    function calculate(cep){
        var URL = "https://viacep.com.br/ws/";
        URL  = cep;
        URL  = "/json/";
        
        $.ajax({
            type: "GET",
            dataType: "JSON",
            url: URL,
            success: function(data){
                alert(data["localidade"])
            }
        });
    }
    var cep= 35400000 //<?=json_encode($value)?>;
    calculate(cep);
</script>

2nd: call js function from PHP

$cep=35400000;
echo '<script type="text/javascript">',
     'calculate("$cep");',
     '</script>'
;

<script type="text/javascript">
    function calculate(cep){
        var URL = "https://viacep.com.br/ws/";
        URL  = cep;
        URL  = "/json/";
        
        $.ajax({
            type: "GET",
            dataType: "JSON",
            url: URL,
            success: function(data){
                alert(data["localidade"])
            }
        });
    }
</script>

  • Related