Allan Thomas
Allan Thomas

Reputation: 3589

Looping through JSON data

I'm building an array of image filesnames (src) and the ID attribute (id)

var arr = {};
$('.selection .image').each(function(index) {
    var $this = $(this),
    id = $this.children('img').attr('id'),
    src = $this.children('img').attr('src');

    arr[id] = src;
});

Then I'm sending it out to a php script to perform some other functions.

e.g. {"8":"http://www.domain.com/file8.jpg","9":"http://www.domain.com/file9.jpg"}

$.ajax({
    type: 'POST',
    url: 'array.php',
    data: 'array='+JSON.stringify(arr),
    dataType: 'json',
    success: function(data){
        updateContainer(data.reply);
    },
});

I'm having trouble looping through the data in the php file. Can anyone help me further than this? Cheers

$json = $_POST['arr'];
$array = json_decode($json, TRUE);

Upvotes: 0

Views: 277

Answers (1)

Erik
Erik

Reputation: 20712

You may be making this more complex then you need to. The $.ajax method will take an object for data:

data: arr

Then, on the PHP end you'd have the following:

print_r($_POST);

array(
  [8] => http://www.domain.com/file8.jpg
  ... etc ...
)

That being said, if you're sample code above is correct, you're passing in a value for array and trying to access it was arr on the php side. You'd want $_POST['array'] based on the code samples above, if you wish to say with the JSON method you've described.

Upvotes: 3

Related Questions