Post via Ajax arrives empty at PHP

-1

I have some values selected by checkboxes that I would like to send to be processed in another PHP script.

When I send the post via ajax to a page that receives the variable $ _POST and prints it, I only see "Array (0) {}".

var objeto = {flag: "exportar"};
var arr = [];
var seletores = document.querySelectorAll(".meusCheckBoxes");
for(i = 0; i < seletores.length; i++){
  if(seletores[i].checked){
    arr.push(seletores[i]); 
  }
}
objeto['dados'] = arr;
$.ajax({
  url: "Url",
  data: objeto,
  type: "POST",
  contentType: false,
  processData: false,
  success: function(retorno){
    $(".conteudo").html(retorno); //array(0) { } 
    console.log(objeto); //Object {flag: "exportar", dados: Array[5]}
  }
}); 

I think the problem is that I send an Object with an array inside, because when I send it separately I can see the return.

I need to send an Object because the index ("export", in this case) has to be associative, something the array in javascript does not have.

Note: Note that in "success" the console prints Object with the array correctly posted.

    
asked by anonymous 18.02.2016 / 00:36

2 answers

1

After commenting on @TobyMosque suggesting the use of FormData , and adding a form in HTML I made the following changes to my JS :

/*var objeto = {flag: "exportar"};
var arr = [];
var seletores = document.querySelectorAll(".all");
for(i = 0; i < seletores.length; i++){
  if(seletores[i].checked){
    arr.push(seletores[i]); 
  }
}
objeto['dados'] = arr;*/

var objeto = new FormData(document.querySelector(".meuForm"));
objeto.append("flag", "exportar");

$.ajax({
  url: "URL",
  data: objeto,
  type: "POST",
  contentType: false,
  processData: false,
  success: function(retorno){
    $(".conteudo").html(retorno);
    console.log(objeto);
  }
}); 

And it was totally OK!

The initial problem was not solved exactly, but this solution proved better than my initial one. Thank you all!

    
18.02.2016 / 21:37
0

PHP only takes the value of the object, in case you are sending an object to php, where it will not recognize the object it is receiving. Use:

arr.push(seletores[i].value);

And send with ajax with JSON as it is easier to work with.

    
18.02.2016 / 12:31