Bacchus Bacchus - 5 months ago 7
Ajax Question

Submit a form in an AJAX function

The server side methods works, and the AJAX function sets

data-duplicated="false"
but
$this.submit();
doesn't work. To actually submit the form I need to press the sumbit button again.

<form data-url="/.../" data-duplicated="true" onsubmit="return checkForDuplicates(this)">
<!-- Form inputs -->
</form>





function checkForDuplicates(e) {
var $this = $(e);
var url = $this.attr('data-url');

if ($this.attr('data-duplicated') === 'true') {

$.ajax({
url: url,
type: 'POST',
data: data,
success: function (result) {
if (result === true) {
$this.attr('data-duplicated', 'false');
$this.submit();
} else {
// warrning
}
}
});

return false;
}
return true;
}


What should I do to actually submit the form?

Answer

Bacchus, as I explained in the comments, you can do something like this:

$(document).ready(function(){
       $('#submit').on('click', function(){
         $.ajax({
                url: url,
                type: 'POST',
                data: data,
                success: function (result) {
                   if(result == 'duplicate'){
                     $('#form').submit();
                   }else{
                     //your custom message here
                   }
                }
            });
       });
});
<form id='form' action='' method='post'>
  <!--your inputs here-->
  <a id='submit'>Submit form</a>
</form>

Hope it helps you.