How to make an Ajax call with jQuery and display a message on success

Earlier today I was developing a contact form for a client that involved using jQuery Ajax to perform a request on a PHP file then return a message through jQuery dynamically onto the page. I very much enjoy developing in JavaScript, especially jQuery and try to as much as possible within my project. JQuery makes everything much cleaner and faster and when adept in the language can make things easier for the developer. Here is a quick snippet of basic code that will allow you to send a contact form remotely to a PHP file to do what you need to do in PHP then send a message back.

Form HTML

<div id="message">Fill out the form below and click send.</div>
<form method="post" action="#">
<table width="100%">
<tr>
<td>Name:</td>
<td><input type="text" name="name" id="name" />
</tr>
<tr>
<td>E-Mail:</td>
<td><input type="text" name="email" id="email" />
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Send Form" onclick="sendForm();return false;" />
</td>
</tr>
</table>
</form>
This is your basic HTML table form that has two fields, name and e-mail as well as a submit button that will call a function then return false so that the form doesn’t submit through POST on click.

JavaScript (jQuery)

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
function sendForm() {
$(document).ready(function() {
// get form values
var name = $('#name').val();
var email = $('#email').val();

// setting message to sending...
$('#message').fadeOut(500 , function() {
$('#message').html('Sending...');
$('#message').fadeIn(500 , function() {
// ajax call
$.ajax({
type: "POST",
data: { name: name, email: email },
url: 'ajax1.php',
success: function(msg) {
$('#message').fadeOut(500 , function() {
$('#message').html(msg);
$('#message').fadeIn(500);
});
}
});
});
});
});
}
</script>
This is the basic jQuery needed. It will essentially run a function when the submit button is clicked, store the name and e-mail fields, open the ajax1.php file located in the same directory and let the PHP script run on that file then return whatever message the ajax1.php echoes out.

PHP

<?php
$mail = mail('youremail@host.com' , 'Ajax Form' , 'Name: ' . $_POST['name'] . '
E-Mail: ' . $_POST['email'] , "From {$_POST['email']}");

if($mail) {
echo 'E-Mail Sent.';
} else {
echo 'E-Mail Not Sent';
}
?>

Leave a Reply

Your email address will not be published. Required fields are marked *

*

*