Using Post in a form submission

I am trying to validate a form field using a $.post request and am having an issue with timing because of the synchronous property of the post I assume. If I put in an alert, it works fine because the post has returned in time to stop the form submission. Here is the original way I did it but the form is submitting before I can send the return = false.


$('form#form-oidupdate').submit(function(e) { 
	var srchstr = $('form#form-oidupdate input').val();
	var passdata = {'type': 'availability', 'srchstr': srchstr};
	$.post('/js/p25_oid.php', passdata, function(data) {
	   if (data == 1) {
		   var instr = "<div id=\\"available\\"><span id=\\"availno\\">Not Available</span></div>";
		   $('#available').replaceWith(instr);
		   return false;
	   }
        });
});

Then I tried this but it doesn’t work either. How does this need to be structured to make it work so the post request returns before it continues on? Thanks


$('form#form-oidupdate').submit(function(e) { 
    if (runPostRequest( callbackFn )) {
	return false;
    }
});

function runPostRequest(callback){
	var srchstr = $('form#form-oidupdate input').val();
	var passdata = {'type': 'availability', 'srchstr': srchstr};
	$.post('/js/p25_oid.php', passdata, callback);
}
	
function callbackFn( data ){
	if (data == 1) {
		var instr = "<div id=\\"available\\"><span id=\\"availno\\">Not Available</span></div>";
		$('#available').replaceWith(instr);
                return false;
	}
}


I’ve run into this issue before myself. What I do is cancel the form submit and then resubmit the form after my AJAX request comes back. To do this you will need to set a global flag. Modifying your first version it would be:


var should_submit = false;
$('form#form-oidupdate').submit(function(e) {
    if (should_submit) return true;
    var srchstr = $('form#form-oidupdate input').val();
    var passdata = {'type': 'availability', 'srchstr': srchstr};
    $.post('/js/p25_oid.php', passdata, function(data) {
        if (data == 1) {
            var instr = "<div id=\\"available\\"><span id=\\"availno\\">Not Available</span></div>";
            $('#available').replaceWith(instr);
            return false;
        } else {
            should_submit = true;
            $('form#form-oidupdate').submit();
        }
    });
    return false;
});