Reputation: 380
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;
Upvotes: 0
Views: 285
Reputation: 115222
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;
Upvotes: 0
Reputation: 167182
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;
.
Upvotes: 3