Sending object from JS to PHP

Hey everyone I’m having some trouble sending single variables or an object into PHP.

When I send a json object from my JS to PHP, the error i receive back is just “undefined”, and on the console, when I type in the variable jsonFile, which stringifies the object I want to send, it says “jsonFile is undefined”

	var jsonFile = JSON.stringify(emailContext);
	$.ajax({
		type: "POST",
		url: "sendEmail.php",
		dataType: "json",
		data: jsonFile,
		success: function(data){
			console.log("success");
		},
		error: function(e){
			console.log(e.message);
		}
	});
}

Where “emailContext” is an object containing attributes of:
name: xxx
email: xxx
mesage: xxx

I’m currently testing this on my local apache server, and I tried various methods but I’m just kinda stuck over here

Is emailContext an array? Are you checking for length before stringify()? From what I’m looking at, it seems like it should work.

Have you tried placing it within try/catch?

V/r,

^ _ ^

emailContext is just an object, and it definitely contains info because when i print it out on the console, it contains the info

If you alert(jsonFile); immediately after setting the var, does it display the JSON, itself?

Does try/catch give anything different from “jsonFile undefined”?

V/r,

^ _ ^

The error method doesn’t receive an actual error object as its 1st argument but the XMLHttpRequest that was sent, and that doesn’t have a .message property – hence it is undefined. Try something like this instead

$.ajax({
  /* ... */
  error: function (xhr) {
    console.log(xhr.statusText)
  }
})

or actually just

$.ajax({
  /* ... */
  error: console.error
})

for the complete arguments.

Well judging from that lonely closing brace at the end of your code the jsonFile variable isn’t declared in the global scope, but probably some sort of event handler function; so you can’t just access it at any point from the console. You can however set a breakpoint inside that function and then inspect the variables in its scope (and actually access them from the console).

When I alert the jsonFIle, it does output me the correct object, ill try both methods you guys provided to get a clear message of the error

When I did this, my console brings back ok, so i changed it to status and it brings back “200” which is for loading or done, however this is in the error:function, so im kinda confused as to why a “loading done” status would only appear at the error

First: Use your devtools of choice to verify the content that was sent:

Second: Both works, but use the shorthand of $.ajax which is $.post to trim down the code:

$.post('/', {example: 'test'}, a => console.log(a))

This should help you to get going. As it looks like, the origin of your data is wrong, so check why the object is not in there and find the root cause.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.