tags:

views:

47

answers:

1

Hi, I am COMPLETELY not getting this so I'm going to ask. This is for an exercise that I'm using to try and learn JSON and jQuery together. I'm pretty sure that my code is doing everything it's supposed to, but I can't seem to figure out how to a)read the JSON that's being returned and b)be able to use the result afterwards (which I'm guessing will be solved with a ). So the code from the main ASP (Classic) page is:

function validate_email_exists () {
var email = new String($('#txt_email').val());
var sender = "[email protected]";
var validatorURL = "email_validator.asp?email=" + email + "&sender="+ sender;
var obj = jQuery.parseJSON('{"isValid":true}');
$.getJSON(validatorURL);

}

And the page that is being called returns this exactly:

{"isValid":true}

So I've checked and it's valid JSON, but I just can't seem to understand from any tutorials I've found yet how to deal with what comes back. All I want to do is send the "validatorURL" variable to the "email_validator.asp" page and have it tell me if it's valid (isValid=true) or not (isValid=false) and put that response into a variable I can then use on the page. This is driving me crazy, so any help would be great, even pointing me to an example (the jQuery one is beyond me for some reason).

+3  A: 
function validate_email_exists () {
    var email = new String($('#txt_email').val());
    var sender = "[email protected]";
    var validatorURL = "email_validator.asp?email=" + email + "&sender="+ sender;
    $.getJSON(validatorURL, function(response) {
        if(response.isValid) {/* it's valid! */} else {/* not valid */}
    });
}
mattbasta
You should probably add that (because it's async) you can not set a variable in the if/else then try to return it from `validate_email_exists`. Because of that, it may be useful to pass a callback to `validate_email_exists`. The `getJSON` callback would then call that, passing in `response.isValid`.
Matthew Flaschen
Wow, that was fast. Thanks very very much.
stephmoreland
Now that I see this, it makes sense. I just couldn't understand that I had to name the returning value and THEN I could use it. It works perfectly, thanks mattbasta!
stephmoreland