简体   繁体   中英

Send jQuery constructed array through jQuery ajax to PHP

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.

You must convert the javascript object into JSON:

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

Then, in your PHP code:

$photoDescriptions = json_decode($_POST['photoDescriptions']);

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM