Am I sending the JSON object correctly via Ajax?

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:

  1. var_dump(isset($_POST['title'])); always prints bool(false)
    and

    1. 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.