1
$.ajax({


            type: "POST",
            url: "ajax.php",
            dataType: 'json',
            data:   "callback=bumpup_contact_us_entry&id=" + id,
            success: function(data){
             $.each(data, function(interval, message) {
                alert(message['request']);
 });            

the php:

$the_return = array('request'=>'success','order_id'=>$order_id-1);

echo json_encode($the_return);

I could never get json to work for me. What am I doing wrong? The problem is isolated to this because returning html works fine.

Tim Cooper
  • 144,163
  • 35
  • 302
  • 261
Adam
  • 8,349
  • 16
  • 64
  • 126

3 Answers3

2
$the_return = array('request'=>'success','order_id'=>20);
echo json_encode($the_return);
//output: {"request":"success","order_id":20}

$.each(data,function(i, item) {
   alert( 'request: ' + data.request + ' id: ' +  data.order_id);
});

################################## BEAVIOURS ####################################

$the_return  = array( 'success' , 20 ); 
echo json_encode($the_return);
// output:  ["success",20] 

$.each(data,function(i, item) {
    alert('success: ' + item[0] + 'id: ' + item[1]);
});

$the_return['request'] = array( 'success' , 20 ); 
echo json_encode($the_return);
// output {"request":["success",20]}

$.each(data.request,function(i, item) {
    alert('success: ' + data.request[0] + 'id: ' + data.request[1]);
});

$the_return['message'] = array('request'=>'success','order_id'=>20);
echo json_encode($the_return);
//output: {"message":{"request":"success","order_id":20}}

$.each(data.message,function(i, item) {
    alert( 'request: ' + data.message.request + ' id: ' + data.message.order_id);
});
Luca Filosofi
  • 30,086
  • 8
  • 65
  • 74
1

Try like this:

$.ajax({
    type: 'POST',
    url: 'ajax.php',
    dataType: 'json',
    data: { callback: 'bumpup_contact_us_entry', id: id },
    success: function(data) {
        $.each(data, function(index, message) {
            alert(message.request);
        }
    }
});

or:

$.post('ajax.php', { callback: 'bumpup_contact_us_entry', id: id }, function(data) {
    $.each(data, function(index, message) {
        alert(message.request);
    }
}, 'json');
Darin Dimitrov
  • 960,118
  • 257
  • 3,196
  • 2,876
  • with the first example I get an error in firebug:second argument to Function.prototype.apply must be an array and gives me this as the response:{"request":"success"} I took out the order_id to simplify it – Adam Feb 20 '11 at 16:30
  • I ended up using your last example but with the .each since it's just going to be one json object. I have no idea why $.ajax was throwing me that error. – Adam Feb 20 '11 at 16:44
0

Try message.request inside your anonymous function.

Spencer Ruport
  • 34,215
  • 11
  • 81
  • 141