codeigniter ajax loader error - javascript

I have a problem with my ajax loader in CI.
This is what I have tried so far:
<script type="application/javascript">
$(document).ready(function() {
$('#submit').click(function() {
var form_data = {
username : $('.username').val(),
password : $('.password').val(),
};
var loader = $('<img/>', {
'src':'assets/img/ajax-loader.gif',
'id':'message'
});
loader.insertAfter($(this));
//.removeClass().addClass('loader').html('<img src="assets/img/ajax-loader.gif">').fadeIn(1000);
$.ajax({ //
url: "<?php echo site_url('login/ajax_check'); ?>",
type: 'POST',
async : false,
data: form_data,
success: function(msg) {
$('#ajax_loader').remove();
$('#message').html(msg);
}
});
return false;
});
});
</script>
c_login.php controller
function ajax_check() {
//if($this->input->post('ajax') == '1') {
if($this->input->is_ajax_request()){
$this->form_validation->set_rules('username', 'username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'password', 'trim|required|xss_clean');
$this->form_validation->set_message('required', 'Please fill in the fields');
if($this->form_validation->run() == FALSE) {
echo validation_errors();
} else {
$this->load->model('m_access');
$user = $this->m_access->check_user($this->input->post('username'),$this->input->post('password'));
if($user) {
echo 'login successful';
//echo '<img src="assets/img/loader-bar.gif"> Hello!';
//$this->load->view('welcome');
} else {
echo 'unknown user'; //
//echo ' <img src="assets/img/icon_error.gif"> Username or password not valid';
}
}
}
}
UPDATE:
The problem is, it's just displaying the loader infinitely.
What I want to do is, if the user is valid, will show the loader.gif and then redirect to main page else will display the username or password incorrect. What is wrong with my code? Any ideas? Thanks.

It seems that you named your loader as "message" instead of creating a "message" new element and name your loader as "ajax_loader".
var loader = $('<img/>', {
'src':'assets/img/ajax-loader.gif',
'id':'ajax_loader'
});
var message = ...
...
'id':'message'
.
success: function(msg) {
$('#ajax_loader').remove();
$('#message').html(msg);
}

Related

i want to update the flashdata on every ajax call

In my Web Application, I want to get an error message on every ajax call.
I m using CodeIgniter using I preferred to use flashdata for this purpose I came to know that flashdata don't update until the refresh
here is my ajax code
$.ajax({
url: '<?php echo base_url();?>Auth/userlogin',
type: 'POST',
data: {
email: email,
password:password
},
dataType: 'text',
success: function(data) {
var error="<?php echo $this->session->flashdata('signup'); ?>"
if(data=='no'){
$('#loginerror').html('<div class="alert alert-danger">'+error+'</div>');
}else{
$('#loginerror').html(' ');
$('#login').hide();
location.reload();
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("some error");
}
});
And here is my Controller Where I m setting Flashdata
$this->form_validation->set_rules('email', 'email', 'trim|required|valid_email');
$this->form_validation->set_rules('password', 'Password', 'trim|required');
if ($this->form_validation->run()==FALSE) {
$this->session->set_flashdata('signup',$this->form_validation->first_error());
echo 'no';
}
I don't see any reason whatsoever of using flash data in ajax cause you already can return any data you need in your response, in your example you can just do this:
if ($this->form_validation->run() == FALSE)
{
$this->json['signup'] = $this->form_validation->first_error();
$this->json['status'] = false;
echo json_encode($this->json);
}
else
{
$this->json['status'] = true;
// your code ....
}
and in your success:
dataType: 'JSON',
success: function(data) {
if(data.status == false) {
$('#loginerror').html('<div class="alert alert-danger">'+data.signup+'</div>');
} else {
$('#loginerror').html(' ');
$('#login').hide();
location.reload();
}
...

Unable to use callback to get response from ajax call

I'm using the jQuery Validator plugin to try to check whether an email address getting entered into the form is unique after an ajax call which passes the email to a script which checks to see if the email is already in the database. I'm using a callback function to try to get the results of the ajax query but the function always returns undefined. I'm not sure what I'm doing wrong. Here is the code:
jQuery.validator.addMethod("unique", function () {
function foo(callback) {
$.ajax({
type: 'POST',
async: true,
url: '/form_processor',
data: 'action=email_validate&email=' + $("#email").val(),
success: callback
});
}
var return_value = foo(function (result) {
if (result !== 'g') {
return false;
} else {
return true;
}
});
alert(return_value);
}, "Email address taken. Choose another.");
If you are using jquery validator, in built method is their to validate, So your validate code will like,
$(document).ready(function(){
$( "#myform" ).validate({
rules: {
email: {
required: true,
email: true,
remote: {
url: "form_processor",
type: "post",
data: {
email: function() {
return $( "#email" ).val();
}
}
}
}
},
messages:
{
email:
{
required: "Please enter your email address.",
remote: "Email already taken"
}
}
});
})
In server side you have to return (print) true or false code will be (if you are using php)
<?php
$email = $_POST['email'];
$query = "SELECT ID FROM users WHERE user_email = "$email" LIMIT 1;";
$results = $mysqli->query($query);
if($results->num_rows == 0)
{
echo "true"; //good to register
}
else
{
echo "false"; //already registered
}
}
else
{
echo "false"; //invalid post var
}
?>

check if email exist in database SQL using codeigniter and AJAX

modal screenshot
i have a form inside bootstrap modal, i want to validate if the email already exist in database. the result direct to the blank page with this thing '{"valid":false,"msg":"Email is already taken"}'. i want the msg appear just like i figure it in screenshot.
View
<?php echo form_open('KulinerControl/isEmailExist', 'id="myform"'); ?>
<div id="msg"> </div>
<input type="text" name="email" id="email" class="input-lg formcontrol">
<button type="submit">Submit</button>
</form>
JS
$(document).ready(function(){
$('#myform').on('submit', function(e) {
var email = $('#email').val();
$.ajax({
type: "POST",
url: "<?php echo base_url()?>KulinerControl/isEmailExist",
dataType: "json",
data: "email="+email,
success: function(data){
if(data.valid){
$('#msg').html(data.msg);
}else{
$('#msg').html(data.msg);
}
}
});
});
});
Controller
function isEmailExist(){
$email = $this->input->post('email');
$exists = $this->KulinerModel->isEmailExist($email);
if($exists){
$msg = array(
'valid' => false,
'msg' => 'Email is already taken');
}else{
$msg = array(
'valid' => true,
'msg' => 'Username is available');
}
echo json_encode($msg);}
update controller
function isEmailExist(){
$email = $this->input->post('email');
$exists = $this->KulinerModel->isEmailExist($email);
if($exists){
echo "Email is already taken !";
}else{
$data = array(
'nama' => $this->input->post('nama'),
'email' => $email,
'password' => md5($this->input->post('password'))
);
$query = $this->KulinerModel->addMember($data);
redirect('/KulinerControl/');
}
}
Thanks in advance
you need to stop submitting your form at first then start checking. then if checking find its ok then submit it. i would use the following
$(document).ready(function(){
$('#myform').on('submit', function(e) {
e.preventDefault(); //<---- stop submiting the forms
var email = $('#email').val();
$.ajax({
type: "POST",
url: "<?php echo base_url()?>KulinerControl/isEmailExist",
dataType: "json",
data: "email="+email,
success: function(data){
if(data.valid){
$('#msg').html(data.msg);
$("#myform").submit(); //<---- submit the forms
}else{
$('#msg').html(data.msg);
}
}
});
});
});
I think real time email checking is better for your situation
<script>
$(document).ready(function(){
$('#email').keyup(function(){
var email = $('#email').val();
$.ajax({
type: "POST",
url: "<?php echo base_url()?>KulinerControl/isEmailExist",
data: "email="+email,
success: function(response){
$('#msg').html(response);
}
});
});
});
</script>
In Your controller
function isEmailExist()
{
$email = $this->input->post('email');
$exists = $this->KulinerModel->isEmailExist($email);
if($exists){
echo "Email is already taken";
}else{
echo "";
}
}
To prevent submitting an easy trick
$(document).ready(function(){
$('#myform').on('submit', function(e) {
if ($.trim($("#msg").val()) === "") {
alert('please choose a different email id');
return false;
}
});
});
change Your Form action controller to this
function dataInsert()
{
$data = array(
'nama' => $this->input->post('nama'),
'email' => $this->input->post('email'),
'password' => md5($this->input->post('password'))
);
$query = $this->KulinerModel->addMember($data);
redirect('/KulinerControl/');
}

Redirecting After a Form Submission

How can I make this form redirect the user to an external site, for example http://amaze.bg, after the user submits the form with the "Register" button and after the form sends the e-mail to antoniya.p#amaze.bg with the entered by the user details?
Here is the PHP code (contact_process.php):
<?php
usleep(500000);
$to = "antoniya.p#amaze.bg";
$author = "";
$email = "";
$comment = "";
$class = "FORM CONTACT ";
if (isset($_POST['input_name']))
$author = $_POST['input_name'];
if (isset($_POST['input_email']))
$email = $_POST['input_email'];
if (isset($_POST['input_class']))
$class = $_POST['input_class'];
if (isset($_POST['input_message']))
$comment = $_POST['input_message'];
$sub="Alumni registration recieved - ".$date1;
$name=$authorlast."< ".$email." >";
$msg = '';
if (#mail($to,$sub,$body,"Content-Type: text/html; charset=iso-8859-1"))
{
$msg = 'Your registration was sent successfully';
//echo '<div class="alert success pngfix">'. $msg .'</div>';
}
else{
$msg = 'Email failed to be sent (mail function not work)';
//echo '<div class="alert error pngfix">'. $msg .'</div>';
}
echo $msg;
?>
And here is the .js part:
jQuery.validator.addMethod(
"math",
function(value, element, params) {
if (value==='')
return false;
return this.optional(element) || value == params[0] + params[1];
},
jQuery.format("Please enter the correct value for {0} + {1}")
);
$('.form-register').validate({
rules: {
input_name: {
minlength: 3,
required: true
},
input_email: {
required: true,
email: true
},
input_message: {
minlength: 0,
required: false
}
,
submitHandler: function(form) {
var a=$('.form-register').serialize();
$.ajax({
type: "POST",
url: "contact_process.php",
data:a,
complete:function(){
},
beforeSend: function() {
},
success: function(data){
if (data=='success') {
$('.form-register').find("input[type=text], textarea").val("");
alert('You have successfully registered. Thank you for being active alumni!');
} else {
alert(data);
}
},
error : function() {
}
});
return false;
}
});
});
Thank you for the help.
After some experiments and help from Charlie I managed to find where and what exactly to add to the code, so that the form sends the information to the server and them redirects the user to another website. The change should be made in the .js file with the addition of the following line:
location = "http://amaze.bg/"
But it should be added under "else" in the .js file, with the "alert" being under "success" for everything to work properly:
success: function(data){
if (data=='success') {
alert(data);
} else {
location = "http://amaze.bg/"
}
},
error : function() {
}
In Your Success Callback, Add location = "http://amaze.bg"
success: function(data) {
// if you echo "success" in your php script when the mail is sent
if (data === 'success') {
$('.form-register').find("input[type=text], textarea").val("");
alert('You have successfully registered. Thank you for being active alumni!');
// Now redirect
location = "http://amaze.bg"
} else {
// if you echo "Some Error Message" from your php script
alert(data);
}
},
Ultimately, You should be sending the proper headers from php so that the success hook in your $.ajax fires on a 200 Status Code and the error hook fires in your $.ajax when a 400 - 500 Status Code is encountered. Please look into HTTP Status Codes and Sending Proper Headers in PHP

Return PHP error when using ajaxForm Jquery Plugin

I'm trying to make a login script that uses ajaxForm and the validate plugin, but if PHP provides an error, it doesn't know. This is my Javascript
$(function login() {
$("#login").validate({ // initialize the plugin
// any other options,
onkeyup: false,
rules: {
email: {
required: true,
email: true
},
password: {
required: true
}
}
});
$('form').ajaxForm({
beforeSend: function() {
return $("#login").valid();
},
success: function() {
window.location="index.php";
},
error: function(e) {
alert(e);
}
});
});
Keep in mind I'm new to JS and there's probably a better way to do this. What I need is, if when the form is submitted but the username or password is wrong, I need it to not redirect, and give the error alert, but this does not work currently. I've googled this before, and checked here and so far have found nothing.
edit: using the below code, it still doesn't work:
JS
$(function login() {
$("#login").validate({ // initialize the plugin
// any other options,
onkeyup: false,
rules: {
email: {
required: true,
email: true
},
password: {
required: true
}
}
});
$("#login").submit(function(e) {
e.preventDefault();
$.ajax({
type : "POST",
dataType : "json",
cache : false,
url : "/doLogin",
data : $(this).serializeArray(),
success : function(result) {
if(result.result == "success"){
window.location = "/index.php";
}else if(result.result == "failure"){
$("#alert").html("Test");
}
},
error : function() {
$("#failure").show();
$(".btn-load").button('reset');
$("#email").focus();
}
});
});
});
HTML
<div class="shadowbar">
<div id="alert"></div>
<form id="login" method="post" action="/doLogin">
<fieldset>
<legend>Log In</legend>
<div class="input-group">
<span class="input-group-addon">E-Mail</span>
<input type="email" class="form-control" name="email" value="" /><br />
</div>
<div class="input-group">
<span class="input-group-addon">Password</span>
<input type="password" class="form-control" name="password" />
</div>
</fieldset>
<input type="submit" class="btn btn-primary" value="Log In" name="submit" />
</form></div>
PHP
public function login() {
global $dbc, $layout;
if(!isset($_SESSION['uid'])){
if(isset($_POST['submit'])){
$username = mysqli_real_escape_string($dbc, trim($_POST['email']));
$password = mysqli_real_escape_string($dbc, trim($_POST['password']));
if(!empty($username) && !empty($password)){
$query = "SELECT uid, email, username, password, hash FROM users WHERE email = '$username' AND password = SHA('$password') AND activated = '1'";
$data = mysqli_query($dbc, $query);
if((mysqli_num_rows($data) === 1)){
$row = mysqli_fetch_array($data);
$_SESSION['uid'] = $row['uid'];
$_SESSION['username'] = $row['username'];
$_SERVER['REMOTE_ADDR'] = isset($_SERVER["HTTP_CF_CONNECTING_IP"]) ? $_SERVER["HTTP_CF_CONNECTING_IP"] : $_SERVER["REMOTE_ADDR"];
$ip = $_SERVER['REMOTE_ADDR'];
$user = $row['uid'];
$query = "UPDATE users SET ip = '$ip' WHERE uid = '$user' ";
mysqli_query($dbc, $query);
setcookie("ID", $row['uid'], time()+3600*24);
setcookie("IP", $ip, time()+3600*24);
setcookie("HASH", $row['hash'], time()+3600*24);
header('Location: /index.php');
exit();
} else {
$error = '<div class="shadowbar">It seems we have run into a problem... Either your username or password are incorrect or you haven\'t activated your account yet.</div>' ;
return $error;
echo "{\"result\":\"failure\"}";
}
} else {
$error = '<div class="shadowbar">You must enter both your username AND password.</div>';
return $error;
$err = "{\"result\":\"failure\"}";
echo json_encode($err);
}
echo "{\"result\":\"success\"}";
}
} else {
echo '{"result":"success"}';
exit();
}
return $error;
}
In your login script, you will need to return errors in json format.
For Example
In your login script, if your query finds a row in the database for that user, echo this:
echo "{\"result\":\"success\"}";
and if it fails:
echo "{\"result\":\"failure\"}";
You then can parse these in JavaScript like so:
$('form').ajaxForm({
beforeSend: function() {
return $("#login").valid();
},
success: function(result) {
if(result.result == "success"){
window.location = "index.php";
}else if(result.result == "failure"){
alert('Failure!');
}
error: function(e) {
alert(e);
}
}
});
Here's an example of an Ajax script I use to log users into my site, you can use this for reference if needed. This is just to help you get an even broader understanding of what I am talking about:
I return more than just a success and failure for various reasons such as user intuitiveness, but the gist is there.
$("#loginForm").bind("submit", function() {
$("#invalid").hide();
$("#disabled").hide();
$("#error").hide();
$("#failure").hide();
$("#blocked").hide();
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
if(email != "" && password != ""){
$.ajax({
type : "POST",
dataType : "json",
cache : false,
url : "/ajax/functions/login",
data : $(this).serializeArray(),
success : function(result) {
if(result.result == "success"){
window.location = "/account";
}else if(result.result == "failure"){
$("#invalid").show();
$(".btn-load").button('reset');
$("#email").focus();
}else if(result.result == "disabled"){
$("#disabled").show();
$(".btn-load").button('reset');
$("#email").focus();
}else if(result.result == "blocked"){
$("#blocked").show();
$(".btn-load").button('reset');
$("#email").focus();
}
},
error : function() {
$("#failure").show();
$(".btn-load").button('reset');
$("#email").focus();
}
});
}else{
$("#error").show();
$(".btn-load").button('reset');
$("#email").focus();
}
return false;
});

Categories