How to show bootstrap success message in ajax success method ()? - javascript

I am using following jQuery/Ajax method to validate a form. I am passing json data to the php file called add.php. Now If add.php page find any error its showing error message otherwise it's showing success message.
Now, In ajax success method I want to show bootstrap success message class if there is no error otherwise a error message class.
To this line :
$('#form_result').append('<p class="alert alert-danger">'+value+'</p>');
Now I can't determine how to check if the result is success.
Jquery/Ajax Code :
<script type="text/javascript">
$(document).ready(function() {
$("#add_zone").submit(function(e) {
e.preventDefault();
$.ajax({
url : 'add',
data : $(this).serialize(),
dataType : 'json',
type : 'POST',
beforeSend : function () {
$("#submit_button").val("Wait...");
},
success : function ( result ) {
$("#submit_button").val("Add New Zone");
$('#form_result').html('');
$.each( result, function( key, value ) {
if(key !== 'error') {
$('#form_result').append('<p class="alert alert-danger">'+value+'</p>');
}
});
},
});
});
});
</script>
add.php page
if(isset($_POST['form_name']) && $_POST['form_name'] == "zone") {
if(verifyForm('zone', 'add')) {
$msg = array();
$msg['error'] = false;
$zone_name = validate_data($_POST['zone_name']);
$remark = validate_data($_POST['remark']);
$errors = array();
$check = mysqli_query($conn, "SELECT zone_name FROM zone WHERE uid ='$uid' AND zone_name = '$zone_name' ");
$num_check = mysqli_num_rows($check);
if(isset($zone_name, $remark)) {
if(empty($zone_name)) {
$msg[] = 'Zone name required';
$msg['error'] = true;
} elseif($num_check > 0 ) {
$msg[] = 'Zone name already exists, choose another name';
$msg['error'] = true;
}
if(!empty($errors)) {
$msg[] = '<div class="alert alert-danger">';
$msg[] = '<strong>OPPS! Correct the following error(s):</strong><br/>';
foreach($errors as $er) {
$msg[] = $er.'.<br/>';
$msg['error'] = true;
}
$msg[] = '</div>';
}
if(empty($errors) && $msg['error'] === false) {
$insert = mysqli_query($conn, "INSERT INTO zone (zone_name, uid, remark) VALUES('$zone_name', '$uid', '$remark') ");
if($insert) {
$msg[] = 'New zone added.';
} else {
$msg[] = "Can't add new zone.";
$msg['error'] = true;
}
}
}
echo json_encode($msg);
}
}

Don't mix output with error state:
<?php
/**
*/
if(isset($_POST['form_name']) && $_POST['form_name'] == "zone") {
if(verifyForm('zone', 'add')) {
$msg = array();
$msg['error'] = false;
$msg['body'] = [];
$zone_name = validate_data($_POST['zone_name']);
$remark = validate_data($_POST['remark']);
$errors = array();
$check = mysqli_query($conn, "SELECT zone_name FROM zone WHERE uid ='$uid' AND zone_name = '$zone_name' ");
$num_check = mysqli_num_rows($check);
if(isset($zone_name, $remark)) {
if(empty($zone_name)) {
$msg['body'][] = 'Zone name required';
$msg['error'] = true;
} elseif($num_check > 0 ) {
$msg['body'][] = 'Zone name already exists, choose another name';
$msg['error'] = true;
}
if(!empty($errors)) {
$msg['body'][] = '<div class="alert alert-danger">';
$msg['body'][] = '<strong>OPPS! Correct the following error(s):</strong><br/>';
foreach($errors as $er) {
$msg['body'][] = $er.'.<br/>';
$msg['error'] = true;
}
$msg['body'][] = '</div>';
}
if(empty($errors) && $msg['error'] === false) {
$insert = mysqli_query($conn, "INSERT INTO zone (zone_name, uid, remark) VALUES('$zone_name', '$uid', '$remark') ");
if($insert) {
$msg['body'][] = 'New zone added.';
} else {
$msg['body'][] = "Can't add new zone.";
$msg['error'] = true;
}
}
}
$msg['body'] = implode('',$msg['body']);
echo json_encode($msg);
}
}
?>
<script type="text/javascript">
$(document).ready(function() {
$("#add_zone").submit(function(e) {
e.preventDefault();
$.ajax({
url : 'add',
data : $(this).serialize(),
dataType : 'json',
type : 'POST',
beforeSend : function () {
$("#submit_button").val("Wait...");
},
success : function ( result ) {
$("#submit_button").val("Add New Zone");
if (result.error) {
$('#form_result').append('<p class="alert alert-danger">'+result.body+'</p>');
}
else {
$('#form_result') . html(result.body);
}
},
});
});
});
</script>

Related

I can't redirect user after login

I have login page which take username and password from user after user will be login. I am getting response for successfully login. but I can not redirect to index.php.
I am getting console message that User successfully login, But then page is not redirect on other page.
My JS file is like this.
$(document).ready(function() {
//alert('ss');
$("#login-form").submit(function(e){
e.preventDefault();
var username = $("#email").val();
var password = $("#password").val();
var isValid = true;
var re = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(!re.test($("#email").val())){
isValid = false;
$("#message").html("Please enter valid email.");
}
if($('#remember').is(':checked')){
$.cookie('adminCookie', $("#loginUser").val(), { expires: 7 });
}
else{
if($.cookie('adminCookie') == null) {
$.removeCookie("adminCookie");
}
}
if(password == ""){
isValid = false;
$("#message").html("Please enter password.");
}
if(isValid){
$.ajax({
type : "POST",
url : "process/login.php?rand="+Math.random(),
data : {
username : $("#email").val(),
password : $("#password").val(),
}
}).
done(function(response){
//alert(response);
var JSONArray = $.parseJSON(rawJSON);
console.log(response);
if(jsonObj.success=="1"){
window.location("index.php");
}else{
$("#userDiv").addClass("form-group has-error");
$("#passDiv").addClass("form-group has-error");
$("#passWarning").css("display","");
$("#passWarning").html("Invalid User Name or Password");
$.when($('#passWarning').fadeOut(5000)).done(function() {
$("#userDiv").attr('class', 'form-group');
$("#passDiv").attr('class', 'form-group');
});
}
}).fail(function(){
}).always(function() {
});
}
});
});
my PHP file is looks like this.
<?php
include "../connection.php";
extract($_POST);
$data = array();
$resArr = array();
if (isset($_POST['username']) && isset($_POST['password'])) {
$check_user = mysqli_query($conn, "select * from cut_users where email like '$username' and password like '$password' and user_role like 'A'");
if ($check_user) {
if (mysqli_num_rows($check_user) > 0) {
$message = "Login successfully.";
$success = 1;
while ($row = mysqli_fetch_array($check_user)) {
if ($row['is_active'] == "0") {
$message = "Your account is blocked. Please contact admin.";
$success = 0;
}
$data["id"] = $row['cut_users_id'];
$data["name"] = $row['name'];
$data["emailID"] = $row['email'];
$data["device"] = $row['device_type'];
$data["is_reset"] = $row['is_reset'];
$_SESSION['userID'] = $row['cut_users_id'];
$_SESSION['name'] = $row['name'];
$_SESSION['emailID'] = $row['email'];
}
$resArr = array("success" => $success, "data" => $data, "message" => $message);
} else {
$resArr = array("success" => 0, "data" => array(), "message" => "Email or password invalid.");
}
} else {
$resArr = array("success" => 0, "data" => array(), "message" => "Something went wrong!!!" . mysqli_error($conn));
}
} else {
$resArr = array("success" => 0, "data" => array(), "message" => "Parameter Missing");
}
header('Content-Type: application/json');
echo str_replace("\/", "/", json_encode($resArr, JSON_UNESCAPED_UNICODE));
?>
1) Why you are using variable jsonObj instead of response ?
2) Modify your if statement like this
if(response.success==1){
window.location.href="index.php";
}
window.location is not a function it is an object. Please change href property in window.location object to redirect to new url.
window.location.href = "./index.php";
Simple redirect to specific file
if(jsonObj.success==1)
{
window.location.href = "http://www.example.com/index.php";
}

How do I submit form without page reload taking into consideration the php script?

So basically I have to work on this loan calculator loancalc.000webhostapp.com
I have looked at other pages on this site "how to submit form without page reload?" but this isn't completely relevant to what i'm working on. So far i've added this into the jquery part of the page...
jQuery('qis-register').on('submit', 'input', function(){
event.preventDefault();
var name = $("input#yourname").val();
var email = $("input#youremail").val();
if (name == ""){
$("input#yourname").focus;
return false;
}
else{
}
if (email == ""){
$("input#youremail").focus;
return false;
}
});
But i'm told there is also two other scripts that I need to work with, I'm not really too experienced with php so not sure what's going on, the two php scripts I have to work with are called quick-interest-slider.php and register.php,
//qis_verify_application in register.php
function qis_verify_application(&$values, &$errors) {
$application = qis_get_stored_application();
$register = qis_get_stored_application_messages();
$arr = array_map('array_shift', $application);
foreach ($arr as $key => $value) {
if ($application[$key]['type'] == 'multi') {
$d = explode(",",$application[$key]['options']);
foreach ($d as $item) {
$values[$key] .= $values[$key.$item];
}
}
if ($application[$key]['required'] == 'checked' && $register['use'.$application[$key]['section']] && (empty($values[$key]) || $values[$key] == 'Select...'))
$errors[$key] = 'error';
}
$filenames = array('identityproof','addressproof');
foreach($filenames as $item) {
$tmp_name = $_FILES[$item]['tmp_name'];
$name = $_FILES[$item]['name'];
$size = $_FILES[$item]['size'];
if (file_exists($tmp_name)) {
if ($size > $register['attach_size']) $errors['attach'.$item] = $register['attach_error_size'];
$ext = strtolower(substr(strrchr($name,'.'),1));
if (strpos($register['attach_type'],$ext) === false) $errors['attach'.$item] = $register['attach_error_type'];
}
}
return (count($errors) == 0);
}
//qis_process_application in register.php
function qis_process_application($values) {
global $post;
$content='';
$register = qis_get_stored_register ('default');
$applicationmessages = qis_get_stored_application_messages();
$settings = qis_get_stored_settings();
$auto = qis_get_stored_autoresponder();
$application = qis_get_stored_application();
$message = get_option('qis_messages');
$arr = array_map('array_shift', $application);
if ($message) {
$count = count($message);
for($i = 0; $i <= $count; $i++) {
if ($message[$i]['reference'] == $values['reference']) {
$values['complete'] = 'Completed';
$message[$i] = $values;
update_option('qis_messages',$message);
}
}
}
$filenames = array('identityproof','addressproof');
$attachments = array();
if ( ! function_exists( 'wp_handle_upload' ) ) {
require_once( ABSPATH . 'wp-admin/includes/file.php' );
}
add_filter( 'upload_dir', 'qis_upload_dir' );
$dir = (realpath(WP_CONTENT_DIR . '/uploads/qis/') ? '/uploads/qis/' : '/uploads/');
foreach($filenames as $item) {
$filename = $_FILES[$item]['tmp_name'];
if (file_exists($filename)) {
$name = $values['reference'].'-'.$_FILES[$item]['name'];
$name = trim(preg_replace('/[^A-Za-z0-9. ]/', '', $name));
$name = str_replace(' ','-',$name);
$_FILES[$item]['name'] = $name;
$uploadedfile = $_FILES[$item];
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
array_push($attachments , WP_CONTENT_DIR .$dir.$name);
}
}
remove_filter( 'upload_dir', 'qis_upload_dir' );
$content = qis_build_complete_message($values,$application,$arr,$register);
qis_send_full_notification ($register,$values,$content,true,$attachments);
qis_send_full_confirmation ($auto,$values,$content,$register);
}
function qis_loop in quick-interest-slider.php
function qis_loop($atts) {
$qppkey = get_option('qpp_key');
if (!$qppkey['authorised']) {
$atts['formheader'] = $atts['loanlabel'] = $atts['termlabel'] = $atts['application'] = $atts['applynow'] = $atts['interestslider'] = $atts['intereselector']= $atts['usecurrencies'] = $atts['usefx'] = $atts['usedownpayment'] = false;
if ($atts['interesttype'] == 'amortization' || $atts['interesttype'] == 'amortisation') $atts['interesttype'] = 'compound';
}
global $post;
// Apply Now Button
if (!empty($_POST['qisapply'])) {
$settings = qis_get_stored_settings();
$formvalues = $_POST;
$url = $settings['applynowaction'];
if ($settings['applynowquery']) $url = $url.'?amount='.$_POST['loan-amount'].'&period='.$_POST['loan-period'];
echo "<p>".__('Redirecting....','quick-interest-slider')."</p><meta http-equiv='refresh' content='0;url=$url' />";
die();
// Application Form
} elseif (!empty($_POST['qissubmit'])) {
$formvalues = $_POST;
$formerrors = array();
if (!qis_verify_form($formvalues, $formerrors)) {
return qis_display($atts,$formvalues, $formerrors,null);
} else {
qis_process_form($formvalues);
$apply = qis_get_stored_application_messages();
if ($apply['enable'] || $atts['parttwo']) return qis_display_application($formvalues,array(),'checked');
else return qis_display($atts,$formvalues, array(),'checked');
}
// Part 2 Application
} elseif (!empty($_POST['part2submit'])) {
$formvalues = $_POST;
$formerrors = array();
if (!qis_verify_application($formvalues, $formerrors)) {
return qis_display_application($formvalues, $formerrors,null);
} else {
qis_process_application($formvalues);
return qis_display_result($formvalues);
}
// Default Display
} else {
$formname = $atts['formname'] == 'alternate' ? 'alternate' : '';
$settings = qis_get_stored_settings();
$values = qis_get_stored_register($formname);
$values['formname'] = $formname;
$arr = explode(",",$settings['interestdropdownvalues']);
$values['interestdropdown'] = $arr[0];
$digit1 = mt_rand(1,10);
$digit2 = mt_rand(1,10);
if( $digit2 >= $digit1 ) {
$values['thesum'] = "$digit1 + $digit2";
$values['answer'] = $digit1 + $digit2;
} else {
$values['thesum'] = "$digit1 - $digit2";
$values['answer'] = $digit1 - $digit2;
}
return qis_display($atts,$values ,array(),null);
}
}
Do I have to edit any of the php and I also don't know what I have to write considering the php.
You can use what is called Ajax to submit the data to the server via POST.
Create a button and give it a class of qis-register, then give each of your input fields a class that matches it's name. Then just add that field to the data object that I have following the format within it.
jQuery(document).on('click', '.qis-register', function(){
var name = $("input#yourname").val();
var email = $("input#youremail").val();
if (name == ""){
$("input#yourname").focus;
}
else if (email == ""){
$("input#youremail").focus;
}
else{
jQuery.ajax({
type: "POST",
url: "your_php_here.php",
data: {
name:name,
email:email,
qissubmit:$(".qissubmit").val(),
qisapply:$(".qisapply").val(),
part2submit:$(".part2submit").val(),
},
done: function(msg){
console.log(msg);
}
});
}
});

Codeigniter jquery not working inside AJAX file upload

I have an AJAX file upload code in codeigniter. The Issue is that I changed the simple form submit to file submit. But After that, JQUERY has stopped working. The response is coming success, but at the same time, ajax error function is called. I don't know what's wrong with my code.
This is my controller.
public function ajax_add() {
$this->_validate();
$config = [
'upload_path' => './assets/game_images/',
'allowed_types' => 'gif|png|jpg|jpeg'
];
$this->load->library('upload', $config);
if ($this->upload->do_upload('image')) {
$file = $this->upload->data();
$file_name = $file['file_name'];
if ($file_name == '') {
$data['error_string'][] = 'Please upload an image.';
$data['status'] = FALSE;
echo json_encode($data);
exit();
}
} else {
$data['inputerror'][] = 'image';
$data['error_string'][] = $this->upload->display_errors();
$data['status'] = FALSE;
echo json_encode($data);
exit();
}
$data = array(
'title' => $this->input->post('title'),
'iframe' => $this->input->post('iframe'),
'status' => $this->input->post('status'),
'category_id' => $this->input->post('category_id'),
//'image' => $file_name
);
$insert = $this->game->save($data);
echo json_encode(array("status" => TRUE));
}
private function _validate() {
$data = array();
$data['error_string'] = array();
$data['inputerror'] = array();
$data['status'] = TRUE;
if ($this->input->post('title') == '') {
$data['inputerror'][] = 'title';
$data['error_string'][] = 'Game Title is required';
$data['status'] = FALSE;
}
if ($this->input->post('iframe') == '') {
$data['inputerror'][] = 'iframe';
$data['error_string'][] = 'Game Iframe is required';
$data['status'] = FALSE;
}
if ($this->input->post('status') == '') {
$data['inputerror'][] = 'status';
$data['error_string'][] = 'Status is required';
$data['status'] = FALSE;
}
if ($this->input->post('category_id') == '') {
$data['inputerror'][] = 'category_id';
$data['error_string'][] = 'Please select category';
$data['status'] = FALSE;
}
if ($data['status'] === FALSE) {
echo json_encode($data);
exit();
}
}
And this is my HTML
if (save_method == 'add') {
url = "<?php echo site_url('game/ajax_add') ?>";
} else {
url = "<?php echo site_url('game/ajax_update') ?>";
}
var formData = new FormData($('#form')[0]);
$.ajax({
url: url,
type: 'JSON',
data: formData,
async: false,
success: function (data)
{
if (data.status) //if success close modal and reload ajax table
{
$('#modal_form').modal('hide');
reload_table();
} else
{
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="' + data.inputerror[i] + '"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
$('[name="' + data.inputerror[i] + '"]').next().text(data.error_string[i]); //select span help-block class set text error string
}
}
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled', false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled', false); //set button enable
},
cache: false,
contentType: false,
processData: false
});
$.ajax({
type: 'POST',
url: url,
dataType: 'JSON',
contentType: 'application/json; charset=utf-8'
})

commands in chatroom & defining words after command

Okay basically I'm trying to have a action happen of alert('hi $message'); when a user enters the command /command lewis into the chatroom; In the alert I have stated the variable $message and this is the word followed by the command; for example /command $message. I have posted my script below; so basically what I'm trying to achieve is recognise when a user types /command followed by a $message into the textarea then perform an action.
Chatroom Javascript
name ='<? echo $chat_room_username; ?>';
$("#name-area").html("You are: <span>" + name + "</span>");
var chat = new Chat();
$(function() {
chat.getState();
// watch textarea for key presses
$("#sendie").keydown(function(event) {
var key = event.which;
//all keys including return.
if (key >= 33) {
var maxLength = $(this).attr("maxlength");
var length = this.value.length;
// don't allow new content if length is maxed out
if (length >= maxLength) {
event.preventDefault();
}
}
});
// watch textarea for release of key press
$('#sendie').keyup(function(e) {
if (e.keyCode == 13) {
var text = $(this).val();
var maxLength = $(this).attr("maxlength");
var length = text.length;
// send
if (length <= maxLength + 1) {
chat.send(text, name);
$(this).val("");
} else {
$(this).val(text.substring(0, maxLength));
}
}
});
});
var instanse = false;
var state;
var mes;
var file;
function Chat () {
this.update = updateChat;
this.send = sendChat;
this.getState = getStateOfChat;
}
//gets the state of the chat
function getStateOfChat(){
if(!instanse){
instanse = true;
$.ajax({
type: "POST",
url: "/rooms/process.php?room=<? echo $room; ?>",
data: {
'function': 'getState',
'file': file
},
dataType: "json",
success: function(data){
state = data.state;
instanse = false;
},
});
}
}
//Updates the chat
function updateChat(){
if(!instanse){
instanse = true;
$.ajax({
type: "POST",
url: "/rooms/process.php?room=<? echo $room; ?>",
data: {
'function': 'update',
'state': state,
'file': file
},
dataType: "json",
success: function(data){
if(data.text){
for (var i = 0; i < data.text.length; i++) {
var newdata = data.text[i].replace(/:brand/g,"<img src=\"/_img/logo1.png\"></img>");
newdata = newdata.replace(/:tipsound/g,"<audio autoplay><source src=\"/tip.wav\" type=\"audio/mpeg\"></audio>");
<?
$select_gifs = mysql_query("SELECT * FROM `submited_chatroom_gifs` WHERE `staff` = '1'");
while($gif = mysql_fetch_array($select_gifs)){
?>
newdata = newdata.replace(/:<? echo $gif['name']; ?>/g,"<img data-toggle=\"tooltip\" height=\"<? echo $gif['height']; ?>\" width=\"<? echo $gif['width']; ?>\"title=\":<? echo $gif['name']; ?>\" src=\"/_img/gifs/<? echo $gif['img']; ?>\"></img>");
<? } ?>
$('#chat-area').append($("<p>"+ newdata +"</p>"));
}
}
document.getElementById('chat-area').scrollTop = document.getElementById('chat-area').scrollHeight;
instanse = false;
state = data.state;
},
});
}
else {
setTimeout(updateChat, 1500);
}
}
//send the message
function sendChat(message, nickname)
{
updateChat();
$.ajax({
type: "POST",
url: "/rooms/process.php?room=<? echo $room; ?>",
data: {
'function': 'send',
'message': message,
'nickname': nickname,
'file': file
},
dataType: "json",
success: function(data){
updateChat();
},
});
}
process.php
<?php
$function = $_POST['function'];
$room = $_GET['room'];
$log = array();
switch($function) {
case('getState'):
if(file_exists($room . '.txt')){
$lines = file($room . '.txt');
}
$log['state'] = count($lines);
break;
case('update'):
$state = $_POST['state'];
if(file_exists($room . '.txt')){
$lines = file($room . '.txt');
}
$count = count($lines);
if($state == $count){
$log['state'] = $state;
$log['text'] = false;
}
else{
$text= array();
$log['state'] = $state + count($lines) - $state;
foreach ($lines as $line_num => $line)
{
if($line_num >= $state){
$text[] = $line = str_replace("\n", "", $line);
}
}
$log['text'] = $text;
}
break;
case('send'):
$nickname = $_POST['nickname'];
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
$message = htmlentities(strip_tags($_POST['message']));
if(($message) != "\n"){
if(preg_match($reg_exUrl, $message, $url)) {
$message = preg_replace($reg_exUrl, ''.$url[0].'', $message);
}
fwrite(fopen($room . '.txt', 'a'), "<p><font size=\"2px\">". $nickname . ": " . $message = str_replace("\n", " ", $message) . "</font></p>\n");
}
break;
}
echo json_encode($log);
}
?>
the alert is only for the person who wrote the command in
Thankyou for any help, and I apologise for the lengthy question.
[edit] Sorry just re-read my question and I will just try and explain what I'm trying to achieve in abit more detail. So basically when a user inputs /command lewis the script would then perform an alert('Hi Lewis');. But then if a user was to enter /command john the alert would be alert('Hi John');.
The alert would be instead of posting the message to the chatroom.

Codeigniter ajax check email availability

I have been trying check email availibity using ajax and jquery script as follows,
my controller:
$get_result = $this->user->check_email_availablity();
if($get_result == FALSE ) {
$validate['message'] = '<p>Email is not available.</p>';
} else {
$validate['message'] = '<p>Email is available.</p>';
}
$this->load->view('user/signup', $validate);
my model:
function check_email_availablity() {
$email = $this->input->post('u_email');
$query = $this->db->query('SELECT u_email FROM tbl_users where u_email = "'.$email.'"');
if($query->num_rows() === 1) {
return FALSE;
} else {
return TRUE;
}
}
my js:
$(document).ready(function() {
/// make loader hidden in start
$('#Loading').hide();
$('#email').blur(function(){
var a = $("#email").val();
var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
// check if email is valid
if(filter.test(a)){
// show loader
$('#Loading').show();
$.post("<?php echo base_url()?>main/signup", {
email: $('#email').val()
},
function(response){
//#emailInfo is a span which will show you message
$('#Loading').hide();
setTimeout("finishAjax('Loading', '"+escape(response)+"')", 400);
});
return false;
}
});
function finishAjax(id, response){
$('#'+id).html(unescape(response));
$('#'+id).fadeIn();
}
});
my view:
<?php echo form_input('u_email', set_value('u_email'), 'class="form-control" id="email"'); ?>
<span id="Loading"><?php echo $message; ?></span>
My problem is model always returns TRUE and shows 'email is available' message, how do I check the email availability live
In your model change the if condition in query row:
function check_email_availablity() {
$email = $this->input->post('u_email');
$query = $this->db->query('SELECT u_email FROM tbl_users where u_email = "'.$email.'"');
if($query->num_rows() > 0) {
return FALSE;
} else {
return TRUE;
}
}
And in your controller:
$get_result = $this->user->check_email_availablity();
if(!$get_result) //if email already exist in your database
{
$validate['message'] = '<p>Email is not available.</p>';
} else {
$validate['message'] = '<p>Email is available.</p>';
}
$this->load->view('user/signup', $validate);

Categories

Resources