Adam
Adam

Reputation: 9049

getting undefined for the returned json

$.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.

Upvotes: 1

Views: 381

Answers (3)

Luca Filosofi
Luca Filosofi

Reputation: 31173

$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);
});

Upvotes: 2

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

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');

Upvotes: 1

Spencer Ruport
Spencer Ruport

Reputation: 35107

Try message.request inside your anonymous function.

Upvotes: 0

Related Questions