redirect in codeigniter using ajax function - javascript

this is my controller function
public function verifyUser()
{
$userName = $_POST['email'];
$userPassword = $_POST['password'];
$var=array('email'=>$userName,'password'=>$userPassword);
$check=$this->mymodel->login_validation($var);
//$status = array("STATUS"=>"false");
if(count($check))
{
redirect('main/valid_login');
}
else
{
echo "<div style='border:1px solid red;font-size: 11px;margin:0 auto !important;'>Could't Authorize to the system! Try again with valid credentials.</div>" ;
}
}
this is my ajax function
<script>
function makeAjaxCall(){
$.ajax({
type: "post",
url: "<?php echo site_url('main/verifyUser');?>",
cache: false,
data: $('#userForm').serialize(),
success:function(msg)
{
$('#show_id').html(msg);
}
});
}
</script>
this is my form
<form name="userForm" id="userForm" action="">
<div id="show_id"></div>
<fieldset>
<p><label for="email">E-mail address</label></p>
<p><input type="email" id="email" placeholder="enter your email id" name="email"></p> <!-- JS because of IE support; better: placeholder="mail#address.com" -->
<p><label for="password">Password</label></p>
<p><input type="password" id="password" placeholder="*******" name="password" style="width: 328px;"></p> <!-- JS because of IE support; better: placeholder="password" -->
<p><input type="button" value="Sign In" onclick="javascript:makeAjaxCall();"></p>
</fieldset>
</form>
everything is working fine,but when i entered the valid username and password,its not redirecting to any page,so please help me on this

Send JSON data to ajax as response and handle it according to need.
Contorller:
public function verifyUser() {
$userName = $_POST['email'];
$userPassword = $_POST['password'];
$var=array('email'=>$userName,'password'=>$userPassword);
$check=$this->mymodel->login_validation($var);
//$status = array("STATUS"=>"false");
if(count($check)) {
$this->output
->set_content_type("application/json")
->set_output(json_encode(array('status'=>true, 'redirect'=>base_url('main/valid_login') )));
}
else {
$this->output
->set_content_type("application/json")
->set_output(json_encode(array('status'=>false, 'error'=>'Could't Authorize to the system! Try again with valid credentials.')));
}
}
Handle JSON data with ajax.
$.ajax({
type: "post",
url: "<?php echo site_url('main/verifyUser');?>",
cache: false,
data: $('#userForm').serialize(),
dataType: 'json',
success:function(response) {
if( response.status === true )
document.location.href = response.redirect;
else
$('#show_id').html("<div style='border:1px solid red;font-size: 11px;margin:0 auto !important;'>"+response.error+"</div>");
}
});

Controller Function:
public function verifyUser()
{
$userName = $_POST['email'];
$userPassword = $_POST['password'];
$var=array('email'=>$userName,'password'=>$userPassword);
$check=$this->mymodel->login_validation($var);
//$status = array("STATUS"=>"false");
if(count($check))
{
echo 1;
}
else
{
echo "<div style='border:1px solid red;font-size: 11px;margin:0 auto !important;'>Could't Authorize to the system! Try again with valid credentials.</div>" ;
}
}
Ajax Function
<script>
function makeAjaxCall(){
$.ajax({
type: "post",
url: "<?php echo site_url('main/verifyUser');?>",
cache: false,
data: $('#userForm').serialize(),
success:function(msg)
{
if(msg== "1")
{
//redirect here
}
$('#show_id').html(msg);
}
});
}
</script>

Related

Not able to display message after submitting form using ajax

I am trying to submit the form using AJAX in CodeIgniter. Values of the form are getting saved in DB but the reply that has been set in the controller is not getting displayed in console.log or alert in AJAX code.
Code of form
<form class="form-signup" id="signup-form" method="post">
<input type="email" class="form-control" placeholder="Email" name="email" id="email">
<input type="password" class="form-control" placeholder="Password" name="password" id="password">
<button type="submit" class="btn btn-primary btn-lg btn-signup col-sm-offset-1" id="submit_form">SIGN UP</button>
</form>
Script code
<script type="text/javascript">
$(document).ready(function() {
$("#submit_form").click(function(event) {
event.preventDefault();
var email = $("input#email").val();
var password = $("input#password").val();
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "student/register",
dataType: 'json',
data: {email: email, password: password},
success: function(res) {
if (res)
{
console.log(res); //need to print the result here
//alert(res);
}
}
});
});
});
Controller code
public function register()
{
$data = array(
'email' => $this->input->post('email'),
'password'=>$this->input->post('password')
);
$email = $data['email'];
$password = $data['password'];
$this->db->where('email',$email);
$query = $this->db->get('student');
if ($query->num_rows() > 0)
{
echo "Email already exist";
}
else
{
$data1=array(
'email' => $email,
'password' => md5($password)
);
$final=$this->signin_model->register_user($data1);
return $final;
}
}
Model code
public function register_user($data1)
{
$success=$insert_data = $this->db->insert('student', $data1);
if($success)
{
$result= "success ";
}
else
{
$result= "register unsuccessful";
return $result;
}
}
As shown in the code there are 3 messages
Email already exists
Success
Register unsuccessful
In AJAX, if I do console.log or alert, I want any 1 of the above 3 messages to get displayed according to the flow.
How to display the reply on front end?
You have to use echo instead of return for success.
Please change it as follows
if ($query->num_rows() > 0)
{
echo "Email already exist";
}
else
{
$data1=array(
'email' => $email,
'password' => md5($password)
);
$final=$this->signin_model->register_user($data1);
echo $final;
}
and remove that 2 variables initialized together. That is unnecessary. This is fine.
$success = $this->db->insert('student', $data1);
Hope this can help you.
The ajax that you have used has datatype as json. So if you want data to be displayed on front end either encode the reply in json or you need to change or remove the json datatype from your ajax
Please change dataType:'json' to dataType: 'text'
<script type="text/javascript">
$(document).ready(function() {
$("#submit_form").click(function(event) {
event.preventDefault();
var email = $("input#email").val();
var password = $("input#password").val();
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "student/register",
dataType: 'text',
data: {email: email, password: password},
success: function(res) {
if (res)
{
console.log(res); //need to print the result here
//alert(res);
}
}
});
});
});

PHP file not called via AJAX

Below is my code for the problem. I am trying to call php file via AJAX.
I have an HTML file where after form submission, the AJAX calls the PHP file.
Unfortunately, I cannot see any output.
HTML File(Body):
<form>
<label for="">Username</label>
<input type="text" name="username" value="">
<br><br>
<label for="">Password</label>
<input type="text" name="password" value="">
<br>
<button name="button" id="button" value="Submit">Submit</button>
</form>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script src="login.js"></script>
My login.js file(for AJAX):
$("#button").click(function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: 'login.php'
});
});
My PHP file:
<?php
// Server credentials
$serverName = "localhost";
$username = "root";
$password = "root";
$dbName = "Blog";
//Creating connection
$db = mysqli_connect($serverName,$username,$password,$dbName);
if(!$db){
echo "error";
die($db);
}
else{
echo "er22ror";
}
mysqli_close($db);
?>
Your AJAX call doesn't do anything with the result:
$.ajax({
type: 'POST',
url: 'login.php'
});
In order to see output, you have to output something. Use a callback for that. For example, you can log the result to the console:
$.ajax({
type: 'POST',
url: 'login.php'
}).done(function (result) {
console.log(result);
});
$.ajax({
type: 'POST',
url: 'login.php',
success: function (res) {
alert('hi'+res);
}
});
used above. you can also show in console window

jQuery Ajax if variable on submit is ok hide button

I am trying to hide the submit button if the email is the same with the one in the database from action.php. How could I implement this in my following code:
<form onsubmit="return submitdata();">
<input type="text" id="mail">
<input type="submit" value="Check">
</form>
<p id="msg"></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
function submitdata()
{
var name=document.getElementById('mail').value;
$.ajax({
type: 'post',
url: 'action.php',
dataType: 'text',
data: {
'name':name
},
cache:false,
success: function (data) {
console.log(data);
$('#msg').html(data);
}
});
return false;
}
</script>
action.php:
<?php
require_once 'config.php';
$email_ck=$_POST['name'];
if(extract($crud->get_email($email_ck))){
echo "Response: ".$email;
$hide = 1;
}else{
echo 'hmmmm';
}
?>
When the email coincide I get the correct message, but how could I call back $hide to determine to hide my submit button?
Instead of returning a message, return an indication.
(In the JS script write the message accordingly)
A detailed json string would be a good idea but for simplification see the following.
PHP:
<?php
require_once 'config.php';
$email_ck=$_POST['name'];
if(extract($crud->get_email($email_ck))){
echo "already_exists";
}else{
echo 'not_exists';
}
?>
JS:
$.ajax({
type: 'post',
url: 'action.php',
dataType: 'text',
data: {
'name':name
},
cache:false,
success: function (data) {
if(data == 'already_exists'){
$('#buttonId').hide();
} else if(data == 'not_exists'){
$('#msg').html('Response: ' +name);
}
}
});

ajax call and validate email in php

I'm trying to "transform" a form action into an ajax call.
My form:
<!-- <form method="POST" onSubmit="return doSubmitLogic()" action="action.scripts.php" >
<input type="hidden" name="actiune" value="login" />
<div>
<label> Email </label>
<input type="email" name = "email" id="email" /><span id="emailErr"></span >
</div>
<div>
<label> Password </label>
<input type="password" name = "password" id="password" /> <span id="passErr"></span >
</div>
<div>
<input id ="submitBtn" type="submit" name="button" value="Send"/>
</div>
And what I tried to do with my ajax:
$(document).ready(function(){
$("#submitBtn").click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "functions.php",
data: {
Email: $("#email").val(),
Password: $("#password").val(),
},
success: function(result){
alert(result);
},
error: function (error){
alert("Error");
}
});
});
});
Also my piece of code "functions.php" is composed by many checking if the action has a specific value and if so to do something.So:
if ($_POST['actiune']==="login") {
$email = $_POST['email'];
$password = $_POST['password'];
$encript_pass = md5($password);
$query = "select * from user where email='$email' and password='$encript_pass'";
$result = mysql_query($query) or die ("Error in query: $query " . mysql_error());
$row = mysql_fetch_array($result);
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
echo("$email is a valid email address");
} else {
echo("$email is not a valid email address");
}
}
when I run it it give me an alert saying error. Any syggestions?
Just replace your code with this, notice the "actiune" under the Email & Password
$(document).ready(function(){
$("#submitBtn").click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "functions.php",
data: {
Email: $("#email").val(),
Password: $("#password").val(),
actiune: $('input[name="actiune"]').val()
},
success: function(result){
alert(result);
},
error: function (error){
alert("Error");
}
});
});
});
You need to pass actiune with your datas too.
data: {
email: $("#email").val(),
password: $("#password").val(),
actiune: 'login'
},
I also removed the uppercases from the field you pass since you require password and email in your php not Password and Email

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