I have a basic form that I would like to submit using ajax, without having to actually reload the page. This is the gist of the code:
<cfif cgi.request_method EQ "post">
<cfdump var="#form#" />
<cfabort />
</cfif>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(function(){
$('#qsSearch').click(function(){
$.post(
'<cfoutput>#cgi.script_name#</cfoutput>',
$('#qsUserForm').serialize(),
function(data){
$('#results').html(data);
}
);
});
});
</script>
</head>
<body>
<form id="qsUserForm">
<table>
<tr>
<th>First Name:</th><td><input id="qsFirstName" name="qsFirstName" type="text" /></td>
<th>Last Name:</th><td><input id="qsLastName" name="qsLastName" type="text" /></td>
<th>Username:</th><td><input id="qsUserName" name="qsUserName" type="text" /></td>
<th>Email:</th><td><input id="qsEmail" name="qsEmail" type="text" /></td>
<th>User ID:</th><td><input id="qsUserID" name="qsUserID" type="text" /></td>
<td><input id="qsSearch" name="qsSearch" type="submit" value="Search" /></td>
</tr>
</table>
</form>
<div id="results"></div>
</body>
</html>
The form dump should be showing up in the “results” div. However, it doesn’t.
Upon debugging with Firebug I noticed that the code is actually executing correctly, and the results are inserted into the results div – however, as soon as the post code exits, it disappears. If I put a breakpoint at the closing parenthesis for the post call, I can see the correct results in the results div – as soon as the code continues it disappears.
I have used code like this often enough before – what is wrong with this simple ajax post?
(I have tried replacing the search button click handler with the form submit handler, but it didn’t change anything.)
Apparently, your form is reloading
You should stop the form from submission using: