Im trying to use jquery and ajax to submit a form and show the results without reloading. Like your typical ajax commenting setup.
My HTML is setup like this:
<form id="create_new_heading" action="/display.php?brand=1" method="post">
<label for="entry">Heading:</label><br/>
<input type="text" id="heading" name="heading" maxlength="150"/><br/>
<input type="submit" value="Add this Heading" />
</form>
<div id="result">
</div>
JS:
<script>
/* attach a submit handler to the form */
$("#create_new_heading").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $( this ),
term = $form.find( 'input[name="heading"]' ).val(),
url = $form.attr( 'action' );
/* Send the data using post and put the results in a div */
$.post( url, { s: term },
function( data ) {
var content = $( data ).find( '#test_me' );
$( "#result" ).empty().append( content );
}
);
});
</script>
Form Processor looks like this:
public function write($p) {
if ( $_POST['type'] )
$type = mysql_real_escape_string($_POST['type']);
if ( $_POST['heading'])
$heading = mysql_real_escape_string($_POST['heading']);
if ( $type && $heading ) {
$uniqueid = uniqid();
$sql = "INSERT INTO headings VALUES('$type','$heading','$uniqueid')";
return mysql_query($sql);
} else {
return false;
}
}
I attempted to follow the jquery documentation for implementing this but I can’t seem to get it to work. The form submits, and the entry gets put into the database but I still have to refresh the page to see the new entry. Any idea of what I am doing wrong?
Can you check on firebug, whether caching is screwing the request.
I had a similar problem and started giving a random_id along with the param and
it worked fine.
Proper way could be enable Cache-Control header (or) setting a past time as expiry time.