Zorgan
Zorgan

Reputation: 9123

'return false' doesn't end my function

The 2nd bracket in my verifyImageURL() definately triggers as the console logs no.

However, return false doesn't end the function. Everything continues on after that (the AJAX call at the end fires).

Here's my JS:

function verifyImageURL(url, callBack) {
  var img = new Image();
  img.src = url;
  img.onload = function () {
        callBack(true);
  };
  img.onerror = function () {
        callBack(false);
  };
}

$('input#id_imageURL').on('change', function(e) {
    var url = $(this).val();
    console.log(url, url['type']);
    verifyImageURL(url, function (imageExists) {
        if (imageExists === true) {
            console.log('yes');
        } else {
            console.log('no');
            $('.add_file_div h3').html('That URL is not an image');
            return false;
        }
    });

    var formData = new FormData();
    var random_filename = random_string();

    if ( validateYouTubeUrl($(this).val()) ) {
        console.log($(this).val());
        var videoid = url.match(/(?:https?:\/{2})?(?:w{3}\.)?youtu(?:be)?\.(?:com|be)(?:\/watch\?v=|\/)([^\s&]+)/);
        $('.add_file_label').append('<iframe src="https://www.youtube.com/embed/' + videoid[1] + '"' + '</iframe>');
        $('.add_file_div h3').hide();
        $('.add_file_label').css({
            'border-radius': '5px',
            'box-shadow': '5px',

        });
        $('input#id_imageURL').hide();
        $('#delete_preview_image').show();
    }
    else {

        $('.add_file_div h3').hide();
        $('.add_file_label').css({
            'border-radius': '5px',
            'box-shadow': '5px',
        });
        var imagePath = e.currentTarget.value;
        $('.add_file_label').css('background', 'url(' + imagePath + ') scroll no-repeat center/cover');
        $('.add_file_label').css('opacity', '0.4');
        $('.loading_spinner').css('visibility', 'visible');
        $('.add_file_label').append('<input class="temp_s3_url" type="hidden" name="temp_s3_url">');
        $('.temp_s3_url').val(random_filename);
        $('input#id_imageURL').hide();
        $('#delete_preview_image').show();


        formData.append('csrfmiddlewaretoken', $("input[name='csrfmiddlewaretoken']").val());
        formData.append('random_filename', random_filename);
        formData.append('imageURL', imagePath);

        console.log('Entered:', imagePath);
        $.ajax({
            url: '/upload_image/',
            data: formData,
            type: 'POST',
            contentType: false,
            processData: false,
            success: function () {
                $('.add_file_label').css('opacity', '1');
                $('.add_file_label').css('background', 'url(' + imagePath + ') scroll no-repeat center/cover');
                $('.loading_spinner').css('visibility', 'hidden');
            }
        });

    }
});

and idea what the problem is?

Upvotes: 0

Views: 74

Answers (1)

HMR
HMR

Reputation: 39270

Maybe the following code will work, it uses verifyImageUrl as a promise:

function verifyImageURL(url) {
  var img = new Image();
  img.src = url;
  return new Promise(
    function(resolve){
      img.onload = function () {
        resolve(true);
      };
      img.onerror = function () {
        resolve(false);
      };    
    }
  )
}

$('input#id_imageURL').on('change', function (e) {
  var $this = $(this);
  var url = $this.val();
  console.log(url, url['type']);
  verifyImageURL(url)
  .then(function (imageExists) {
    if (imageExists === true) {
      console.log('yes');
    } else {
      console.log('no');
      $('.add_file_div h3').html('That URL is not an image');
      return false;
    }

    var formData = new FormData();
    var random_filename = random_string();

    if (validateYouTubeUrl($this.val())) {
      console.log($this.val());
      var videoid = url.match(/(?:https?:\/{2})?(?:w{3}\.)?youtu(?:be)?\.(?:com|be)(?:\/watch\?v=|\/)([^\s&]+)/);
      $('.add_file_label').append('<iframe src="https://www.youtube.com/embed/' + videoid[1] + '"' + '</iframe>');
      $('.add_file_div h3').hide();
      $('.add_file_label').css({
        'border-radius': '5px',
        'box-shadow': '5px',

      });
      $('input#id_imageURL').hide();
      $('#delete_preview_image').show();
    }
    else {

      $('.add_file_div h3').hide();
      $('.add_file_label').css({
        'border-radius': '5px',
        'box-shadow': '5px',
      });
      var imagePath = e.currentTarget.value;
      $('.add_file_label').css('background', 'url(' + imagePath + ') scroll no-repeat center/cover');
      $('.add_file_label').css('opacity', '0.4');
      $('.loading_spinner').css('visibility', 'visible');
      $('.add_file_label').append('<input class="temp_s3_url" type="hidden" name="temp_s3_url">');
      $('.temp_s3_url').val(random_filename);
      $('input#id_imageURL').hide();
      $('#delete_preview_image').show();


      formData.append('csrfmiddlewaretoken', $("input[name='csrfmiddlewaretoken']").val());
      formData.append('random_filename', random_filename);
      formData.append('imageURL', imagePath);

      console.log('Entered:', imagePath);
      return $.ajax({
        url: '/upload_image/',
        data: formData,
        type: 'POST',
        contentType: false,
        processData: false,
      }).then(
        function () {
          $('.add_file_label').css('opacity', '1');
          $('.add_file_label').css('background', 'url(' + imagePath + ') scroll no-repeat center/cover');
          $('.loading_spinner').css('visibility', 'hidden');
        }
      );
    }
  }).catch(
    function(error){
      console.error("There was an error:",error);
    }
  );
});

Your function seems to be a bit long, maybe you should split it up in smaller functions like hideFileInput.

Upvotes: 1

Related Questions