Hi Everyone!

I am trying to use a $.post call in jQuery to check a user's credentials before submitting a form (so I can show errors without reloading the page), but I've run into a problem. I know why it is, because AJAX is not synchronous, but I just can't figure out how to do it.

In my code the script I'm making the call to returns "valid" or "invalid". If the return is "valid", I want to submit the form, if not, show an error message. Here is a simplified version:

$("#my_form").submit( function () {

	some_value = "username"

	$.post(script_location, {data : some_value}, function (data)  {
		response = data
	})
	
	if (response == "valid") {
		return true
	}
	
	else {
		$(".error").show()
		return false
	}

})

This obviously does not work because code is executed quickly one after another and the variable "response" is not yet set when the execution gets to the if statement, since it is set sometime later, asynchronously.

I looked into using functions, callbacks, but nothing seems to work properly, I always run into the same issue. This is probably really simple, i just a complete dunce, please do let me know what is the standard way of doing this properly.

From the jQuery site:

$.post("test.php", { name: "John", time: "2pm" },
   function(data){
     process(data);
   }, "xml");

Try wrapping your if statement in a function, then calling this function and passing 'data' to it within the success function in the .post:

$.post(script_location, {data : some_value}, function (data)  {
	my_function(data);
});

function my_function(response) {
  if (response == "valid") {
  } else  {
  }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.