user2889046 user2889046 - 5 months ago 22
jQuery Question

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

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?

Answer

Your function returns way before the request might gets fulfilled hence return sends an undefined since no value exists in it. To test it, try to put a default value in your error variable.

Why ?

Since its an async http call, the server might take time to respond but since you return from outside the success and error callback, the return happens before your call(GET) executes and hence no value has been set to it so its an undefined value there.

Try to put a default value to your error to know more about it.

var error = "blah";

  $.get(url, function() { 
    error = false;
  }).fail(function() {
    error = "URL is invalid";
  });
  return error;

A better way

As here you have each function doing its own task and its more readable.

function doAjax(url, successCallback, failureCallback) {

    $.get(url, function() { 
        error = false;
        successCallback(error);
      }).fail(function() {
        error = "URL is invalid";
        failureCallback(error);
      });

}

function successCallback(errorString){
  //do something here, but be happy as it executed well :D
}

function errorCallback (errorString) {
 //do something here, be sad because it didn't
}

doAjax("http://google.com",successCallback, errorCallback);