samedi 25 juin 2016

Trying to return a value from jQuery.get(), always ends up as being undefined [duplicate]

This question already has an answer here: How do I return the response from an asynchronous call? 15 answers Right now I'm working on form validation w/ jQuery/Javascript, and I have an input where a user can enter a URL. I made a function called urlError that checks to see if the URL exists, which is as follows: var urlErrorExist = urlError("some_url"); function urlError(url) { $.ajaxPrefilter( function (options) { if (options.crossDomain && jQuery.support.cors) { var http = (window.location.protocol === 'http:' ? 'http:' : 'https:'); options.url = http + '//cors-anywhere.herokuapp.com/' + options.url; //options.url = "http://cors.corsproxy.io/url=" + options.url; } }); var error; $.get(url, function() { error = false; }).fail(function() { error = "URL is invalid"; }); return error; } My logic is that if the URL exists, I set the variable error to be false, and if there is an error, set error to the string URL is invalid. In the end I return the value of error, in which case I can test to see if there is an error, and if there is, display the "URL is invalid" string to the page. However, the error variable always ends up as being undefined when I log it to the console. I've tried using alerts to see if the $.get is actually working like so: $.get(url, function() { alert("URL is valid"); }).fail(function() { alert("URL is invalid"); }); } And it works as intended for invalid and valid URLs. Where am I going wrong here?

Aucun commentaire:

Enregistrer un commentaire