0

I'm trying to send an array from Javascript to PHP.

function wishlist_save(arr){
    $.ajax({
        type: "POST",
        url: "from.php?type=customers",
        data: {info: JSON.stringify(arr) },
        success: function(){

        }
    }); 
}   

The array is set this way:

function getAll(){
    var info = [];
    var i = 0;
    $(".desc").each(function(){
        var value = $(this).text();
        var qtt = $(this).attr('alt');

        info[i] = [];
        info[i]['desc'] = value;
        info[i]['qtt'] = qtt;

        i++;
    });

    return info;
}

If I output (with console.log(getAll())) the array in javascript I get the right values in Chrome Console:

[Array[0], Array[0], Array[0]]
 ->0: Array[0]
      desc: 'John'
      alt: 'Good'
 ->1: Array[0]
      desc: 'Obama'
      alt: 'Great'

But in PHP (from.php?type=customers) I can't figure out how to get those values..

$arr = json_decode($_POST['info']);
ChromePhp::log($arr[0]['desc']); // returns null

What am I doing wrong?

Solved.

The problem was on JSON.stringify(arr), which in some way didn't send properly the array to PHP.

So, all I needed was to adapt the function that retrieves the array:

var info = [];
info.push({desc: value, qtt: qtt });

Besides that, the AJAX only now need:

data: {info: arr },

And PHP:

Linesofcode
  • 5,327
  • 13
  • 62
  • 116

0 Answers0