Javascript - form submission depending on ajax response

I want to use AJAX to determine if form values ​​are acceptable to me (this is not form validation). AJAX result will determine if a form is submitted or not.

Below you will see that I am making an AJAX call when the form is submitted, and depending on what is being returned (either empty, which is acceptable, or an error message that is not acceptable), I would like to return true; or return false; $("form").submit .

I suspect my problem is being in AJAX success: Please help me get the result from an AJAX call so that I can do something like if (result == "") { return true; } else { return false; } if (result == "") { return true; } else { return false; } if (result == "") { return true; } else { return false; } .

WORKERS:

 $("form").submit(function(e) { e.preventDefault(); var form = this; var tray = $('select[name=tray_id]').val(); $.ajax({ type: "POST", url: "modules/reserve-check.php", data: {tray_id: tray}, cache: false }).done(function(result) { if (result == "") form.submit(); else alert(result); }).fail(function() { alert('ERROR'); }); }); 

ORIGINAL:

 $("form").submit(function() { var tray = $('select[name=tray_id]').val(); $.ajax({ type: "POST", url: "modules/reserve-check.php", data: {tray_id: tray}, cache: false, success: function(result) { alert(result); }, error: function(result) { alert(result); //This works as expected (blank if acceptable and error msg if not acceptable) } }); /* if (result == "") return true; else return false; */ return false; //this is here for debugging, just to stop the form submission }); 
+4
source share
2 answers

Since the ajax call is asynchronous, you must prevent the form from submitting, and then when the result returns, you check to see if it meets the condition and submit the form using the source code handler, avoiding preventDefault() in the jQuery event handler:

 $("form").submit(function(e) { e.preventDefault(); var self = this, tray = $('select[name=tray_id]').val(); $.ajax({ type: "POST", url: "modules/reserve-check.php", data: {tray_id: tray}, cache: false }).done(function(result) { if (result == "") self.submit(); }).fail(function() { alert('error'); }); }); 
+15
source

use e.preventDefault(); to prevent the form from this.submit() , then use this.submit() (does not call the jQuery .submit() trigger function, but rather the native <form> .submit() function) to submit the form.

 $("form").submit(function(e) { e.preventDefault(); var tray = $('select[name=tray_id]').val(); var form = this; $.ajax({ type: "POST", url: "modules/reserve-check.php", data: {tray_id: tray}, cache: false, complete : function(result){callback(result, form)} }); }); var callback = function(result, form){ if(!result) form.submit(); }; 
+1
source

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


All Articles