views:

95

answers:

3

I have several php pages that have forms used to submit data. My typical setup is to have the page post to itself so that I can validate the input and if necessary reload the page with the user submitted data (and markup to show where the error is). If everything is OK I redirect to a thank you page.

I would like to start using ajax (jquery) to submit the forms, but have the original php submit to fall back on incase the client is not using javascript. I'm still very new to jquery and have found several examples to submit using jquery but none using the setup I described above. If possible could someone give a brief example or point to a page that does. Thanks

+1  A: 

You can submit POST data with jQuery by using the POST method:

$.post("verify.php", {"name":"jonathan"}, function(results) {
  if (results.response == "ok") {
    alert(results.message);
    $("#form").remove();
  } else {
    alert(results.message);
  }
}, "json");

An example-script may be the following:

if ($_POST["name"] == "jonathan")
{
  print json_encode(array(
    "response" => "ok",
    "message"  => "You have been verified.";
  ));
}
else
{
  print json_encode(array(
    "response" => "fail",
    "message"  => "Your name is incorrect.";
  ));
}
Jonathan Sampson
...and redirection can be performed within the `success` callback using `window.location.href = blah.html`
karim79
+1  A: 

You could possibly use the jquery form plugin here http://jquery.malsup.com/form/

that would be an easy way convert existing pages.

John Boker
A: 

window.location.href = thankyou_page_url in your $.post callback if the response is OK.

BojanG