jQuery AJAX submit form
This is a simple reference:
// this is the id of the form$("#idForm").submit(function(e) { e.preventDefault(); // avoid to execute the actual submit of the form. var form = $(this); var url = form.attr('action'); $.ajax({ type: "POST", url: url, data: form.serialize(), // serializes the form's elements. success: function(data) { alert(data); // show response from the php script. } }); });
You can use the ajaxForm/ajaxSubmit functions from Ajax Form Plugin or the jQuery serialize function.
AjaxForm:
$("#theForm").ajaxForm({url: 'server.php', type: 'post'})
or
$("#theForm").ajaxSubmit({url: 'server.php', type: 'post'})
ajaxForm will send when the submit button is pressed. ajaxSubmit sends immediately.
Serialize:
$.get('server.php?' + $('#theForm').serialize())$.post('server.php', $('#theForm').serialize())
Another similar solution using attributes defined on the form element:
<form id="contactForm1" action="/your_url" method="post"> <!-- Form input fields here (do not forget your name attributes). --></form><script type="text/javascript"> var frm = $('#contactForm1'); frm.submit(function (e) { e.preventDefault(); $.ajax({ type: frm.attr('method'), url: frm.attr('action'), data: frm.serialize(), success: function (data) { console.log('Submission was successful.'); console.log(data); }, error: function (data) { console.log('An error occurred.'); console.log(data); }, }); });</script>