Ajax method in jquery using PHP as backend -
i have script file ajax method has been implemented, adds record form ...and have php file serves backend. trying dint declare record variable in php, declared in jquery part. how did accessed using
$record = json_decode($_post['record']);
what json_decode , json_stringify in script file.
main.js
$add_form.submit(function(e) { e.preventdefault(); var fields = ['id', 'name', 'subject', 'theory', 'practical']; var record = {}; (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; }
the action variable declared (created) in main.js. you're right.
object used , filled values.
the $.ajax({
code block sends stringified action.php.
"stringified" means converted string.
has done send server-side php because object (or array) can't sent directly without converting string.
then string, received has $_post['record']
, has "decoded" access values.
json_decode
does... creates array it.
google theses keywords more:
jquery object
json.stringify()
json_decode()
php array
ajax example tutorial
Comments
Post a Comment