Send JSON data to PHP using XMLHttpRequest without jQuery

I am trying to submit JSON data from a form using an XMLHttpRequest object. I can send data using the following function. There are no errors in FireBug, and the JSON data in the request is displayed by well-formed FireBug.

However, I am sending data to echo.php , which simply returns the contents:

<?php print_r($_POST); print_r($_GET); foreach (getallheaders() as $name => $value) { echo "$name: $value\n"; } echo file_get_contents('php://input'); ?> 

The POST array is always empty, but I see the JSON string returned by file_get_contents . How does this happen? What am I doing wrong?

echo.php output

 Array ( ) Array ( ) Host: localhost User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:10.0.2) Gecko/20100101 Firefox/10.0.2 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: eo,de-de;q=0.8,de;q=0.6,en-us;q=0.4,en;q=0.2 Accept-Encoding: gzip, deflate Connection: keep-alive Content-Type: application/json; charset=utf-8 Referer: http://localhost/form.html Content-Length: 88 Cookie: {{..to much data..}} Pragma: no-cache Cache-Control: no-cache {"type":"my_type","comment":"commented"} 

send function:

 function submit(){ var data={}; data.type=document.form.type.value; data.comment=document.form.comment.value; //get right XMLHttpRequest object for current browsrer var x=ajaxFunction(); var string = JSON.stringify(data); x.open('POST','echo.php',true); x.setRequestHeader('Content-type','application/json; charset=utf-8'); x.setRequestHeader("Content-length", string.length); x.setRequestHeader("Connection", "close"); x.onreadystatechange = function(){ if (x.readyState != 4) return; if (x.status != 200 && x.status != 304) { alert('HTTP error ' + req.status); return; } data.resp = JSON.parse(x.responseText); if(data.resp.status=='success'){ alert('That worked!'); }else{ alert('That didn\'t work!'); } } x.send(string); return false; //prevent native form submit } 
+6
source share
2 answers

You forgot to specify your variables in the submit function. A good way to use it is

 x.send('name1='+string+'&name2=value2'); 

Given this, I think you will have to change the content length header. I do not think it would be useful to send it.

Another thing you can do is try using the GET method. You can also try changing the title of your content as follows:

 xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded") 
+7
source

PHP does not automatically handle JSON requests, as is the case with requests encoded in the form or multiple. If you want to use JSON to send requests to PHP, you basically do it right with file_get_contents (). If you want to combine these variables into your global $ _POST object, you can, although I would not recommend doing this, as this may confuse other developers.

 // it safe to overwrite the $_POST if the content-type is application/json // because the $_POST var will be empty $headers = getallheaders(); if ($headers["Content-Type"] == "application/json") $_POST = json_decode(file_get_contents("php://input"), true) ?: []; 

Quick note: you should not send encoding with your Content-Type for / json application. This should only be sent with the text / * Content-Types.

+5
source

Source: https://habr.com/ru/post/909730/


All Articles