I am reading the documentation on the jQuery website about the $.ajax() method and I didn’t see an example of the HTML. I’m wondering how you tie the $.ajax() function to a user’s “Click” on the submit button. This is my best guess, is it the right way?
Here is the example:
<html>
<head></head>
<body>
<form id="my_form">
<input type="text" name="name"><br />
<input type="text" name="email"><br />
<textarea name="message"></textarea>
<input type="submit" name="submit">
</body>
</html>
Javascipt
submit: function {
var form_data = $("form#my_form").serialize();
function progress() {
//some loading gif
};
function removeProgress() {
//remove the loading gif
};
$.ajax ({
type: "GET",
url: "contact-us.php",
data: form_data,
beforeSend: progress(),
error: function() { alert("dude, something went wrong!"); },
success: function() { alert("WIN!"); },
complete: function() {
removeProgress();
alert("1 row added.");
}
});
You will need to bind the function to an event triggered by an element. For example, to bind a function to the
submitevent of the<form id="my_form">element, you would do this:In order to prevent the form from posting to a page (as it would normally do), you would need to add a call to
preventDefault()on theevent, like this: