Submitting JSON data via JQuery ajax.post to PHP

前端 未结 4 1365
慢半拍i
慢半拍i 2020-11-28 15:33

Im submitting Data to a php file via AJAX using POST. It worked fine with just submitting strings, but now I wanted to submit my JS Object with JSON and decode it on PHP sid

4条回答
  •  温柔的废话
    2020-11-28 15:53

    Where you went wrong in your code in the first code is that you must have used this:

    var_dump(json_decode(file_get_contents("php://input"))); //and not $_POST['data']
    

    Quoting from PHP Manual

    php://input is a read-only stream that allows you to read raw data from the request body.

    Since in your case, you are submitting a JSON in the body, you have to read it from this stream. Usual method of $_POST['field_name'] wont work, because the post body is not in an URLencoded format.

    In the second part, you must have used this:

    contentType: "application/json; charset=utf-8",
    url: "ajax/selectSingle.php?m=getAbsence",
    data: JSON.stringify({'Absence' : JSON.stringify(this)}),
    

    UPDATE:

    When request has a content type application/json, PHP wont parse the request and give you the JSON object in $_POST, you must parse it yourself from the raw HTTP body. The JSON string is retrieved using file_get_contents("php://input");.

    If you must get that using $_POSTyou would make it:

    data: {"data":JSON.stringify({'Absence' : JSON.stringify(this)})},
    

    And then in PHP do:

    $json = json_decode($_POST['data']);
    

提交回复
热议问题