jQuery Ajax - Sending form data

PloMar
Posts: 48

jQuery Ajax - Sending form data

Hello
I have the following code to send form data to a php script, with jQuery Ajax, withouut reloading the page.
But, when I press the Submit button it opens the "page.php", and the alert() isn't displayed.

Code: Select all

<script> $(document).ready(function(){ $('#form').submit(function(e) { var form_data = $(this).serialize(); $.ajax({ type: 'POST', url: '/page.php', data: form_data, success: function() { alert('Message sent'); } }); }); }); </script>
- How to make it work?

Admin
Hi,
You have to call preventDefault() method to stop default action.

Code: Select all

<script> $(document).ready(function(){ $('#form').submit(function(e) { e.preventDefault(); // STOP default action e.unbind(); // unbind. to stop multiple form submit var form_data = $(this).serialize(); // get form data into a string with pairs: name=value $.ajax({ type: 'POST', url: '/page.php', data: form_data, success: function() { alert('Message sent'); } }); }); }); </script>

Similar Topics