views:

39

answers:

2

I have a function which returns another function which returns a boolean value, on this i do validation which is causing unusual behavior.

The code in the function is as follows:

$.post( "classes/InsertCustomer.php", 
  { iResult: theResult.valid  },
  function(data)
  {
    alert(data);
  }); 
return true;

When this runs, the post happens but doesn't return anything. However, when the last line is "return false" the post executes perfectly and returns the data from the PHP file. No change to the PHP code at all, just the return true and false in the JavaScript.

Is there any sensible reason for this?

+1  A: 

The return value is there to block the event's default action. If you're for example calling this JS function during an onclick of a link or onsubmit of a form, then return true will instruct the link or form element to continue the default action it was asked to do (e.g. following link href or going to form action). Big chance that yours is going to same page and thus basically refreshing the page. Doing return false will block this and you stay at the same page.

In unobtrusive JS you'd often like to return false when you're replacing synchronous actions by asynchronous (ajaxical) actions. For graceful degradation you should however take care that it works as well when JS is disabled (like as when the function returns true), which is currently clearly not the case. Disable JS in your webbrowser and retest. You'd like to have everything to work as well in such situation.

BalusC
Damn, you beat me by 10 minutes. SO was really slow about informing me of new answers. ;-) I've got to give you +1 because you were basically saying the same as me. :)
Chris
A: 

Is this being run on an onsubmit to try to make it do an ajax form submission instead of a "true" one? Your "return true" is not part of the $.post so is likely telling whatever event handler it is in to continue with its default action.

If this is a form submission then the above will cause the form to submit to its default location which may be itself. This may effectively cause it to just reload the page which will cause the event handler waiting for the .post response to get lost.

When you set it to return false it is telling the page to not perform the default action (submitting) so it will stay on the page giving the post compelte event handler time to complete and fire.

Chris