Jump to content

Send JSON through AJAX


aneeb

Recommended Posts

Hey Everyone! i have generated JSON from HTML form data, now i want to send that JSON to a PHP page. I have written this javascript.

  var jsondata;$.fn.serializeObject = function(){	var o = {};	var a = this.serializeArray();	$.each(a, function() {		if (o[this.name] !== undefined) {			if (!o[this.name].push) {				o[this.name] = [o[this.name]];			}			o[this.name].push(this.value || '');		} else {			o[this.name] = this.value || '';		}	});	return o;};$(function() {	$('form').submit(function() {		jsondata = $('#result').text(JSON.stringify($('form').serializeObject()));  return false;});})

Please help me i am new to this..

Link to comment
Share on other sites

pfft, there is no way you are new to JavaScript. You're code is rather advanced :) I didn't dig to deep into your serializeObject... But since you are harnessing the power of jQuery, you can probably do some modification of: jsonData = JSON.stringify($('form').serializeObject());jQuery.post("someFileName.php", {json: jsonData}, function(data){ console.log(data); });

Link to comment
Share on other sites

Thank you sir for your reply. I have done what you mentioned but it is stays on that same page nothing happens.I am doing it like this..

var jsondata;$.fn.serializeObject = function(){	    var o = {};	    var a = this.serializeArray();	    $.each(a, function() {			    if (o[this.name] !== undefined) {					    if (!o[this.name].push) {							    o[this.name] = [o[this.name]];					    }					    o[this.name].push(this.value || '');			    } else {					    o[this.name] = this.value || '';			    }	    });	    return o;};$(function() {	    $('form').submit(function() {			    jsonData = JSON.stringify($('form').serializeObject());jQuery.post("save.php", {json: jsonData}, function(data){ console.log(data); });  return false;});})

And on the PHP page i put this code to get the JSON data.

<?php$tmp = json_decode($_POST["data"]);echo $tmp['Fname'];?>

Link to comment
Share on other sites

Well 2 things here, nothing should look like it is happening as AJAX is behind the scenes (use firebug on FireFox to see ajax calls). Second, PHP should be $tmp = json_decode($_POST["json"]);

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...