Support list Array with Jquery, JSON and PHP


I'm doing a help list function that creates an array from a table to store it in a database as a string.

The table contains a lot of information, in short, I can retrieve all the information with this JS code

  $("table#tbl_asistencia tr").each(function()
      var i = 0;
      var asistencia_arr = [];
      var tableData = $(this).find('td');
      if (tableData.length > 0)
        dataType: 'json',
        cache: false,

In the google console this appears

That is, if he is sending the arrangement. On the PHP side I have this

if (isset($_RESQUEST["asistencia_arr"])){$asistencia_arr = $_REQUEST["asistencia_arr"];}else{$asistencia_arr = "";}
$arr = json_decode($asistencia_arr);

But nothing is showing up, I have no response in the Chrome console, apparently I'm doing something wrong in PHP and even in JS. I'm seeing it appear as:

asistencia_arr[]: UN USUARIO
asistencia_arr[]: A
asistencia_arr[]: A

I'm worried that the array does not have an index and can not access it. For example

asistencia_arr[0]: UN USUARIO
asistencia_arr[1]: A
asistencia_arr[2]: A

How can I solve it and get the values in PHP? Thanks to everyone.

asked by Alberto Siurob 24.11.2016 в 01:28

1 answer


The short answer is YOU DO NOT HAVE TO RESOLVE IT The indexes of the Arrays are implicit:

echo asistencia_arr[0] //debe mostrar "UN USUARIO"

In a slightly longer response, to be consistent what joins and sends JQuery against what PHP gets and interprets we would normally use an associative array but JavaScript does not work that way, we use a Object Literal instead:

var person = {opcion1:"John", opcion2:"Doe", opcion3:50, opcion4:"blue"};

Lastly, you are doing a POST , so in PHP the data is also in the variable $_POST and what you have is an array in the variable asistencia_arr something similar to this:

$_POST['asistencia_arr'] = ["UN USUARIO", "A", "A"];

As we said at the beginning, it has implicit indexes, we have the following:

echo $_POST['asistencia_arr'][0]; //"UN USUARIO"
echo $_POST['asistencia_arr'][1]; //"A"
echo $_POST['asistencia_arr'][2]; //"A"

Finally, specifically in your code you have a json_decode() but in the screen that you show, it seems to me the data is NOT traveling as JSON; this may be what is breaking everything.

Before anything, PHP prints what is coming to you to know if you are indeed receiving a JSON since the dataType option in your ajax function is to tell JQuery what type of response to expect:

answered by 24.11.2016 / 09:16