Hi,

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() {
	$('#submit').click(function(e){
		e.preventDefault();
		createJSON();
		$.post("save.php", {data:JSONstr}, function(result){ alert(result);}, "json"); 
	});
});

The php page:

<?php
	$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

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() {
	$('#submit').click(function(e){
		e.preventDefault();
		$.ajax({
			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.

Airshow

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.