I have the following function which gets called when a user clicks a submit button . Am I passing the JSON object in this line data:{sendFormData:formdata},
of the following code correctly?
I can see alert(JSON.stringify(formdata));
printing everything properly but when I do the following in the processPostRequest.php
page
var_dump($_POST["sendFormData"]);
It just prints NULL
. What am I doing wrong? Thanks
I can also see the Hurray
in the alert printing.
function submit(){
console.log("Test");
var formdata = $("#myform").serializeArray();
alert(JSON.stringify(formdata));
var request = $.ajax({
url: 'processPostRequest.php',
type:'POST',
contentType:'application/json',
data:{sendFormData:JSON.stringify(formdata)},
success: function(msg) {
alert("Hurray!");
}
});
}
Well
A:I would simplify it by calling $.post
B: put sendFormData in quotes, just for safety.
C: How do you know what the script var_dumpâs? Youâre not doing anything with the results in your success function.
Maybe I will take this example instead of above one :
function submit(){
var projectTitle = $('#projectTitle').val();
// let's say the value of projectTitle is "test"
alert("Inside Submit "+projectTitle);
var request = $.ajax({
url: 'php/<path to php file>/processPost.php',
type:'POST',
data:({title:projectTitle}),
dataType:'json',
success: function(msg) {
alert("Hurray!");
console.log("Checking Message");
console.log(msg);
}
});
}
So when this function gets called, in the processPost.php
, I am calling two var_dumps
which are as follows:
-
var_dump(isset($_POST['title']));
always prints bool(false)
and
var_dump ($_POST['title']);
always prints NULL
However, in the developers tool of browser, under Response
tab of Network tab, I could see both the values of var_dumps
getting printed. So, I want the value of projectTitle
on the processPost.php
page and for that, am I doing wrong by trying to grab it like the way I have shown in the above two var_dumps
?
and what happens if you specify data as
data: {"title":projectTitle}
âŚand are you certain that $(â#projectTitleâ) actually matches up to a text field? IE: Do you see in the outgoing request the POST value for title?
What happens if you var_dump($_REQUEST)
instead? That should give you everything from $_GET
, $_POST
, and $_COOKIE
No change. I still see it in the response tab as shown in the screenshot below :

When I used var_dump($_REQUEST)
, my Ajax didnât work as I got 500 Internal Server Error for GET in the console log.
So the request wasnt a POST verb, it was a GET verb. Might want to set your network monitor to report the Method as well.
try changing the word âtypeâ to âmethodâ in your call. I dont think jQueryâs deprecated type yet, but itâs definitely the old form of the request.
Changing it to method
is giving NULL and false in the response header. I think type
is the correct one.
Which one does your Network monitor say is using the POST method?
How do I setup Network monitor to see method?
right click on one of the current column headers and check âMethodâ.
Thanks. I saw POST
method when I used type:POST
. BTW I have my form starting like this :
`<form id="myform" action="" method="post">
</form>`
Do you think this could be creating any problem?
No, because the form isnt being submitted.
What version of jQuery are you using? Cause method was added in jQuery 1.9 and theyâre in version 3.3 at this pointâŚ
Itâs 2.1.4
. I just checked.
My form looks like this :
<form id = "myform" action="" method="post" >
First name: <input type="text" name="FirstName" id="projectTitle" value="Mickey"><br>
Last name: <input type="text" name="LastName" id="LastName" value="Mouse"><br>
<button type = "button" onclick="submit()">Submit Top Test </button>
</form>
If form isnât submitted then I am wondering how come itâs getting serialized and showing in alert?
What i mean by saying the form isnt submitted is that it doesnt use the standard form method of submission (The HTML version. Where you have a button with type submit and the page reloads etc). Instead javascript is AJAXâing the form data off to the php script to get the result.
Well. First thing iâd recommend would be to get a more up-to-date version of jquery. Though that might mess with other scripts running on the page, Odd that 2.1.2 doesnt recognize method.
When you look at the POST request in your network analyzer, what does it say the Form Data payload is in the Headers tab? (See attached for example. You may need to scroll down a ways in the headers tab, Form Data is usually the last item)
Hey @Jack_Tauson_Sr,
When you send JSON to a PHP script via a POST request, it doesnât actually end up in the $_POST array.
You have to retrieve it in the following way:
# Get JSON as a string
$json_str = file_get_contents('php://input');
# Get as an object
$json_obj = json_decode($json_str);
Thatâs odd. It certainly does when I do it.
test2.html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$.ajax({
url: 'http://127.0.0.1/test2.php',
type: 'POST',
data: {'wark':"caw"},
success: function(msg) {
console.log(msg);
}
})
</script>
test2.php
<?php
echo $_POST['wark'];
?>
Result:
And even when i specify and send some JSONâŚ
test2.html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$.ajax({
url: 'http://127.0.0.1/test2.php',
type: 'POST',
data: {'wark':{'imajson':"doot"}},
dataType: 'json',
success: function(msg) {
console.log(msg);
}
})
</script>
test2.php
<?php
echo json_encode($_POST['wark']);
?>
Result:
You need to set the content type, and pass the payload through JSON.stringify()
, as in the OPâs original example.
$.ajax({
url: 'test.php ',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({'wark':{'imajson':"doot"}}),
dataType: 'json',
success: function(msg) {
console.log(msg);
}
});
If the payload goes through JSON.stringify, itâs no longer JSON (itâs a string), and youâre sending with the wrong datatype.
Additionally, the OP did NOT stringify the entire data element, it only stringified the elements sendFormData within the JSON.
JSON is a text format. Itâs a string representation of JavaScript data structures.
Thatâs why you have mime types like text/plain
, text/html
, and text/css
- all of these are sent as string data, even though the format of the text is different in each case.
Yeah, thatâs something else the OP is doing wrong there if he wantâs to send the data as JSON.