Search code examples
javascriptphpjsonpostjsondecoder

json_decode $_POST not receiving Javascript JSON


I'm trying to send json formatted values to php but $_POST on php returns null when i call the function. This procedure is similar to w3schools php json example found here https://www.w3schools.com/js/js_json_php.asp at the bottom but still don't get the same result. The values next to the strings in json are variables with values in it. Here's what i've done:

var args = {'name': name, 'birthday': birthday, 'policy': policy, 'cl': cl, 'claim': claim, 'incoming': incoming, 'theDate': theDate,
    'xora': xora, 'treatment': treat, 'session': sess, 'inpat': inpat, 'outpat': outpat, 'daycase': daycase,
    'radioBtn': radioBtn, 'admDate': admDate, 'invDate': invDate, 'invNum': invNum, "nomisma": nomisma,
    'provSelect': provSelect, 'specSel1': specSelect1, 'prescSel': prescSelect, 'specSel2': specSelect2, 'amount': amount,
    'deduct': deduct, 'dedColl': dedColl, 'copay': copay, 'copayColl': copayColl, 'totalAm': totalAm, 'comms': comms,
    'diagnosiDesc': diagnosiDesc, 'diagnosiCode': diagnosiCode, 'nonAmount': nonAmount, 'reason': reason, 'categs': category };
var json = JSON.stringify(args);

if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp = new XMLHttpRequest();
} else {
    // code for IE6, IE5
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
    if (this.readyState === 4 && this.status === 200) {
        //alert("Saved and Continue");
        window.open("PHP/SaveAndCont.php?q="+json); // Test
    }
};

xmlhttp.open("POST","PHP/SaveAndCont.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("q="+json);

And here is my php file:

include('Connection.php');
header("Content-Type: application/json; charset=UTF-8");
$parse = $_POST['q']; // undefined index q
$obj = json_decode($parse, false);
var_dump($parse, $obj); // NULL

Solution

  • Set the content type header to application/json.

    In PHP with raw request you won't have variables filled in $_POST but instead you need to get json via raw request to get it:

    Check if the request type is post if not exit PHP

    <?php
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        die("wrong type of request"); 
    }
     // get raw json post object and decode it
     $json = json_decode(file_get_contents("php://input"));
     var_dump($jsonString);
    

    JS:

    var args = {'name': name, 'birthday': birthday, 'policy': policy, 'cl': cl, 'claim': claim, 'incoming': incoming, 'theDate': theDate,
        'xora': xora, 'treatment': treat, 'session': sess, 'inpat': inpat, 'outpat': outpat, 'daycase': daycase,
        'radioBtn': radioBtn, 'admDate': admDate, 'invDate': invDate, 'invNum': invNum, "nomisma": nomisma,
        'provSelect': provSelect, 'specSel1': specSelect1, 'prescSel': prescSelect, 'specSel2': specSelect2, 'amount': amount,
        'deduct': deduct, 'dedColl': dedColl, 'copay': copay, 'copayColl': copayColl, 'totalAm': totalAm, 'comms': comms,
        'diagnosiDesc': diagnosiDesc, 'diagnosiCode': diagnosiCode, 'nonAmount': nonAmount, 'reason': reason, 'categs': category };
    var json = JSON.stringify(args);
    
    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function () {
        if (this.readyState === 4 && this.status === 200) {
            //alert("Saved and Continue");
            alert(xmlhtml.responseText); // this should print the response
        } else if(this.status !== 200) {
            alert(this.status); // maybe it'll be 404 or 500 if so then correct the url in xmlhttp.open it depends on your server configuration but it needs to be accessed via http://localhost/ or host defined by you
        }
    };
    
    xmlhttp.open("POST","php/saveandcont.php", true); // this should be path that can be opened via browser
    xmlhttp.setRequestHeader("Content-type", "application/json");
    xmlhttp.send(json);