I use jquery in almost all websites i make, so now i tried to have some ajax to the forms of my website.
I didn’t use any libraries (i heard there are some libraries for ajax in codeigniter, but i decided to go with this method), so make some jquery functions to take the data from the form and submit it to the controller using jquery’s ajax functions. ($.post in particular). but after writing all the ajax queries i realized that i need a validation also. so saw simple jquery validation and it also have an option to enable ajax. (all my coding just got wasted
). so i used that along with this. so here is the code
At first i made a simple form with the below structure
<form action="<?php echo site_url('user/login');?>" method="POST">
<fieldset>
<legend>User Login:</legend>
<ul>
<li><label for="username">username:</label><input name="username" type="text" id="username" value="" /></li>
<li><label for="password">password:</label><input name="password" type="password" id="password" value="" /></li>
<li><label for="submit">Submit Button:</label> <input class="submit" type="submit" id="ajax_submit" value="Submit" /></li>
</ul>
</fieldset>
</form>
<div id="result"></div>
A few things you need to look in this structure is the “action”, make sure you have an action specified in-order to submit the data of the form or to work even if javascript is disabled. And also the “id” of the submit button, we are listening to the click on this submit button, so make sure you have the id is “ajax_submit”.
Now we have some jquery to help us with that submission.
<script type="text/javascript">
$(function() {
$('#ajax_submit').closest('form').simpleValidate({
errorElement: 'em',
ajaxRequest: true,
completeCallback: function(validated_data) {
var formData = validated_data.serialize();
$.post(
$('#ajax_submit').closest('form').attr('action'),
formData,
function(data){
$('#result').html(data);
},
'html'
);
}
});
});
</script>
if anyone need code without validation
<script type="text/javascript">
$(function() {
$('#ajax_submit').click(function(e){
e.preventDefault();
$.post(
$(this).closest('form').attr('action'),
$(this).closest('form').serialize(),
function(data){
$('#result').html(data);
},
'html'
);
});
});
</script>
Load the simple jquery validation and jquery on top of this.
Now whenever user hits the ajax_submit button everything gets passed to the action url and data is loaded to the result div.
Take the data in your controller as usual and echo the result or alert