I am trying to send an Ajax request with data from the html form. Here is the javaScript file:

$(document).ready(function() { $('#form').submit(function (e) { e.preventDefault(); var data = $('#form').serializeArray(); $.ajax({ type: "POST", url: "... .php", data: data, dataType: "json", success: function(d) { ... }, error: function(xhr, status, error) { alert(xhr.responseText + '|\n' + status + '|\n' +error); } }); }); }); 

In the file ... .php next:

  $data = json_decode($_POST['data']); $dataJson = json_encode($data); echo $dataJson; 

The response from the server is Null. I do not understand the reason. In JavaScript, the data variable contains objects ...

  • Is this the full content of the php file, or is there something else? - Vasily Barbashev
  • The rest of the code I commented out. Left only these lines - user206114
  • Recently I came across this problem, but I do not remember how I decided; In my opinion, the jamb in the data encoding ( application/x-www-form-urlencoded ) was. - Roman Grinyov
  • And maybe in the “same origin policy” ... - Roman Grinyov
  • To supplement your question, use the edit button. - Nick Volynkin

1 answer 1

In your case, the data property must be an object. $_POST['data'] will work if: data: {data: data} . Well, that is You must pass an object to the request so that it reaches

 var dataD = JSON.stringify( { a: 15, b: 18 } ); console.log('DATA=', dataD); $.ajax({ type: "POST", url: "myFile.php", data: { data: dataD }, success: function(d) { console.log('D=', d); }, error: function(xhr, status, error) { alert(xhr.responseText + '|\n' + status + '|\n' +error); } });