Jump to content

Send JSON through AJAX


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 post
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 post
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 post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...