Im having difficulty getting my form contents to send to my php page using ajax, jquery and json. The results just doesnt want to show.

My javascript, where I create the JSON object and try to send it through to the php page:

var JSONobj;
var JSONstr;
function createJSON(){
	JSONobj = {
		firstname : $('#firstname').val(), 
		surname : $('#surname').val(), 
		age : $('#age').val(), 
		email : $('#email').val()
	JSONstr = JSON.stringify(JSONobj);

$(document).ready(function() {
		$.post("save.php", {data:JSONstr}, function(result){ alert(result);}, "json"); 

The php page:

	$tmp = json_decode($_POST["data"]);
	echo $tmp['firstname'];

What should happen is the firstname should be alerted. But the alert box doesnt even show and I find no errors using firebug...

Thanks in advance

5 Years
Discussion Span
Last Post by Airshow

I am not sure whether your createJSON() implementation is correct or not.
What I would do will be

var JSONobj = [];
JSONobj.push({firstname: $('#firstname').val(), surname: $('#surname').val(), age : $('#age').val(), email : $('#email').val()});
JSONstr = JSON.stringify(JSONobj);

JSON encoding is unnecessary here because regular GET or POST serialisation will do the job.

Simply use jQuery's form.serialize() method to encode all fields in the form.

$(document).ready(function() {
			url: "save.php", 
			type: "POST",
			data: $(this.form).serialize(),
			success: function(result){ alert(result); }

If necessary you can build the data string (or a data object) specifically to include only those form name|values pairs of interest, but this is generally not necessary because server-side scripts can (most times) be written simply to ignore any name|value pairs that are not needed.

In general, use JSON for sending multi-item data in an HTTP response. Only in exceptional circumstances, eg. to send a deep javascript object, is it necessary to use JSON-encoding in an HTTP request, but for the most part, it can be avoided.


Edited by Airshow: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.