00 Votes

jQuery: Set event.preventDefault within GET or POST Request

Question by Axuter | 2016-11-06 at 19:29

I have a submit form on my page which only should be submitted if a specific condition is met.

The problem is that this condition is not yet fixed at the time of executing the script. Therefore, I want to reload it with a simple jQuery .get() or .post(). Depending on what the result of this reload is, a event.preventDefault should be set (for preventing the submit) or not.

Up to now, I have elaborated the following JavaScript code:

$("#formid").submit(function(event){
    // request
    $.post("script.php",$(this).serialize(),function(msg){
        // prevent submit in case of specific content
        if (msg=='xx') event.preventDefault();
    });
});

However, there is a problem with that code: it is just another working and I have no idea why! If I set the prevenDefault outside the POST (or even GET request, I have tried both), it is working like a charm. But I need it within the POST or GET request, because there is the source of my condition.

Can someone help me and give me an approach for solving the problem?

ReplyPositiveNegative
1Best Answer1 Vote

Just try the following approach in which the .post() is changed to an .ajax() request and async is set to false:

$("#formid").submit(function(event){
   $.ajax({
      type: "POST",
      url: "script.php",
      data: $(this).serialize(),
      async: false,
      success: function(msg) {
        if (msg=='xx') event.preventDefault();
      }
   });
});

The .post() request of jQuery is running asynchronous. That means that the actual script is processed further while the POST or GET request is sent.

Thereby, the form is already submitted before our data arrives and the preventDefault command has no change to be executed.

If we use .ajax() instead, we have the possibility to determine whether the request should be carried out asynchronous or not. With setting async to false, the POST request will be done first - before the code will be executed afterwards. In other words, we are waiting for the data and preventDefault has enough time to run.
2016-11-07 at 13:49

ReplyPositive Negative
Reply

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.