Papa Tee
Papa Tee

Reputation: 69

$.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>

Upvotes: 0

Views: 1732

Answers (1)

Roamer-1888
Roamer-1888

Reputation: 19288

$.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.

Upvotes: 3

Related Questions