$.getJSON not responding when inside function

The $.getJSON jquery function in the validateMdn() function is not working when in te function above. But works well when I have it outside a the function. I need it inside the $.getJSON inside a function because I only want the request to get triggered on form submission.

the alert in the function works just fine but also does not work when in the $.getJSON(url, function(returnData) { alert("Hello"); });

Thanks!

<script>
function validateMdn(){

var url ="http://www.example.com/Validate.do?mdn=123456789&type=postpaid";

alert('validate function');

$.getJSON(url, function(returnData) {
  alert("Validity is : "+returnData.isValid+"  Balance is: "+returnData.balance);



});

}




function checkNumber() {

var numb1 = $('[name=ordPhoneNumber]');
var numb2 = $('[name=ordPhoneNumberConfirm]');

isvalid = numb1.val()=== numb2.val();

if(!isvalid){
alert('Number  does not match')

       }

numb2.closest('.input-wrapper').toggleClass('error',!isvalid);
   return isvalid;

}



$(function() {
     $('#topup_form').submit( function() {
         return (checkNumber()&&validateMdn());
     });
});


</script>
<form method="post" name="topup" id="topup" action="https://www.example.com/topup.html">
    <input type="text" name="ordPhoneNumber" id="ordPhoneNumber" maxlength="12" pattern="phone"  required>
    <small class="error invalid"> Error messgae.  </small>

    <input type="text" name="ordPhoneNumberConfirm" id="ordPhoneNumberConfirm" maxlength="12" pattern="phone" required>

    <small class="error invalid"> Error message.  </small>
     <button type="submit" name="submitbutton" class="button blue right">Continue</button>
                <button type="reset" class="button right">Clear</button>
             </form>

Answers


$.getJSON() is asynchronous. To make use of the response in the onsubmit handler, validateMdn() should return a promise. The handler can then use a promise method (.then() or .done()) to access the data.

$(function() {
    function validateMdn() {
        var url ="http://www.example.com/Validate.do?mdn=123456789&type=postpaid";
        alert('validate function');

        //return the promise returned by $.getJSON().then().
        return $.getJSON(url).then(function(returnData) {
            alert("Validity is : " + returnData.isValid + "\nBalance is: " + returnData.balance);
            return returnData;
        });
    }

    function checkNumber() {
        var numb1 = $('[name=ordPhoneNumber]'),
            numb2 = $('[name=ordPhoneNumberConfirm]'),
            isvalid = numb1.val()=== numb2.val();//var
        if(isvalid) {
            numb2.closest('.input-wrapper').removeClass('error');
        } else {
            alert('Number does not match')
            numb2.closest('.input-wrapper').addClass('error');
        }
        return isvalid;
    }

    $('#topup_form').on('submit', function(e) {
        e.preventDefault();//inhibit form submission
        var form = this;
        validateMdn().then(function(returnData) {
            if(checkNumber() && returnData.isValid) {
                form.submit();//submit form only if both validations are successful
            }
        });
    });
});
EDIT

checkNumber() can be called before calling validateMdn(), thus allowing validateMdn() to be called only if the number is valid.

First, modify checkNumber() to return either a valid number or false :

    function checkNumber() {
        var numb1 = $('[name=ordPhoneNumber]'),
            numb2 = $('[name=ordPhoneNumberConfirm]'),
            isvalid = numb1.val()=== numb2.val();//var
        if(isvalid) {
            numb2.closest('.input-wrapper').removeClass('error');
        } else {
            alert('Number does not match')
            numb2.closest('.input-wrapper').addClass('error');
        }
        return isvalid ? numb1 : false;
    }

The value returned by checkNumber() can be tested and passed to validateMdn() :

    $('#topup_form').on('submit', function(e) {
        e.preventDefault();//inhibit form submission
        var form = this,
            number = checkNumber();
        if(number) {//number is either a valid number or `false`
            validateMdn(number).then(function(returnData) {
                if(numberValid && returnData.isValid) {
                    form.submit();//submit form only if both validations are successful
                }
            });
        }
    });

Now all you need to do is modify validateMdn() to accept number as a parameter, and do something with it.


Need Your Help

1 billion unique strings while inserting millions concurrently

mysql database concurrency insert unique

I have over billion unique strings representing usernames and I am adding millions more every few minutes concurrently, over 50% are duplicates. I am currently using a InnoDB table with mySQL. I am...

Detach and Attach div as a dialog in jquery

javascript jquery html dialog jquery-ui-dialog

I have a div with some id that contains some buttons/labels. Its a container itself. I want to have a button that when user clicks on the button a dialog has to appear with the same div but the div...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.