0

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?

girbic
  • 301
  • 3
  • 11

1 Answers1

3

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);
cafebabe1991
  • 4,928
  • 2
  • 34
  • 42
  • Would be nice if you can add a sample to resolve the issue. – Jules Jun 23 '16 at 04:22
  • @Jules Done, thanks :) – cafebabe1991 Jun 23 '16 at 04:29
  • Hey, I've actually tried doing this and I'm still having trouble setting error to either `false` or the string `URL is invalid`. Say in your example I set the doAjax call to a variable v like so `var v = doAjax(...)`. What do I need to do so that this function call returns either false, or the string "URL is invalid". It still returns undefined for me. – girbic Jun 23 '16 at 08:18
  • You will get the result of the ajax inside the callback functions because the call is asynchronous and they are the only means to achieve that. If you want to be able to get the result right there, then it should be a synchronous call (which would freeze the browser ie: waits till the response is available and returns you a true or false whatever you need. Read this answer to know more about it. http://stackoverflow.com/a/5316755/1270865 – cafebabe1991 Jun 23 '16 at 09:03
  • So basically it's not really possible to return a value based on whether the Ajax call worked or not because whatever variable you try to set that value to, it will be evaluated as undefined before it can be assigned a value based on the asynchronous call? – girbic Jun 23 '16 at 10:04
  • Yes, that is how an asynchronous call works. – cafebabe1991 Jun 23 '16 at 10:14