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);
		type: "POST",
		url: "sendEmail.php",
		dataType: "json",
		data: jsonFile,
		success: function(data){
		error: function(e){

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?


^ _ ^


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"?


^ _ ^


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

  /* ... */
  error: function (xhr) {

or actually just

  /* ... */
  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