puiu91
2/2/2016 - 4:34 PM

Javascript ajax to PHP script

Javascript ajax to PHP script

<?php 

// errors turned up to 11
ini_set('display_errors',1);
error_reporting(E_ALL|E_STRICT);

// prevent caching
header('Cache-Control: no-cache, must-revalidate');

// set MIME header to json
header('Content-type: application/json');

// decode input stream
$json = json_decode(file_get_contents('php://input'), true);

echo json_encode('got the data');
    // create ajax request object
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {

                response = JSON.parse(xhr.responseText)
                console.dir(response)

            } else {
                throw 'Ajax request failed';
            }
        }
    };    

    console.dir(xhr)

  // open the connection and make a POST request
  xhr.open('POST', encodeURI('recievesAjax.php'), true);
  xhr.setRequestHeader('Content-Type', 'application/json');
  xhr.send(JSON.stringify(data));