0

I can't seem to get this object to pass through jQuery's ajax to my PHP file.

$("body").on("submit", ".upload-results-form", function(){

        var photosJSON = [];

$(".upload-result-wrapper .upload-results .photos li").each(function(){

    var photoID = $(this).attr("rel");
    var description = $(".photo-upload-description", this).val();
    var source = $("img", this).attr("src");

    photosJSON.push({photoID: photoID, description: description, source: source});

});

var jsonData = JSON.stringify(photosJSON);


    $.ajax({
    type: "POST",
    url: "ajax/add/albums/photos_publish.php",
data: "photosJSON="+jsonData,
    cache: false,
    success: function(html){
        alert(html);        
    }
    });

}); 

my jsonData looks like this:

[{"photoID":"47","description":"","source":"photos/50611a8725cca_224.jpg"},
{"photoID":"48","description":"","source":"photos/50611a8764881_224.jpg"},
{"photoID":"49","description":"","source":"photos/50611a87aa508_224.jpg"},
{"photoID":"50","description":"","source":"photos/50611a88dd34b_224.jpg"}]

and my php file:

$photosJSON = json_decode($_POST['photosJSON']);
echo $photosJSON['photoID'];

however nothing is returned, it doesn't appear that anything is being sent through to php.

2 Answers 2

1

You must convert the javascript object into JSON:

data: {photoDescriptions: JSON.stringify(photoDescriptions)},

Then, in your PHP code:

$photoDescriptions = json_decode($_POST['photoDescriptions']);
Sign up to request clarification or add additional context in comments.

3 Comments

Oops, I just realized I had the file directory off a tad bit, so not matter what I had it seemed like it wasn't working - because it wasn't! Thanks for your help as well
And actually, it doesn't appear that anything is being sent to PHP. The string is empty
Updated the code. Data being passed through http must be encoded, and jQuery does that automatically if pass data as object, otherwise you must use encodeURIComponent to encode the string.
1

First things first: the "data" attribute of the AJAX call needs to be an object, like timidboy said.

Two quick sanity checks:

console.log(photosJSON);

right after the end of the .each(), and

var_dump($_POST);

somewhere in your PHP page. I suspect that, presuming you followed timidboy's corrections, the problem is not in your AJAX. Are you certain, for instance, that the identifier being iterated over by each() actually matches a DOM element on the page?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.