Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AJAX request before regular form is being submitted

Tags:

jquery

ajax

forms

I have a jQuery form validation script that is executed while user is trying to submit. I would like another function with AJaX request to be executed (and completed) after the form is validated but before it is sent.

Here is the script. The zglosip function works okay when called separately; i.e. not from inside the submit() function.

zglosip(); (function that I want to be called)

function zglosip() {
        $.ajax({
            type : 'post',
            url : 'res/php/nZglos.php',
            data : {
            "erepid" : "111",
            "ip" : "222",
            "poz" : "333"
            },
            success : function(data, textStatus, jqXHR) {
            tempor.html(data);
            },
            error : function(XMLHttpRequest, textStatus, errorThrown) {
            tempor.html(errorThrown);
            },
            dataType : 'text'
            return true;
        });
    };

validation script (created by Joren Rapini and modified by me)

pole & tempor are variables containing names of some divs

$("#forml").submit(function(){  
    //Validate required fields
    if ((pole.val() == "") || (pole.val() == blad)) {
        pole.addClass("podkresl");
        pole.val(blad);
    } else {
        pole.removeClass("podkresl");
    }
    // Validate the e-mail.
    if (!/\b(https?|ftp|file):\/\/[\-A-Za-z0-9+&@#\/%?=~_|!:,.;]*[\-A-Za-z0-9+&@#\/%=~_|]/.test(pole.val())) {
        pole.addClass("podkresl");
        pole.val(blad);
    }


    if ($(":input").hasClass("podkresl")) {
        return false;
    } else {
      if (zglosip() == true) {
          return true
      }
    }
});

As you have already found out, I had tried to return true of the submit() function after the zglosIp() returned true (the if statement at bottom of the script). This did not work unfortunately, I have also tried calling zglosip() with separate function{return true} in it but surely I have not used it properly. Please help me.

like image 829
Grzegorz G. Avatar asked Jul 26 '13 15:07

Grzegorz G.


People also ask

Does ajax wait for response?

ajax() function with the default settings, any JavaScript code after this AJAX request will be executed without waiting for a response. In most cases, this is the desired behavior, but there are some situations where you will want to prevent further execution until there has been a response to the AJAX call.

Can we submit form using ajax?

We can submit a form by ajax using submit button and by mentioning the values of the following parameters. type: It is used to specify the type of request. url: It is used to specify the URL to send the request to. data: It is used to specify data to be sent to the server.

What is the difference between ajax and form submit?

A standard form submit sends a new HTTP request (POST or GET) and loads the new page in the browser. In Ajax, the data is sent to the server (POST or GET) in the background, without affecting the page at all, and the response is then received by javascript in the background, again without affecting the page at all.


1 Answers

You want to first ensure the form is not being submitted, then run your ajax call, and if the call is successful, proceed to submit. Note I removed the ajax call from zgoslip and put it in the submit handler for the form. you can restructure it the way you want:

$('form').submit(function(e) { 

     // this code prevents form from actually being submitted
     e.preventDefault();
     e.returnValue = false;

     // some validation code here: if valid, add podkres1 class

     if ($('input.podkres1').length > 0) { 
        // do nothing
     } else {

        var $form = $(this);

        // this is the important part. you want to submit
        // the form but only after the ajax call is completed
         $.ajax({ 
             type: 'post',
             url: someUrl, 
             context: $form, // context will be "this" in your handlers
             success: function() { // your success handler
             },
             error: function() { // your error handler
             },
             complete: function() { 
                // make sure that you are no longer handling the submit event; clear handler
                this.off('submit');
                // actually submit the form
                this.submit();
             }
         });
     }
});
like image 77
quekshuy Avatar answered Sep 19 '22 18:09

quekshuy