i have a form (made through codeigniter) that i want to submit with ajax onClick. Form submits without Ajax and doesnt let me do event.preventDefault();
jQuery file
$('#register_submit').click(function(e){//
e.preventDefault();
var first_name = $('#register_form1').val();
$.ajax({
type: "POST",
async: false,
url: base_url+"register/registration_val",
data: "register_first_name="+first_name,
success: function(data){
$('#inferiz').html(data);
},
error: function(){alert('error');}
});
});
// Controller works just fine. name register, function that i POST to is registration_val
HTML file
<form method="POST" action='<?php echo site_url('/register/registration_val'); ?>' id='register_form' >
<input type="login" name="register_first_name" id="register_form1">
<input type='submit' value="Register" id='register_submit'>
</form>
Problem is, when I click on SUBMIT button, jQuery doesnt do its work, instead, form submits itself to the controller and gives out an ERROR message.
I cannot prevent the form from submitting (which i think would solve the problem), the Click event is completely ignored. Thanks in advance
Try your luck with the submit
event instead of click
:
$('form').submit(function(e){//
e.preventDefault();
var first_name = $('#register_form1').val();
$.ajax({
type: "POST",
async: false,
url: base_url+"register/registration_val",
data: "register_first_name="+first_name,
success: function(data){
$('#inferiz').html(data);
},
error: function(){alert('error');}
});
});
If the from has an id
replace 'form'
with '#{formId}'
.
Notes:
Like with this:
$('body').on('submit', 'form', function(e){
e.preventDefault();
var first_name = $('#register_form1').val();
$.ajax({
type: "POST",
async: false,
url: base_url+"register/registration_val",
data: "register_first_name="+first_name,
success: function(data){
$('#inferiz').html(data);
},
error: function(){alert('error');}
});
});
Just replace body
with a closer static element (if there is one) to enhance performance.
Good Luck!
if you put return false;
to the end of click event, it should not submit your form to controller..
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.