Venelin
Venelin

Reputation: 3308

jQuery/JSON - Response $.each multiple variables in array

Here is how i create the json response via PHP:

    foreach($results as $row){
        $result['address'][] = $row['name'];
        $result['office_id'][] = $row['office_id'];
    }
echo json_encode($result);  

So i have two variables: address and office_id.

Here is how i handle the response:

$.ajax({
    url: '../select.php',
    type: 'post',
    data: {
        city_id: EcontCity
    },
    dataType: 'json',
    success: function (data) {
    $('#shipping-office-select').empty();                               
    $.each(data.address, function(index, address) {                                                 
        $('#shipping-office-select').append('<option value="'+ office_id +'" >'+ address +'</option>');
    });
    }
});

So i can get the info for address with this code, but can get the response for office_id.

Why? Can you help me out resolve this error ?

Thanks in advance!

Upvotes: 0

Views: 51

Answers (2)

CodeGodie
CodeGodie

Reputation: 12132

The iteration in PHP is wrong. Also, in your JS code, where are you defining office_id?

This is how I would redo it.

PHP:

foreach ($results as $row) {
    $result[] = array(
        'address' => $row['name'],
        'office_id' => $row['office_id']
    );
}
echo json_encode($result);

your AJAX, the success method:

 success: function (data) {
         $.each(data, function (i, row) {
             $('#shipping-office-select').append('<option value="' + row.office_id + '" >' + row.address + '</option>');
         });
 }

Upvotes: 0

Derlin
Derlin

Reputation: 9881

In your each function, you iterate through the $result['address']array. You use office_id, which has not been declared anywhere inside the function.

Not sure I understood everything, but if there is exactly the same number of addresses and office ids, you can try:

$.each(data.address, function(index, address) {                                                 
    $('#shipping-office-select').append('<option value="'+ 
         data.office_id[index] 
            +'" >'+ address +'</option>');
});

Upvotes: 1

Related Questions