AJAX form submission in jQuery Mobile

I am trying to submit a simple ajax login form to jQuery Mobile's website, but I am having problems.

It appears that when I submit the form (via POST), the form parameters are added to the URL. Not only that, they erase the linked page that I was on before submitting the form.

For example, I am on the localhost:8080/myapp/#sign_up page localhost:8080/myapp/#sign_up

Then I submit a form causing the URL to become: localhost:8080/myapp/ ?email=a@a.com &pass=pass

So, if I hit the validation errors and clicked the back button, I won’t go back to the #sign_up page.

Any ideas?

+6
source share
3 answers

If you handle submitting a form using a special submit event handler, you can handle validation on the same page:

 //bind an event handler to the submit event for your login form $(document).on('submit', '#form_id', function (e) { //cache the form element for use in this function var $this = $(this); //prevent the default submission of the form e.preventDefault(); //run an AJAX post request to your server-side script, $this.serialize() is the data from your form being added to the request $.post($this.attr('action'), $this.serialize(), function (responseData) { //in here you can analyze the output from your server-side script (responseData) and validate the user login without leaving the page }); }); 

To stop jQuery Mobile from starting your own AJAX profile of your form, put this in your form tag:

 <form data-ajax="false" action="..."> 
+15
source

Jaspers solution above worked for me! The only thing I had to adjust was to replace .live with .submit (.live is no longer recommended). So now like this:

 $('#form_id').submit(function (e) { //cache the form element for use in this function var $this = $(this); //prevent the default submission of the form e.preventDefault(); //run an AJAX post request to your server-side script, $this.serialize() is the data from your form being added to the request $.post($this.attr('action'), $this.serialize(), function (responseData) { //in here you can analyze the output from your server-side script (responseData) and validate the user login without leaving the page }); }); 
+3
source

If you want to submit the form and not use ajax (which is the default), you must add 'data-ajax = "false" to the form line:

  <form data-ajax="false" action="test.php" method="POST"> 
0
source

Source: https://habr.com/ru/post/900790/


All Articles