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.
main.js
$add_form.submit(function(e) {
e.preventDefault();
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() );
else
record[field] = $('input#add_'+field).val();
}
record.total = record.theory + record.practical;
$.ajax({
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'
}).fadeOut(2500);
}
else {
$add_modal.find('.ajax_add_result').text('Error Adding Student Record!').css({
color: 'red',
display: 'block'
}).fadeOut(2500);
}
},
error: function() {}
});
});
action.php
switch ($action) {
case 'ajaxAddRecord':
$record = json_decode($_POST['record']);
print ( $student->addRecord($record) ) ? 'true' : 'false' ;
break;
}