Sending object from JS to PHP

php

#1

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


#2

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,

^ _ ^


#3

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


#4

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,

^ _ ^


#5

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


#6

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


#7

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