Abhijit Borkakoty Abhijit Borkakoty - 1 year ago 85
JSON Question

Ajax method in jquery using PHP as backend

I have a script file where the ajax method has been implemented, which adds a record to a form ...and then i have a php file which serves as the backend. What I am trying to say is we dint declare the record variable in php, we only declared it in jquery part. But how did we actually accessed it using

$record = json_decode($_POST['record']);

What is json_decode and json_stringify in the script file.


$add_form.submit(function(e) {


var fields = ['id', 'name', 'subject', 'theory', 'practical'];
var record = {};

for (var index in fields) {

var field = fields[index];

if (field == 'id' || field == 'theory' || field == 'practical')
record[field] = parseInt( $('input#add_'+field).val() );

record[field] = $('input#add_'+field).val();


record.total = record.theory + record.practical;

url: '/ab_batch/practice/db/action.php',
type: 'POST',
data: {
action: 'ajaxAddRecord',
record: JSON.stringify(record)

success: function(result) {

if ( 'true' == result.trim() ) {

$add_modal.find('.ajax_add_result').text('Student Record Added...').css({
color: 'green',
display: 'block'

else {
$add_modal.find('.ajax_add_result').text('Error Adding Student Record!').css({
color: 'red',
display: 'block'


error: function() {}




switch ($action) {
case 'ajaxAddRecord':

$record = json_decode($_POST['record']);
print ( $student->addRecord($record) ) ? 'true' : 'false' ;


Answer Source

The action variable is declared (created) in main.js. You're right.
It is an object which is then used and filled with values.

The $.ajax({ code block sends it stringified to action.php.
"stringified" means converted to a string.
It has to be done to send it to the server-side PHP because an object (or an array) can't be sent directly without converting it to a string.

Then this string, received has $_POST['record'], has to be "decoded" to access the values.
This is what json_decode does... It creates an array with it.

Google theses keywords for more:
jQuery object
PHP array
Ajax example tutorial

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download