king bla king bla - 1 year ago 206
Javascript Question

Javascript function img.onload doesn't return anything(true or false)

function getMeta() {
var img = new Image();
var verif = true;
img.onload = function() {
if (this.width != 468 && this.height != 60) {
alert('error : only these image sizes are accepted : 468x60');
return false;
} else
alert('loaded successfully');
img.onerror = function() {
alert('error : this is not a valid image');
return false;
img.src = document.getElementById('t1').value;
return true;

<form action=""
method="post" target="_blank" id="form1"
onsubmit="return getMeta();">

function img.onload won't return anything
I need a return value of true or false.

I want to use the return value in onsubmit of the form.
could anyone help me?

Answer Source

For general reference, you should go read How do I return the response from an asynchronous call?. This describes the general issue of obtaining an async result. After reading that, you will hopefully understand why you can't just return a value from .onload() and expect that to be the return value from getMeta(). But, that answer by itself doesn't offer a full solution to your specific issue.

So, now lets describe in a bit more detail what's going on in your code and then discuss an option for fixing it.

img.onload is asynchronous. That means it finishes sometime, long after getMeta() has already returned.

Meanwhile, you're trying to do this:

onsubmit="return getMeta();"

Which makes it look like you're trying to use an async result to determine whether the form should submit or not. That simply can't be done that way. The async result is not yet known and your getMeta() function always returns true.

You can restructure your code so that it never submits synchronously. You load the image and, only when the image loads, do you either display an error to the user or manually submit the form. This has potential user interface issues because the user hits the submit button and nothing happens immediately (because you're loading the image to validate). This leaves the user wondering what's going on. They will often think it didn't work and either press the submit button again or think it's just broken. So, you typically need a bunch of UI around this to disable the button, provide feedback that you're verifying the image now, then provide an appropriate error message if the image doesn't verify and often other UI controls should be disabled while you're verifying the image so the user doesn't go off and do other things while you're in the middle of trying to decide if you're going to submit this form or not.

So, to fix the submit:

In your onsubmit handler, you would always return false so the form never submits immediately. Then, in the onload() handler (after the image has loaded), you would manually submit the form or show an error.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download