I want to submit a form by php ajax and trying to keep things simple, but they are inevitably complicated.
pageA.php is just a form.
pageB.php is validating and processing code. On top of this page I created $_SESSION['message'] = ""; and if something is wrong, at the end of page this could be $_SESSION['message'] = "Password is too short"; – for example.
This message I want to display on pageA.php – inside a div #message.
Sessions are started on top of both pages (session_start();
On pageA I also have a spinner gif, which is hidden by default (display:none;), but it should be visible during (and just during) form processing.
pageA.php
<form id="formReg" action="pageB.php" method="post">
. . .
</form>
<img id="spinn" src="spinn.gif" />
<div id="message"></div>
<button id="sub">Register</button>
JS at the bottom of pageA:
$("#sub").click( function() {
$("#spinn").show(); // it seems this works, but very shortly
$.post( $("#formReg").attr("action"), $("#formReg").serialize()); // this works (data are stored in the table).
$("#formReg :input").val(''); //this works
$("#spinn").hide();
$("#message").html($_Session["message"]); // doesn't work, of course.
});
At the bottom of pageB.php I have:
header("Location: pageA.php");, to keep visitors on pageA.
First: All actions which should happen after the form submit must be placed in a callback function passed to
$.post(). AJAX functions return immediately, therefore the spinner will be hidden shortly after it is shown. Do it like this:That way, the code in the callback function gets executed as soon as the post request returns, not after the
$.postcall returns (which merely starts the request, but doesn’t wait for it’s completion).Regarding displaying the message: Your
pageB.phpdoesn’t have to redirect, as it is only invoked via AJAX. So the client’s browser will never leavepageA.phpafter opening it. The AJAX call is a separate HTTP request, which doesn’t affect the page currently open. To return the value, you have to simply output it onpageB– thedataparameter of the callback function defined above will contain it. If you want to keep it simple, just do:If you need to pass more than one item to your AJAX callback, take a look at JSON.