Home >Database >Mysql Tutorial >How to Integrate MySQL Inserts with PHP and jQuery/AJAX for a Seamless Form Submission Experience?
Challenge: Implementing an ajax-driven form that seamlessly inserts data into a MySQL database.
Solution:
<code class="javascript">var ajaxSubmit = function(formEl) { var url = $(formEl).attr('action'); var data = $(formEl).serializeArray(); $.ajax({ url: url, data: data, dataType: 'json', success: function() { if(rsp.success) { alert('form has been posted successfully'); } } }); // Prevent default form submission return false; }</code>
<code class="php">$val = mysql_real_escape_string(post('my_value'), $cxn); $sql = sprintf("INSERT INTO %s (column_name_goes_here) VALUES '%s';", 'table_name_goes_here', $val ); $result = mysql_query($sql, $cxn); $resp = new stdClass(); $resp->success = false; if($result) { $resp->success = true; } print json_encode($resp);</code>
Benefits:
The above is the detailed content of How to Integrate MySQL Inserts with PHP and jQuery/AJAX for a Seamless Form Submission Experience?. For more information, please follow other related articles on the PHP Chinese website!