PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, March 3, 2022

[FIXED] Yii2 - beforeSubmit ajax return value

 March 03, 2022     ajax, jquery, yii, yii2     No comments   

Issue

I am doing an AJAX call in my beforeSubmit() function, as follows:

$('#register-form').on('beforeSubmit', function(event) {
    $.ajax({
        url: url,
        success: function(response) {
            return response.status; // boolean
        }
    });
});

I want the result of the AJAX success function (true or false) to determine the return value of the beforeSubmit() function.

I realise that you can't return within ajax success, I'm also aware a potential solution to this would be to set async: false in my AJAX call, however I know this isn't recommended, so would prefer to try a different solution.

I have tried to implement a "callback" function as detailed in these posts:

ajax return true/false - I have implemented a callback

jQuery: Return data after ajax call success

But I still cannot seem to get it to work.


Solution

I have solved this as follows:

$('#register-form').on('beforeSubmit', function(event) {
    var form = $(this);

    if (!form.hasClass('complete')) {
        $.ajax({
            url: url,
            success: function(response) {
                if (response.status == true) {
                    form.addClass('complete').submit();
                }
            }
        });

        return false;
    }
});

So the beforeSubmit() function only returns false if the form does not have class 'complete'. If it does, it will proceed with default form submission.



Answered By - MAX POWER
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing