Home:ALL Converter>Getting data sent with Ajax from php?

Getting data sent with Ajax from php?

Ask Time:2019-05-20T22:03:28         Author:Ratacand

Json Formatter

sorry if this has been asked many times but I can't get it to work. I'm trying to build a restful website, I have a simple form:

<form action="/my/path" method="post" id="myformid">
Name <input type="text" name="name">
<input type="submit" value="Test">
</form>

I convert the data the user inputs using Javascript and I send them to my php file using Ajax:

function postData() {
    $('#myformid').on('submit', function(event) {
        event.preventDefault();
        const json = JSON.stringify($("#myformid").serializeArray());
        $.ajax({
            type: "POST",
            url: "/my/path",
            data: json,
            success: function(){},
            dataType: "json",
            contentType : "application/json"
        });
    });
}

And I tried reading the data on php like:

$data = json_decode(file_get_contents('php://input'), true);
$name = $data["name"];

The code works perfectly if I send a JSON in the request body using a tool like Postman, but from what I tested using Ajax the json data arrives as POST data, and I can read it using $_POST["name"], but non with the 'php://input' as I did.

How can I fix it so the JSON gets accepted even sent via Javascript?

Author:Ratacand,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/56222590/getting-data-sent-with-ajax-from-php
Farhad Misirli :

Change your ajax codes\n\n$('#btnSubmit').on('click', function(event) {\n event.preventDefault();\n $.ajax({\n type: \"POST\",\n url: \"/new.php\",\n data: $(\"#myformid\").serialize(),\n dataType: \"json\",\n success: function(response) {\n console.log(response);\n }\n });\n});\n\n\nAlso you need some changes in form\n\n<form action=\"new.php\" method=\"post\" id=\"myformid\">\nName <input type=\"text\" name=\"name\">\n<input id=\"btnSubmit\" type=\"button\" value=\"Test\">\n\n\n\n\nAnd you can get POST data in php file like $_POST['name'] ",
2019-05-20T14:31:07
stan chacon :

Hi you can try like this:\n\nFirst I use an id attribute for each input i dont really like to serialize stuff but thats me you can do it your way here are the files.\nyour index.php:\n\n <form method=\"post\" id=\"myformid\">\n Name :<input type=\"text\" id=\"name\" name=\"name\">\n <input type=\"submit\" value=\"Test\">\n </form>\n <br>\n <div id=\"myDiv\">\n </div>\n\n\nyour javascript:\n\n //ajax function return a deferred object\n function _ajax(action,data){\n return $.ajax({\n url: 'request.php',\n type: 'POST',\n dataType: 'JSON',\n data: {action: action, data: data}\n })\n }\n //your form submit event\n $(\"#myformid\").on('submit', function(event) {\n //prevent post\n event.preventDefault();\n //validate that name is not empty\n if ($(\"name\").val() != \"\") {\n //parameters INS is insert data is the array of data yous end to the server\n var action = 'INS';\n var data = {\n name: $(\"#name\").val()\n };\n console.log(data);\n //run the function and done handle the function\n _ajax(action,data)\n .done(function(response){\n console.log(response);\n //anppend name to the div\n $(\"#myDiv\").append(\"<p>\"+response.name+\"</p>\");\n });\n }\n });\n\n\nyour request.php file:\n\n<?php\n//includes and session start here\n//validate that request parameters are set\nif (isset($_POST[\"action\"]) && isset($_POST[\"data\"])) {\n //getters\n$action = $_POST[\"action\"];\n$data = $_POST[\"data\"];\n//switch to handle the action to perfom maybe you want to update with the form too ?\nswitch ($action) {\n case 'INS':\n // database insert here..\n //return a json object\n echo json_encode(array(\"name\"=>$data[\"name\"]));\n break;\n}\n}\n ?>\n\n\nResults:\n\n\n\nHope it helps =)",
2019-05-20T21:24:06
lakshya_arora :

From the documentation of .serializeArray().\n\n\n The .serializeArray() method creates a JavaScript array of objects, ready to be encoded as a JSON string.\n\n\nAnd in the example given in the same page, it is clear that you will get an array in php,\nto access an element, you should try-\n\n`$data[0]['name']`\n\n\nAlso, have you tried print_r($data), is it NULL??",
2019-05-20T14:20:46
yy