1

I trying to post some value via ajax to php then php print send back js console.log, have problem:

build array( I'm doubt below I made is array??)

$('.eachcontainer').each(function(){
        var arr = $(this).find('img').map(function(){
            return $(this).attr('src');
        });
        console.log(arr);
        // result:
        // ["16.png", "17.png", "19.png", "18.png"]
        // ["0.png"]
        // ["0.png"]
        // []
        // []
        $.ajax({
            type: "POST", url: "update.php",
            data: arr
        }).done(function(msg){
            console.log(msg);
        });
});

php

print_r($_POST);

js come back console.log

Array
(
    [undefined] => 
)
Array
(
)
Array
(
)
Array
(
    [undefined] => 
)

Why this does not work? How can i fix it?

Also, I tried to change the syntax in my ajax function data: {arr: arr} but this didn't work either.
Error message:
TypeError: Type error jquery-1.10.1.min.js:6
Found error line in jquery-1.10.1.min.js:6:
t = x.isFunction(t) ? t() : null == t ? "" : t, i[i.length] = encodeURIComponent(e) + "=" + encodeURIComponent(t)

2 Answers 2

1

you haven't constructed proper key&value pair using your data, if you want to pass a raw stream of data then set processData: false and capture with php://input

 var arr = $(this).find('img').map(function(){
            return $(this).attr('src');
        });
        $.ajax({
            type: "POST", url: "update.php",
            data: arr,
            processData: false,
        }).done(function(msg){
            console.log(msg);
        });

on the php side

$data = file_get_contents("php://input");
Sign up to request clarification or add additional context in comments.

3 Comments

if set processData: false will effect another data? because I try to post another data:{x: x, y: y} sametime
It will only affect the current request. Subsequent requests will only be affected when you set their processData option to false
then how do I wrote the syntax is correct : data{x: x, y: y, arr: arr} php print $_POST['x']; print $_POST['y']; print file_get_contents("php://input");
0

You first need to call arr.get() to get the jquery.map result back as a regular javascript array. Then you can pass it to the ajax data paramter as:

data: { "images" : arr.get() }

So the full ajax call would look like this:

$.ajax({
    type: "POST", url: "update.php",
    data: { "images" : arr.get() }
}).done(function(msg){
    console.log(msg);
});

You can then read the array back in php as:

$images = $_POST['images'];

Comments