jquery ajax modal problem firing validate and submithandler - javascript

Think i'm lost in my code... can't figure out the problem. I have a modal that opens different forms, setting name and id on the form and submit button accordingly, but nothing happens when pressing submit button. My javascript knowledge is limited and based on try and fail and try and fail and try and sometimes achieving results :)
Back to the issue here... The modal opens fine but nothing happens when hitting submit... Nothing visible to me at least...
Hope i have explained my problems ok.
This calls the modal
<span class="stedModal" data-type="sted" title="Legg til sted" style="cursor: pointer"> <i class="fas fa-plus"></i></span>
The modal:
<!-- Modal - Legg til sted -->
<div class="modal fade" id="Modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Legg til sted</h4>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<!-- name and id is set to sendStedForm in the script that calls the modal -->
<form action="javascript: void(0)" name="none" id="none" class="modalForm">
<div class="main"></div>
<!-- addSted.php is inserted here -->
<div class="text-end">
<!-- button name and id is set by the script that calls the modal to submitSted -->
<button type="submit" name="none1" id="none1" class="btn btn-sm btn-info submitButton" ><i class="far fa-trash-alt"></i> Lagre</button>
<button type="button" class="btn btn-sm btn-success" data-bs-dismiss="modal" aria-label="Close"><i class="fas fa-times"></i> Lukk</button>
</div>
</form>
</div>
</div>
</div>
</div>
calls addSted.php
<input type="hidden" name="lag_id" id="slag_id" value="<?= session()->get('lag_id'); ?>">
<div class="container">
<div class="row">
<div class="col">
<div class="form-group">
<label for="sted">Sted<span class="text-danger fw-bold">*</span></label>
<input type="text" name="sted" id="ssted" class="form-control required" placeholder="Sted">
</div>
</div>
</div>
<div class="row">
<div class="col">
<div class="form-group">
<label for="oppmote">Oppmøte<span class="text-danger fw-bold">*</span></label>
<input type="text" name="oppmote" id="soppmote" class="form-control" placeholder="Oppmøtested">
</div>
</div>
</div>
<div class="row mb-3">
<div class="col">
<div class="form-group">
<label for="sted">Oppmøte tid<span class="text-danger fw-bold">*</span><small class="text-muted">Timer før oppdrag starter</small></label>
<input type="text" name="oppmote_tid" id="soppmote_tid" class="form-control" placeholder="Oppmøte tid">
</div>
</div>
</div>
</div>
The scripts
<script>
function goBack() {
window.history.back();
}
$('#alert').hide();
$('.stedModal').click(function() {
var typet = $(this).data('type');
if (typet == 'type') {
var url = '/vakter/ajaxAddType';
$('.modalForm').attr('id', 'sendTypeForm');
$('.modalForm').attr('name', 'sendTypeForm');
$('.submitButton').attr('id', 'submitType');
$('.submitButton').attr('name', 'submitType');
$('.modal-title').html('Legg til Type');
} else if (typet == 'sted') {
var url = '/vakter/ajaxAddSted';
$('.modalForm').attr('id', 'sendStedForm');
$('.modalForm').attr('name', 'sendStedForm');
$('.submitButton').attr('id', 'submitSted');
$('.submitButton').attr('name', 'submitSted');
$('.modal-title').html('Legg til Sted');
}
// AJAX request
$.ajax({
url: url,
type: 'post',
success: function(response){
// Add response in Modal body
$('#alert').hide();
$('.main').html(response);
// Display Modal
$('#Modal').modal('show');
}
});
});
if ($("#sendStedForm").length > 0) {
$("#sendStedForm").validate({
rules: {
sted: {
required: true,
maxlength: 100,
},
oppmote: {
required: true,
maxlength: 100,
},
oppmote_tid: {
pattern: /^[0-9,]+$/,
maxlength: 4,
}
},
messages: {
sted: {
required: "<small class=\"text-danger\">Legg inn sted</small>",
maxlength: "<small class=\"text-danger\">Sted bør ikke være så langt. 100 tegn er maks</small>",
},
oppmote: {
required: "<small class=\"text-danger\">Legg inn en kort beskrivelse</small>",
maxlength: "Beskrivelsen bær ikke være så lang. Maks 100 tegn</small>",
},
oppmote_tid: {
pattern: "<small class=\"text-danger\">Skriv inn ett gyldig nr</small>",
maxlength: "<small class=\"text-danger\">Oppmøte tid er for langt. Maks 3 tegn</small>",
},
},
submitHandler: function(form) {
alert('hi');
$('#submitSted').html('lagrer..');
// var lag_id = $("#slag_id").val();
// var sted = $("#ssted").val();
// var oppmote = $("#soppmote").val();
// var oppmote_tid = $("#soppmote_tid").val();
// if (!oppmote_tid) { oppmote_tid = '0';}
// oppmote_tid = oppmote_tid.replace(/,/g, '.');
$.ajax({
url: "<?php echo base_url('/vakter/ajaxAddSted/post') ?>",
type: "POST",
// data: $('#ajax_form').serialize(),
dataType: "json",
// data: { lag_id : lag_id, sted : sted, oppmote : oppmote, oppmote_tid : oppmote_tid },
data: $('#sendStedForm').serialize(),
success: function( response ) {
console.log(response);
console.log(response.success);
$('#submitSted').html('Submit');
$('#alert').html(response.msg);
$('#alert').addClass(response.typemsg);
$('#alert').show();
// $('#res_message').removeClass('d-none');
// document.getElementById("ajax_form").reset();
// alert("User record updated successfully with ID: "+response.id);
$("#sted").append('<option value="'+ response.id +'">'+ sted + ' - ' + oppmote + ' - ' + oppmote_tid + ' timer</option>')
$('#stedModal').modal('hide');
$('#submitSted').html('<i class="far fa-trash-alt"></i> Lagre');
setTimeout(function(){
$('#alert').hide();
$('#alert').html('');
},10000);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
});
}

Try to wrap the sendStedForm inside a function and call it after the dom actually has the sendStedForm id to work with which is after ajax data is loaded and placed inside html. Although I have not tested this, but I hope this should work.
function goBack() {
window.history.back();
}
$('#alert').hide();
$('.stedModal').click(function() {
var typet = $(this).data('type');
if (typet == 'type') {
var url = '/vakter/ajaxAddType';
$('.modalForm').attr('id', 'sendTypeForm');
$('.modalForm').attr('name', 'sendTypeForm');
$('.submitButton').attr('id', 'submitType');
$('.submitButton').attr('name', 'submitType');
$('.modal-title').html('Legg til Type');
} else if (typet == 'sted') {
var url = '/vakter/ajaxAddSted';
$('.modalForm').attr('id', 'sendStedForm');
$('.modalForm').attr('name', 'sendStedForm');
$('.submitButton').attr('id', 'submitSted');
$('.submitButton').attr('name', 'submitSted');
$('.modal-title').html('Legg til Sted');
}
// AJAX request
$.ajax({
url: url,
type: 'post',
success: function(response){
// Add response in Modal body
$('#alert').hide();
$('.main').html(response);
// Display Modal
$('#Modal').modal('show');
process_sendStedForm();
}
});
});
function process_sendStedForm(){
if ($("#sendStedForm").length > 0) {
$("#sendStedForm").validate({
rules: {
sted: {
required: true,
maxlength: 100,
},
oppmote: {
required: true,
maxlength: 100,
},
oppmote_tid: {
pattern: /^[0-9,]+$/,
maxlength: 4,
}
},
messages: {
sted: {
required: "<small class=\"text-danger\">Legg inn sted</small>",
maxlength: "<small class=\"text-danger\">Sted bør ikke være så langt. 100 tegn er maks</small>",
},
oppmote: {
required: "<small class=\"text-danger\">Legg inn en kort beskrivelse</small>",
maxlength: "Beskrivelsen bær ikke være så lang. Maks 100 tegn</small>",
},
oppmote_tid: {
pattern: "<small class=\"text-danger\">Skriv inn ett gyldig nr</small>",
maxlength: "<small class=\"text-danger\">Oppmøte tid er for langt. Maks 3 tegn</small>",
},
},
submitHandler: function(form) {
alert('hi');
$('#submitSted').html('lagrer..');
// var lag_id = $("#slag_id").val();
// var sted = $("#ssted").val();
// var oppmote = $("#soppmote").val();
// var oppmote_tid = $("#soppmote_tid").val();
// if (!oppmote_tid) { oppmote_tid = '0';}
// oppmote_tid = oppmote_tid.replace(/,/g, '.');
$.ajax({
url: "<?php echo base_url('/vakter/ajaxAddSted/post') ?>",
type: "POST",
// data: $('#ajax_form').serialize(),
dataType: "json",
// data: { lag_id : lag_id, sted : sted, oppmote : oppmote, oppmote_tid : oppmote_tid },
data: $('#sendStedForm').serialize(),
success: function( response ) {
console.log(response);
console.log(response.success);
$('#submitSted').html('Submit');
$('#alert').html(response.msg);
$('#alert').addClass(response.typemsg);
$('#alert').show();
// $('#res_message').removeClass('d-none');
// document.getElementById("ajax_form").reset();
// alert("User record updated successfully with ID: "+response.id);
$("#sted").append('<option value="'+ response.id +'">'+ sted + ' - ' + oppmote + ' - ' + oppmote_tid + ' timer</option>')
$('#stedModal').modal('hide');
$('#submitSted').html('<i class="far fa-trash-alt"></i> Lagre');
setTimeout(function(){
$('#alert').hide();
$('#alert').html('');
},10000);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
});
}
}

Related

form validation codeigniter 3 with ajax always false when update data

hi guys i have problem when update my data using codeigniter and ajax, when update data my form validation always return false.. but when insert data thats work normal. this is my code, i hope someone can help me, thx a lot..
my controller
public function updateFakultas()
{
$id = $this->input->post('id', true);
$fakultas = $this->input->post('fakultas', true);
$this->form_validation->set_rules('fakul', 'Fakultas', 'required');
if ($this->form_validation->run() == FALSE) {
$hasil = [
'error' => true,
'fakultas' => form_error('fakul', '<p class="mt-3 text-danger">', '</p>'),
];
echo json_encode($hasil);
} else {
$this->Fakultas_model->updateData($id, $fakultas);
$hasil = [
'error' => false
];
echo json_encode($hasil);
}
}
ajax
$('#data_fakultas').on('click', '.item_edit', function() {
var id = $(this).attr('data');
$('#id_fakultas').val("");
$('#fakultas2').val("");
$('#fakultas_error2').html("");
$.ajax({
type: 'POST',
url: '<?= base_url() ?>fakultas/getFakultas',
data: {
id: id
},
dataType: 'json',
success: function(data) {
$('#ModalUbahFakultas').modal('show');
$('[name="id"]').val(data[0].id_fakultas);
$('[name="fakul"]').val(data[0].nama_fakultas);
}
})
})
$('#ubah-fakultas').on('click', function() {
var id = $('#id_fakultas').val();
var fakultas = $('#fakultas2').val();
$.ajax({
type: 'post',
url: '<?= base_url() ?>fakultas/updateFakultas',
data: {
id: id,
fakultas: fakultas
},
dataType: 'json',
success: function(data) {
console.log(data);
if (data.error == false) {
$('#ModalUbahFakultas').modal('hide');
swal("Good Job!", "Data berhasil diubah", "success");
$('#fakultas_error2').html("");
$('#fakultas2').val("");
tampil_data_fakultas();
} else {
$('#fakultas_error2').html(data.fakultas);
$('#fakultas2').on('keyup', function() {
$('#fakultas_error2').html("");
})
}
}
})
})
my view
<div class="modal fade" id="ModalUbahFakultas" tabindex="-1" role="dialog" aria-labelledby="UbahLabelFakultas" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="UbahLabelFakultas">Form Ubah Fakultas</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form class="form-horizontal">
<input type="hidden" id="id_fakultas" name="id">
<div class="form-group">
<label for="fakultas2">Nama Fakultas</label>
<input type="text" class="form-control" id="fakultas2" name="fakul">
<div id="fakultas_error2"></div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Tutup</button>
<button type="submit" class="btn btn-primary" id="ubah-fakultas">Update Data</button>
</div>
</div>
</div>
</div>
i already try to console when ajax post, its fine but i think this problem with form_validation->run()..
you are making a silly mistake while setting validation rule.
your code
$this->form_validation->set_rules('fakul', 'Fakultas', 'required');
Change to
$this->form_validation->set_rules('fakultas', 'Fakultas', 'required');
Your mistaking post variable name "fakultas" with "fakul" while making an Ajax post.
Check your Javascript code
$.ajax({
type: 'post',
url: '<?= base_url() ?>fakultas/updateFakultas',
data: {
id: id,
fakultas: fakultas
},
dataType: 'json',
success: function(data) {
console.log(data);
if (data.error == false) {
$('#ModalUbahFakultas').modal('hide');
swal("Good Job!", "Data berhasil diubah", "success");
$('#fakultas_error2').html("");
$('#fakultas2').val("");
tampil_data_fakultas();
} else {
$('#fakultas_error2').html(data.fakultas);
$('#fakultas2').on('keyup', function() {
$('#fakultas_error2').html("");
})
}
}
})

AJAX login form not working properly

I am making a simple portal with a login page but I am stuck at AJAX problem as I am new to AJAX.
I have a file login.php in which there's a simple html form on clicking it will first check the sample credentials in a php file named test.php. But on entering a wrong credentials or no credentials I am using a jgrowl notification to popup in top right corner which shows two types of error first is invalid credentials and second is error. And on successful match it will redirect to index.php file.
Below is my code attached :
<script>
$("#submit").click( function() {
$.post( $("#login-validation").attr("action"),
$("#login-validation :input").serializeArray(),
function(data) {
var x = data;
if(x=="ok"){
$("#submit").html('Signing In ...');
setTimeout(' window.location.href = "index.php"; ',4000);
}
else if(x=="error"){
$.jGrowl("error", {
sticky: false,
position: 'top-right',
theme: 'bg-blue-alt'
});
}
else{
$.jGrowl( x , {
sticky: false,
position: 'top-right',
theme: 'bg-blue-alt'
});
}
});
$("#login-validation").submit( function() {
return false;
});
});
login.php
<form action="test.php" id="login-validation" class="col-md-4 col-sm-5 col-xs-11 col-lg-3 center-margin" method="post">
<h3 class="text-center pad25B font-white text-transform-upr font-size-23"><b>Employee Self Service Login</b></h3>
<div id="login-form" class="content-box bg-default">
<div class="content-box-wrapper pad20A">
<img class="mrg25B center-margin radius-all-100 display-block" src="http://54.255.228.114/budget/assets/image-resources/indiannica.png" alt="" >
<div class="form-group">
<div class="input-group">
<span class="input-group-addon addon-inside bg-gray">
<i class="fa fa-envelope-o" aria-hidden="true"></i>
</span>
<input type="text" class="form-control" id="exampleInputEmail1" placeholder="Enter email" name="email">
</div>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon addon-inside bg-gray">
<i class="fa fa-unlock-alt" aria-hidden="true"></i>
</span>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password" name="password">
</div>
</div>
<div class="form-group">
<button type="submit" id="submit" class="btn btn-block btn-primary">Login</button>
</div>
</form>
test.php
<?php
if($_POST['email']=="123" && $_POST['password']=="123"){
echo 'ok';
}else if($_POST['email']=="456" && $_POST['password']=="456"){
echo 'error';
}else if($_POST['email']=="789" && $_POST['password']=="789"){
echo 'invalid credentials';
}
else{
echo '404';
}?>
I have updated ajax code as well as test.php page
ajax code with datatype json
$("#login-validation").submit( function(e) {
e.preventDefault();
dataVar = { email:$('input[name="email"]').val(), password:$('input[name="password"]').val() }
$.ajax({
type: "POST",
url: "test.php",
data: dataVar,
dataType: "json",
success: function(data) {
var x = data;
console.log(x);
if(data.status=="success"){
$("#submit").html('Signing In ...');
setTimeout(' window.location.href = "index.php"; ',4000);
}
else if(data.status=="error"){
$.jGrowl("error", {
sticky: false,
position: 'top-right',
theme: 'bg-blue-alt'
});
}
else{
$.jGrowl( x , {
sticky: false,
position: 'top-right',
theme: 'bg-blue-alt'
});
}
}
});
});
test.php page which need to respond in json format only
<?php
if($_POST['email']=="123" && $_POST['password']=="123"){
echo json_encode(array('status'=>"success"));
}else if($_POST['email']=="456" && $_POST['password']=="456"){
echo json_encode(array('status'=>"error"));
}else if($_POST['email']=="789" && $_POST['password']=="789"){
echo json_encode(array('status'=>"error"));
}
else{
echo json_encode(array('status'=>"404"));
}?>
Use Script instead of your's
<script type="text/javascript">
$("#login-validation").submit( function(e) {
e.preventDefault();
dataVar = { email:$('input[name="email"]').val(), password:$('input[name="password"]').val() }
$.ajax({
type: "POST",
url: "test.php",
data: dataVar,
dataType: "text",
success: function(data) {
var x = data;
if(x=="ok"){
$("#submit").html('Signing In ...');
setTimeout(' window.location.href = "index.php"; ',4000);
}
else if(x=="error"){
$.jGrowl("error", {
sticky: false,
position: 'top-right',
theme: 'bg-blue-alt'
});
}
else{
$.jGrowl( x , {
sticky: false,
position: 'top-right',
theme: 'bg-blue-alt'
});
}
}
});
});

PHP redirect after form POST

i'm making a download button on my website that opens a modal with a request for password and then if the password is right should take the user to the real download. This is my javascript:
function submit() {
var postData = $("#passwd").serialize();
//alert(postData);
$.ajax({
type: "POST",
url: "http://www.redcraft.it/submit.php",
data: postData,
success: function(redirect) {
alert('Submitted')
}/*,
error: function() {
alert('Failure');
}*/
});
}
and this is my php:
<?php
function redirect() {
$data = $_POST["postData"];
if($data == is_null()) {
echo "Error";
} else {
echo "<script>window.open('http://www.google.com/" + $data + "', '_self')</script>";
}
}
?>
I'm using echo with a js script in php to try different methods to redirect since header() doesn't work. I'm sure the php is correctly called because i've added a row to create a file when the function is called, and the file is correctly generated.
Please, i need your help and don't kill me if i've made some "noobie" errors.
Edit:
This is the html of the modal:
<div class="modal fade bs-modal-sm" tabindex="-1" role="dialog" aria-labelledby="loginModalLabel" aria-hidden="true">
<div class="modal-dialog modal-mediom">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Download mondo RedCraft</h4>
</div>
<div class="modal-body">
<p>Per scaricare il mondo della redcraft inserisci la password che trovi nel video di presentazione del download!</p>
<div class="control-group">
<label class="control-label" for="userid">Password:</label>
<div class="controls">
<input id="passwd" required="" name="passwordinput" type="input" class="form-control input-medium">
</div>
</div>
<div class="control-group">
<label class="control-label" for="confirmsignup"></label>
<div class="controls">
<button id="confirm" onClick="submit()" name="confirmsignup" class="btn btn-primary" data-dismiss="modal">Conferma</button>
</div>
</div>
</div>
</div>
</div>
</div>
just add one div in your html
<div id="outputredirect"></div>
and add below line in your ajax success or replace with your alert
if(redirect == "Error"){
alert(redirect);
} else {
jQuery('#outputredirect').html(redirect);
}
Your javascript code should redirect to the url returned by the php script :
function submit() {
var postData = $("#passwd").serialize();
//alert(postData);
$.ajax({
type: "POST",
url: "http://www.redcraft.it/submit.php",
data: postData,
success: function(redirect) {
location.href(redirect);
}/*,
error: function() {
alert('Failure');
}*/
});
}

Website login with Ajax

Here is a screenshot of the console.I am a beginner in working with json and Ajax and I am trying to write a login for my website, but I don't know why it is not working.
login-register.js
function loginAjax(){
$.post( "login.js", function( data ) {
if(data == 1){
window.location.replace("/sportime.html");
} else {
shakeModal();
}
});
}
login.js
$(document).ready(function()
{
$('#login').click(function()
{
var username=$("#username").val();
var password=$("#password").val();
var dataString = 'username='+username+'&password='+password;
if($.trim(username).length>0 && $.trim(password).length>0)
{
$.ajax({
type: "POST",
url: "ajaxLogin.php",
data: dataString,
cache: false,
beforeSend: function(){ $("#login").val('Connecting...');}
});
}
return false;
});
});
ajaxLogin.php
<?php
include("conectare.php");
session_start();
if(isset($_POST['username']) && isset($_POST['password']))
{
// username and password sent from Form
$username=mysqli_real_escape_string($mysqli,$_POST['username']);
//Here converting passsword into MD5 encryption.
$password=md5(mysqli_real_escape_string($mysqli,$_POST['password']));
$result=mysqli_query($mysqli,"SELECT uid FROM users WHERE username='$username' and password='$password'");
$count=mysqli_num_rows($result);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
// If result matched $username and $password, table row must be 1 row
if($count==1)
{
$_SESSION['login_user']=$row['uid']; //Storing user session value.
echo $row['uid'];
}
}
?>
sportime.php
<?php
session_start();
if(!empty($_SESSION['login_user']))
{
header('Location: sportime-loggedin.php');
}
?>
and this is the modal for the login from sportime.php
<div class="modal fade login" id="loginModal">
<div class="modal-dialog login animated">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Login</h4>
<div class="content text-center"><h5>Use your University credentials</h5></div>
</div>
<div class="modal-body">
<div class="box">
<div class="content">
<div class="error"></div>
<div class="form loginBox">
<form method="post" action="" onsubmit="loginAjax(); return false;" accept-charset="UTF-8">
<input id="email" class="form-control" type="text" placeholder="University ID" name="id">
<input id="password" class="form-control" type="password" placeholder="Password" name="password">
<input class="btn btn-default btn-login" type="submit" value="Login">
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
Why are you trying to post to a js file?
function loginAjax(){
$.post( "login.js", function( data ) {
if(data == 1){
window.location.replace("/sportime.php");
} else {
shakeModal();
}
});
}
Your loginAjax function should look like this
function loginAjax() {
var username = $("#email").val();
var password = $("#password").val();
var dataString = 'username=' + username + '&password=' + password;
if ($.trim(username).length > 0 && $.trim(password).length > 0) {
$.ajax({
type: "POST",
url: "ajaxLogin.php",
data: dataString,
cache: false,
beforeSend: function() {
$("#login").val('Connecting...');
}
}).success(function(data) {
if (parseInt(data) > 1) {
window.location.replace("/sportime.html");
} else {
shakeModal();
}
});
}
return false;
}
EDIT
You have misplaced the ids.
Replace
var username = $("#username").val();
with var username = $("#email").val();

Show hidden div after login error: JQuery and AJAX

I'm using Jquery AJAX to catch login error,
but when i submit a bad login i can't see the div loginError
i searched on http://api.jquery.com
i used this example http://hayageek.com/jquery-ajax-form-submit
Here is my js:
$().ready(function() {
$("#loginForm").validate({
rules: {
email: {
required: true
},
password: {
required: true,
minlength: 6,
maxlength: 20
}
},
messages: {
email: {
required: "Please provide an email"
},
password: {
required: "Please provide a password",
minlength: "Your password must be at least 6 characters long",
maxlength: "Your password must be at most 20 characters long"
}
}
});
$("#loginForm").submit(function(e)
{
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax( {
url : formURL,
type: "POST",
data : postData,
error: function(jqXHR, textStatus, errorThrown) {
$("#loginError").show();
}
});
e.preventDefault();
});
When i remove the e.preventdefault(); i can see briefly this div but my page reload and
the div disappear !
And Here is my form:
<form class="cmxform form-signin" id="loginForm" method="POST" action="">
<fieldset>
<div class="login-wrap">
<h2 class="form-signin-heading"><?php echo lang('login.title')?></h2>
<div id="loginError" class="alert alert-warning" hidden="hidden">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<strong>Oh snap!</strong> <?php echo lang('login.error')?>
</div>
<div class="form-group ">
<label class="control-label" for="femail">Email:</label>
<input class="form-control" type="email" id="femail" name="email" placeholder="<?php echo lang('login.email') ?>" autofocus required>
</div>
<div class="form-group ">
<label class="control-label" for="fpassword">Password:</label>
<input class="form-control" type="password" id="fpassword" name="password" placeholder="<?php echo lang('login.password') ?>" required>
</div>
<label class="control-label checkbox" for="frememberme">
<input type="checkbox" id="frememberme" name="rememberme" value="rememberme"><?php echo lang('login.rememberme')?>
<span class="pull-right"> <?php echo lang('login.forget') ?></span>
</label>
<button class="btn btn-lg btn-block btn-login" type="submit"><?php echo lang('login.login')?></button>
<button type="button" class="btn btn-lg btn-block btn-register"><?php echo lang('login.register')?></button>
<div class="login-social-link">
<p><?php echo lang('login.joinus') ?></p>
<a href="index" class="facebook">
<i class="icon-facebook"></i>Facebook</a>
<a href="index" class="twitter">
<i class="icon-twitter"></i>Twitter</a>
</div>
</div>
</fieldset>
</form>
maybe it come from my CodeIgniter code.
Thank's in advance !
try something like this
$("#loginForm").submit(function(e)
{
e.preventDefault();
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax( {
url : formURL,
type: "POST",
data : postData,
error: function(jqXHR, textStatus, errorThrown) {
$("#loginError").show();
}
});
});
Try this:
$("#loginForm").submit(function (e) {
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url: formURL,
type: "POST",
data: postData,
success: function (response) {
if (response) {
//do stuff if login is correct
} else {
$("#loginError").show();
}
},
error: function (jqXHR, textStatus, errorThrown) {
//$("#loginError").show();
}
});
e.preventDefault();
});
Note: Get the response from server side after database operation. and make changes in IF/ELSE condition as per your requirement

Categories