Prevent form submission in Ajax

I have a form with

<form id=myform onsubmit=return validate();>
<input type=text id=name name=name>
</form>

      

In my javascript file I have

function validate(){
 $.ajax({
        dataType: 'json',
        url: app.url.prefix,
        method: 'POST',
        data: {service: 'manage', met: 1, name: name },
        success: function (data) {
            if (data.exists){
                 return false;
            }

        }

    });
return true;
}

      

This code Ajax

checks if the returned data is meaningful, especially data.exists

. I would like to prevent the form from being submitted based on the existing value.

it
if (data.exists){ return false; }

does not work.

+3


source to share


3 answers


$('#myform').submit(function() {
    return false;
});

      

This should do the trick, now the form won't reload the page when you press enter or a button.



EDIT:
Your form is missing double quotes too

<form id="myform" onsubmit="return validate();">
    <input type="text" id="name" name="name">
</form>

      

0


source


Your problem comes from the async ajax function call, it returns true before the ajax data is returned. I haven't tested it, but you can try something like this:

function validate(){
var self = this;
self.preventDefault();
 $.ajax({
        dataType: 'json',
        url: app.url.prefix,
        method: 'POST',
        data: {service: 'manage', met: 1, name: name },
        success: function (data) {
            if (!data.exists){
                 self.submit();
            }

        }

    });

      



return false; }

0


source


Decision:

I changed mine HTML

and I added an event onclick

thanonsubmit

<form id="myform">
   <input type="text" id="name" name="name">
   <button type="submit" id="button" onclick="validate();">
</form>

      

also in Javascript

I cannot imagine here

 $("#button").on("click",function(event){
    event.preventDefault();
});

      

Here is my function to check if the data exists and then submit the form

function validate(){

$.ajax({

 dataType: 'json',
 url: app.url.prefix,
 method: 'POST',
 data: {service: 'manage', met: 1, name: name },
 success: function (data) {
 if (!data.exists){
   $('#myform').submit();
}
 }
  });

      

0


source







All Articles