简体   繁体   中英

Unable to alert a json object after a ajax call

I have a php file with an array that has a few values. I also have a html page with a single input field. I have a listener that listens for changes in the input field, when a change happens a ajax call is made to the php file with an array. The php file uses json_encode() to convert the array to json.

Once this is done the data is returned to my html page and I am trying to alert the data.

However I am not able to, I get no errors, simply nothing happens and I am not sure why.

Here is my code.

<input type="text" name="searchDB" id="searchDB" placeholder="Type Address Here" autofocus=""/>
 <script>
            $(document).ready(function(){
                $("#searchDB").change(function(){
                    $.ajax({
                        type:"GET",
                        url: "request_9_dnm_db.php",
                        data: "hi="+$("#searchDB").val(),
                        dataType: "json",
                        success:function(msg){
                            var obj = jQuery.parseJSON(msg);
                            alert(obj.name);
                        }//Success

                    });//Ajax Call
                });//SearchDB Change
            });//document.ready
        </script>

And Here is my php

<?php

    $boom = array("user"=>array( array(
     "name"=>"Bob",
     "last"=>"Smith"), array(
         "name"=>"Jon",
         "last"=>"Snow"
     )
    )  
 );

 $coded = json_encode($boom);
return $coded;

You are using return in PHP in a wrong place. Give this instead:

echo $coded;

The above code should be used instead of return $coded; .

You are already added dataType: "json" so you don't need to parse it again using var obj = jQuery.parseJSON(msg);

$.ajax({
    type:"GET",
    url: "request_9_dnm_db.php",
    data: "hi="+$("#searchDB").val(),
    dataType: "json",
    success:function(obj){
        alert(obj.name);
    }//Success
});//Ajax Call

Also in your php you need to echo the json encoded string instead of returning

echo $coded; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM