I'm sending a fairly simple compilation of object to a php script using the jQuery's .ajax. I want to extract one value from each object in the PHP script. The javascript is:
var obj = [{id:1, name:"val1"}, {id:2, name:"val2"},{id:3, name:"val3"}];
$.ajax({
type: "GET",
url: "call.php",
contentType: "application/json",
data: {type: "stream", q: JSON.stringify(obj)},
success: function(response){
alert(response);
}
});
The call.php file is written as:
if($_GET['type']=='stream'){
$obj = json_decode($_GET['q']);
for($i=0;$obj[$i];$i++){
echo $obj[$i]->{'name'}." ";
}
}
However this returns 0, and I simply cannot figure out why.
Secondly a attempted using type:"POST" in the javascript, and $_POST in php, but that failed altogether.
2 Answers 2
data: {type: "stream", q: JSON.stringify(obj)},
instead of this use
data: {type: "stream", q: obj},
Comments
You are missing dataType: 'json' in your ajax options. contentType option is for data being sent only.
After adding dataType, try this:
echo $_GET['q'];
It should simply return the json string you send. If not need to look at request in console for problems
1 Comment
dataType is not related to send data, but for format of receive data you expecting.
var_dumping$_GETin your call.php script to see what jQuery and PHP have done with your data?