How To Use jQuery To Submit Form To PHP/MySQL
jQuery JavaScript Library https://jquery.com/
Intermediate
Using jQuery to submit a form, is something you are seeing more and more of as jQuery’s popularity grows. When I first started reading about jQuery and Ajax all I wanted to do was learn how to submit a form using jQuery.
This new code is using the elements and styles that belong to the Twitter Bootstrap, download and get it setup if you want the same look and feel as the demo.We are going to take form data and submit it to a jQuery Ajax call then send that to a PHP page with the data.
<form class="well" id="jquery-submit-ajax" method="post">
<label>Your Name</label>
<input type="text" class="span7" name="yourName" placeholder="Type something…">
<label>Your Email</label>
<input type="text" class="span7" name="yourEmail" placeholder="Type something…">
<span class="help-block">When this form is submitted it will be sent via jQuery/AJAX.</span>
<input class="btn btn-primary" type="submit" value="Submit & Test Form">
<br /><br />
<div class="alert alert-success hide">
<p>Form successfully submitted! The data sent is below:</p>
<div id="success-output" class="prettyprint"></div>
</div>
<div class="alert alert-error hide">
<p>Oh shit! Error below:</p>
<div id="error-output" class="prettyprint"></div>
</div>
</form>
$(document).ready(function(){
$("#jquery-submit-ajax").submit(function(e) {
$.ajax({
type: "POST",
url: "jquery-ajax-control.php",
data: $(e.target).serialize(),
dataType: "json",
beforeSend:function(){
$('.alert-error,.alert-success').hide();
},
error: function(jqXHR, textStatus, errorThrown){
$('.alert-error').fadeIn();
$('#error-output').html(errorThrown);
},
success: function(data){
$('.alert-success').fadeIn();
$('#success-output').html(data);
}
});
return false;
});
The next section is the bulk of the code. jQuery makes it very nice and easy to create Ajax calls. As you see, we have type, url, data, and success. These are pretty self explanatory.
Remember that all of these are explained at the jQuery page. There is a slew of options you can run within this one jQuery.ajax() function.
The success part:
success: function(){
$('form#submit').hide(function(){$('div.success').fadeIn();});
}
Once the form is successfully submitted, the form will hide and thanks to jQuery callbacks, we then show the success message.
Below is what our ajax.php file will look like, this will carry out the submission. Save this as ajax.php.
<?php
include ("../../inc/config.inc.php");
// CLIENT INFORMATION
$fname = htmlspecialchars(trim($_POST['fname']));
$lname = htmlspecialchars(trim($_POST['lname']));
$addClient = "INSERT INTO clients (fname,lname) VALUES ('$fname','$lname')";
mysql_query($addClient) or die(mysql_error());
?>
There you have it, a straight forward guide to to using jQuery, PHP, and a simple HTML form to submit a form. Hopefully this will be a help to users new to the jQuery/Ajax world!