I know this has been covered so much but I'm a little out of my depth here and I just need someone to explain how to do this in a way I can understand.
I'm looking to submit an HTML form via the AJAX function in jQuery which then instantly sends the form data over to my PHP script. My PHP script then needs to gather that data and assign to variables etc. The PHP script then does a load of other crap and finally echos out some results based upon that data entered.
Once that's done, I want that echo'd data to appear on the same page as the HTML form.
What I don't understand is how to gather the response from the PHP file so that I can then output it on the form page.
I tried using the (res) argument that someone posted here: PHP + jQuery + Ajax form submission - return results on the same page which from what I can see is along the right lines of what I'm trying to achieve but it was outputting the entire PHP file (the actual php code itself) and not my single echo.
Any help is much appreciated!
Thanks.
You simply need to set a $.get()
or $.post()
query.
Give the form an ID in your HTML:
<form id="ajaxquery" method="post" action="">
<label for="field">Type Something:</label>
<input type="text" name="field" id="field" value="" />
<input type="submit" value="Send to AJAX" />
</form>
<div id="success"></div>
Then in your JS:
$("#ajaxquery").live( "submit" , function(){
// Intercept the form submission
var formdata = $(this).serialize(); // Serialize all form data
// Post data to your PHP processing script
$.post( "/path/to/your.php", formdata, function( data ) {
// Act upon the data returned, setting it to #success <div>
$("#success").html ( data );
});
return false; // Prevent the form from actually submitting
});
Then in your PHP:
<?php
// Process form data
echo '<strong>You submitted to me:</strong><br/>';
print_r( $_REQUEST );
Anything echo()'d will be returned to the $.post() function as data
Have an $.ajax(); call using jquery to submit the page and in success (when the PHP code runs) return json string and contain an element containing status:true or something like then call a function (in jquery success) which gets results from another php page and displays instantly
JQuery's get function will allow you to pass in a function that will be called on the requests on success.
jQuery.get( url [, data] [, success(data, textStatus, jqXHR)] [, dataType] )
Anyway, if your actual code is fully displayed, there are few reasons I can think of:
A. Wrong server configuration/php compiler - your server can not process the php page as a script file and outputs it as a text.
B. Your code is written not correctly (mostly, when on the server short tags like <?
are disabled and you need to write <?php
) so your server does not accept this as a script.