Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
Have you tried var_dumping $_GET in your call.php script to see what jQuery and PHP have done with your data? – cHao Jun 4 '12 at 18:52

2 Answers

up vote 2 down vote accepted
 data: {type: "stream", q: JSON.stringify(obj)},

instead of this use

 data: {type: "stream", q: obj},
share|improve this answer
yes that did the trick :) – Andreas Jarbol Jun 4 '12 at 19:00

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

share|improve this answer
1  
hi mate, dataType is not related to send data, but for format of receive data you expecting. – thecodeparadox Jun 4 '12 at 19:08

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.