Stop submitting from javascript ajax request


I'd like to stop a form submitting by thr result of an ajax request... this is the code i tried to use: The function chreg() should return a boolean given from the ajax request, but it doesn't!


function chreg() { user = document.getElementById('nome').value; passw1 = document.getElementById('passw1').value; passw2 = document.getElementById('passw2').value; mai = document.getElementById('mail').value; dat = 'use='+encodeURIComponent(user)+'&pas='+encodeURIComponent(passw1)+'&pas2='+encodeURIComponent(passw2)+'&mail='+encodeURIComponent(mai); htp = new XMLHttpRequest; htp.onreadystatechange = function(){ if (htp.readyState == 4 && htp.status == 200){ if (htp.responseText == "true"){ alert('true'); return true; } else { document.getElementById('er2').innerHTML = '<br/><h3>'+tag_esc(decodeURIComponent(htp.responseText))+'</h3>'; return false; } } }; a = Math.random htp.open("POST","checklog.php?a="+a,true); htp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); htp.send(dat); }

And the HTML:

<form action="reg.php" method="POST" onsubmit="return chreg(this);"> <table id="tab2"><tr><td> <label for="user1">Username: <input type="text" name="user" id="nome" /></label></td> <td> <label for="mail">Indirizzo e-mail: <input type="text" name="mail" id="mail" /></label> </td> </tr> <tr><td><label for="pass1">Password: <input type="password" name="pass1" id="passw1" /> </label></td> <td><label for="pass2">Password (conferma): <input type="password" name="pass2" id="passw2" /></label></td></tr> <tr><td colspan="2"><br /><input type="submit" class="st" value="Registrati" /></td> </tr> </table> <div id="er2"></div> </form>

But it doesn't work! Help Thanks a lot!


You won't be able to make it work as it stands because <strong>AJAX is <em>asynchronous</em></strong> by default. That means that your chreg method initiates the request and returns <em>immediately</em>, before the request has completed and its result become known. This is a problem because you cannot return from chreg before the result is known since you need that result to know <em>what</em> to return.

One solution would be to make the request synchronous by changing the third parameter here:

// you will not need to set onreadystatechange at all htp.open("POST","checklog.php?a="+a,false); // false = synchronous htp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); htp.send(dat); if (htp.responseText == "true"){ alert('true'); return true; } else { document.getElementById('er2').innerHTML = '<br/><h3>'+tag_esc(decodeURIComponent(htp.responseText))+'</h3>'; return false; }

This is not the best solution because it might end up locking up the UI for the duration of the request, which is undesirable. However, going back to the asynchronous model (which does not have this problem) is going to be more involved because it requires you to do stuff "backwards":

<ol><li>Function chreg is called and makes the AJAX request; it <em>always</em> returns false (so the form is not submitted)</li> <li>When the onreadystatechanged handler you installed detects that the AJAX is complete, it checks the response.</li> <li>If the response is logically true (the form actually needs to be submitted) then use <a href="https://developer.mozilla.org/en/DOM/form.submit" rel="nofollow">form.submit</a> to do it.</li> </ol>


Your success handler function returns either true or false but your main chreg method doesn't.

You need to return false in your chreg method to stop the form submitting.

[...] htp.send(dat); return false;

Since you're handling the form submission through ajax, you'll likely not want the form to do a postback atall.


<!DOCTYPE html> <html> <body>

My First JavaScript

Please input a number.

<input id="demo" type="text"> <script> function myFunction() { var x=document.getElementById("demo").value; if(x==""||isNaN(x)) { alert("Not Numeric"); } } </script>


  • Magic number for plain text file
  • AJAX Permission Denied On IE?
  • parse json list in reverse order
  • Losing session in Coldfusion
  • Radio button show hover between two radio button using jquery
  • Type mismatch: cannot convert from Connection to Connection
  • angularjs ng-bind-html html input part missing
  • Zend Framework 2, Module Redirect
  • Why does PHP appear to evaluate this condition incorrectly?
  • Problem in Loading xml from specified url using javascript in FF & Google Chrome
  • Contact form problem - I do receive messages, but no contents (blank page)
  • Correctly Importing Apache Commons Math Package
  • Problem with Django using Apache2 (mod_wsgi), Occassionally is “unable to import from module” for no
  • C# fibonacci function returning errors
  • D3 get axis values on zoom event
  • Scrapy recursive link crawler
  • NetLogo BehaviorSpace - Measure runs using reporters
  • Align navbar back button on right side
  • DotNetZip - Calculate final zip size before calling Save(stream)
  • How to redirect a user to a different server and include HTTP basic authentication credentials?
  • How to handle AllServersUnavailable Exception
  • Can I make an Android app that runs a web view in Chrome 39?
  • Upload files with Ajax and Jquery
  • Do I've to free mysql result after storing it?
  • Warning: Can't call setState (or forceUpdate) on an unmounted component
  • A cron job substitute?
  • json Serialization in asp
  • Buffer size for converting unsigned long to string
  • Load html files in TinyMce
  • How can I get HTML syntax highlighting in my editor for CakePHP?
  • Free memory of cv::Mat loaded using FileStorage API
  • How do I configure my settings file to work with unit tests?
  • Memory offsets in inline assembly
  • Turn off referential integrity in Derby? is it possible?
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • LevelDB C iterator
  • Linking SubReports Without LinkChild/LinkMaster
  • Binding checkboxes to object values in AngularJs
  • To Get the radio button value in ruby on rails
  • jQuery Masonry / Isotope and fluid images: Momentary overlap on window resize