Note that there are some explanatory texts on larger screens.

plurals
  1. POSend JSON data to PHP using XMLHttpRequest w/o jQuery
    primarykey
    data
    text
    <p>I am trying to send JSON data from a form using the XMLHttpRequest object. I can send the data using the following function. There are no errors displayed in FireBug and the JSON-data in the request is displayed well formed by FireBug.</p> <p>However, I send the data to <strong>echo.php</strong>, what simply returns the content:</p> <pre><code>&lt;?php print_r($_POST); print_r($_GET); foreach (getallheaders() as $name =&gt; $value) { echo "$name: $value\n"; } echo file_get_contents('php://input'); ?&gt; </code></pre> <p>The POST-array is always empty, but I can see the JSON string returned by <code>file_get_contents</code>. How does that happen? What am I doing wrong?</p> <p><strong>output of echo.php</strong></p> <pre><code>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"} </code></pre> <p><strong>the sending function:</strong></p> <pre><code>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 &amp;&amp; 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 } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload