0

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

1
  • As well as having to use a callback function in getJSON, as posted by Matthew, you should also lose the new String(): val() already returns a string, and new String() does something you never ever want in JS. Also when creating URLs, you must use encodeURLComponent() over values being inserted as query or path components, like the email and sender variables. Commented Aug 8, 2010 at 1:21

1 Answer 1

3
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 */}
    });
}
Sign up to request clarification or add additional context in comments.

3 Comments

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.
Wow, that was fast. Thanks very very much.
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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.