Displaying the message in the div in codeigniter - javascript

I have created a form which includes the following field and below it I have created a div with the id email_feedback to display the message.
label>Email</label>
<div class="input-group">
<input name="email" id="email_id" type="email" class="form-control" placeholder="Email" required>
<span class="input-group-addon"><i class="fa fa-envelope-o fa-fw"></i></span>
<div id="email_feedback"></div>
</div>
and I have created the following jquery function in a separate file in js.
$(function() {
$("#register_submit").click(function() {
$.post("<?php echo base_url(); ?>user/login_register/about",
{ email : $("#email_id").val() }, function(data) {
$("#email_feedback").html(data);
console.log(data.length);
});
});
});
and I have written the following function in the controller.
function about() {
$email = $this->input->post('email');
$email_verify = $this->userdata_insertion->read_user_information($email);
if($email_verify == "true"){
echo "The user already exists";
}
}
and this function in the model.
public function read_user_information($email) {
$condition = "email =" . "'" . $email . "'";
$this->db->select('*');
$this->db->from('vtiger_users_details');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
return true;
} else {
return false;
}
}
but whenever I try to use the email id that I have used before it is not showing the error message can anyone let me know where I am committing the mistake.

try :
Controller:
if($email_verify){
echo "The user already exists";
}
Model:
public function read_user_information($email) {
$this->db->select('*');
$this->db->from('vtiger_users_details');
$this->db->where('email',$email);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
return true;
} else {
return false;
}
}

There was an issue with the base URL whenever I use to pass the base_url in the jquery as follows.
<?php echo base_url(); ?>user/login_register/about
it uses to consider the path of the controller where the function is been written and then concatenate the base URL to that resulting in the wrong URL. I have removed the echo "base_url()" and it is working fine now.

Related

Ajax php post not authenticating

I have a sample script that will authenticate my users to access the page. My issue is when I post the values the js file does reflect that the data has been serialized but when it is posted to the php file to check if the database record exists the users still gets access to the page whether the login in details are correct or wrong. For some reason it seems not to take my `$_POST['pass'] and my $_POST['user_email'] values. But if I manually type in the user email and password in the php file to replace the variables it will works.
HTML form
<form class="login" id="login-form" name="login-form" method="post">
<p class="title">LOGIN</p>
<input type="text" placeholder="Email" id="user_email" name="user_email" autofocus/>
<i class="fa fa-user"></i>
<input type="password" placeholder="Password" id="pass" name="pass" />
<i class="fa fa-key"></i>
<button>
<i class="spinner" style="outline:none;"></i>
<span class="state">Log in</span>
</button>
</form>
My js file to post the values. I added the console.log just to test see what values are been taken in by the script
$('document').ready(function()
{
var working = false;
$('.login').on('submit', function(e) {
e.preventDefault();
if(working)return
working = true;
var $this = $(this),
$state = $this.find('button > .state');
$this.addClass('loading');
$state.html('Authenticating');
var data = $("#login-form").serialize();
console.log(data);
$.ajax({
type : 'POST',
url : 'login_process.php',
data : data,
success : function(response) {
console.log(response);
if(response=="ok"){
setTimeout(function() {
$this.addClass('ok');
$state.html('Welcome');
setTimeout(function() {
$state.html('Log in');
$this.removeClass('ok loading');
working = false;
}, 4000);
setTimeout(function() {
window.location.href = "/Home.aspx";
}, 4000);
}, 3000);
//$("#btn-login").html('<img src="btn-ajax-loader.gif" /> Signing In ...');
//setTimeout(' window.location.href = "home.php"; ',4000);
} else {
console.log('ERROR IN LOGINING IN');
}
}
});
return false;
});
});
PHP file 'login_process'
<?php
session_start();
require_once 'dbconfig.php';
if(isset($_POST['pass']))
{
$user_email = urldecode(trim($_POST['user_email']));
$user_password =trim($_POST['pass']);
//$password = md5($user_password);
$password = $user_password;
try {
$stmt = $db_con->prepare("SELECT * FROM tbl_users WHERE user_email=:email");
$stmt->execute(array(":email"=>$user_email));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$count = $stmt->rowCount();
if($row['user_password']==$password){
echo "ok"; // log in
$_SESSION['user_session'] = $row['user_id'];
}
else{
echo "email or password does not exist."; // wrong details
}
}
catch(PDOException $e){
echo $e->getMessage();
}
}
?>
You are missing the dataType make with dataType : 'json' just after data, You can return the result in json by json_encode() ti debug result

Jquery alert box for registrate new user

Im all new to ajax and jquery so iam asking u guys for some help. I have to forms that one creates a new user and second logs the user in.
The functions work greate, but i want to create alert boxes for success or failure of the functions.
And i dont know how... Here is my code
HTML
<!-- Formular for signing up -->
<h4 class="form-headline"> Not a member? Sign up here </h4>
<form method="post">
<div class="form-group">
<label> Username </label>
<input type="text" class="form-control" id="newusername">
</div>
<div class="form-group">
<label> Password </label>
<input type="password" class="form-control" id="newpassword">
</div>
<div class="form-group">
<label> Your club </label>
<input type="text" class="form-control" id="newclub">
</div>
<input type="button" id="btn-reg" class="btn btn-success" value="Sign up!">
</form>
Script
// -----------------Registration of new user----------------------
console.log('Script loaded...');
// Calling for the method - reg
$("#btn-reg").on("click", reg);
function reg(e) {
e.preventDefault();
console.log('Klick, klick...');
// Declaring variables
var newusername=$("#newusername").val();
var newpassword=$("#newpassword").val();
var newclub=$("#newclub").val();
$.post('classCalling.php', {
newusername: newusername,
newpassword: newpassword,
newclub: newclub
},
function(data){
console.log(data);
});
}
PHP
// Creating instance of the class userClass.php
var_dump($_POST);
if(isset($_POST['newusername'])){
// Defining variables
$newusername = $_POST['newusername'];
$newpassword = $_POST['newpassword'];
$newclub = $_POST['newclub'];
// Password hash
$hashpassword = sha1($newpassword);
$user = new User();
$user->newUsers($newusername, $hashpassword, $newclub);
} else {
}?>
OOP
// >>>>>>>>>>>>>>>> Function for saving new user to database
public function newUsers($newusername, $hashpassword, $newclub) {
// Using prepared statement to prevent mysql injections.
$stmt = $this->db->prepare("INSERT INTO users(username, password, club)VALUES(?, ?, ?);");
$stmt->bind_param("sss", $newusername, $hashpassword, $newclub);
if($stmt->execute()) {
echo "<h3 class='usercreated'>Created</h3>";
} else {
echo "<h3 class='usercreated'> Failed </h3>";
}
}
Just noticed that you are using function to create a new user, my bad again
if(isset($_POST['newusername'])){
// Defining variables
$newusername = $_POST['newusername'];
$newpassword = $_POST['newpassword'];
$newclub = $_POST['newclub'];
// Password hash
$hashpassword = sha1($newpassword);
$user = new User();
$status = $user->newUsers($newusername, $hashpassword, $newclub);
if($status) {
echo json_encode(array("status" : "success"));
}else {
echo json_encode(array("status" : "failed"));
}
}
Make a return from this function
public function newUsers($newusername, $hashpassword, $newclub) {
// Using prepared statement to prevent mysql injections.
$stmt = $this->db->prepare("INSERT INTO users(username, password, club)VALUES(?, ?, ?);");
$stmt->bind_param("sss", $newusername, $hashpassword, $newclub);
if($stmt->execute()) {
return true;
}else {
return false
}
}
this will be the same
$.post('classCalling.php', {
newusername: newusername,
newpassword: newpassword,
newclub: newclub
},
function(data){
var object = JSON.parse(data);
alert(object.status);
// or you can add if else by using the status
});
}
You could just echo the script tag.
if($stmt->execute()) {
echo "<h3 class='usercreated'>Created</h3>";
echo "<script type="text/javascript">";
echo "alert("Hello World!")";
echo "</script>";
} else {
echo "<h3 class='usercreated'> Failed </h3>";
echo "<script type="text/javascript">";
echo "alert("Hello World!")";
echo "</script>";
}
}
For the Script block.
var posting = $.post('classCalling.php', {
newusername: newusername,
newpassword: newpassword,
newclub: newclub
});
posting.done(function( data ) {
alert( "Data Loaded Ok");
});
posting.fail(function( data ) {
alert( "Error loading data");
});
Hope this helps you.

updating MYSQL table gives success msg, but does'nt update the table

the AJAX msg gives successful, but the data doesn't update in DB, can you help plz!
html code:
<div class="row">
<input type="text" ng-model="updateId" class="form-control" placeholder="user Id To Update Phone">
<input type="text" ng-model="updatePhone" class="form-control" placeholder="user New Phone">
</div>
<div class="col-xs-3">
</div>
<div class="col-xs-2">
<button ng-click="updateuser()" type="button" class="btn btn-primary">Update </button>
</div>
</div>
javascript code:
$scope.updateuser = function () {
var data = {
updateId: $scope.updateId,
updatePhone: $scope.updatePhone
};
$.ajax({
data: data,
type: "post",
url: "update.php",
success: function(data){
alert("Data Updated");
},
error:function (XMLHttpRequest, textStatus, errorThrown) {
if (textStatus == 'Unauthorized') {
alert('custom message. Error: ' + errorThrown);
} else {
alert('custom message. Error: ' + errorThrown);
}
}
});
};
update.php code:
<?php
header('Content-Type: application/json');
include 'connect.php';
$db = new database();
$db->setDb_name('training');
$db->connect();
if(isset($_POST)){
$id = $_POST['updateId'];
$phone = $_POST['updatePhone'];
$data = $db->update('user',array('phone'=>$phone),array('id',$id));
echo json_encode($data);
}
mysql_close();
?>
the update() function:
public function update($table,$rows,$where)
{
for($i = 0; $i < count($where); $i++)
{
if($i%2 != 0)
{
if(is_string($where[$i]))
{
if(($i+1) != null)
$where[$i] = '"'.$where[$i].'" AND ';
else
$where[$i] = '"'.$where[$i].'"';
}
}
}
$where = implode('=',$where);
$update = 'UPDATE '.$table.' SET ';
$keys = array_keys($rows);
for($i = 0; $i < count($rows); $i++)
{
if(is_string($rows[$keys[$i]]))
{
$update .= $keys[$i].'="'.$rows[$keys[$i]].'"';
}
else
{
$update .= $keys[$i].'='.$rows[$keys[$i]];
}
// Parse to add commas
if($i != count($rows)-1)
{
$update .= ',';
}
}
$update .= ' WHERE '.$where;
$query = #mysql_query($update);
}
}
I am using angularJS, and when trying to run updating in update.php it works correctly, but using AJAX it gives "Data Updated" msg but actually doesnt update table.. why?
First of all, the ajax success callback from (I'm assuming) jQuery just means the HTTP request succeeded. This means it got a 200 response code. With most minor and some major errors in PHP the request will still be successful. If you want to know what went wrong, enable error reporting in PHP and be sure the errors are displayed:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
Now, you should be able to see any errors. Use something like Chrome's developer console to see what error happened in your PHP code. Another option would be to log the error in PHP and check the error log after the request.

how to pass variable from jquery ajax to php mvc

I'm using the php-mvc and adding search functionality using ajax. How am going to pass the value from the input to model and query the value. I tried to add $_GET['searchData'] inside getAllUsersProfiles method but it doesn't get the value.
HTML:
<input type="text" id="searchData" placeholder="search name here..." />
...
<!--where I want to output the search result -->
<tbody id="account_results"></tbody>
JS:
$("#searchData").keyup(function(){
var searchValue = $.trim($(this).val());
if(searchValue !== ''){
$.get("<?php echo URL; ?>admin/index/", function(returnData){
if(!returnData)
$("#account_results").html("<p>No record(s) found.</p>");
else
$("#account_results").html(returnData);
});
}
});
PHP Model:
public function getAllUsersProfiles()
{
$sql = "SELECT id, username, email, active, firstname, lastname
FROM users";
if(isset($_GET['searchData'])) {
$sql .= " WHERE CONCAT(TRIM(firstname), ' ', TRIM(lastname))
LIKE '%:searchData%'";
$sth = $this->db->prepare($sql);
}
else
//if search input is not set, output all of the list.
$sth = $this->db->prepare($sql);
$sth->execute();
$all_users_profiles = array();
foreach ($sth->fetchAll() as $user) {
//code here..
}
return $users;
}
PHP Controller:
class Admin extends Controller
{
function __construct()
{
parent::__construct();
}
function index()
{
$admin_model = $this->loadModel('Admin');
$this->view->users = $admin_model->getAllUsersProfiles();
$this->view->render('admin/index');
}
Your PHP code doesn't get the searchData value because you don't send it with the GET request. Try this in your JS part:
$("#searchData").keyup(function(){
var searchValue = $.trim($(this).val()), url = '<?php echo URL; ?>/admin/index/?searchData=' + searchValue;
if(searchValue !== ''){
$.get(url, function(returnData){
if(!returnData)
$("#account_results").html("<p>No record(s) found.</p>");
else
$("#account_results").html(returnData);
});
}
});
And then you can get the value with $_GET['searchData'] in PHP

AJAX not returning result from php

I am trying to learn from an example from online,for a login form with php and jquery and i am using the exactly the same example, but for some reason the AJAX isnt getting anything back but redirecting my to another php.
Here is a link of what i had been trying and the problem.
http://rentaid.info/Bootstraptest/testlogin.html
It supposed to get the result and display it back on the same page, but it is redirecting me to another blank php with the result on it.
Thanks for your time, i provided all the codes that i have, i hope the question isnt too stupid.
HTML code:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<form id= "loginform" class="form-horizontal" action='http://rentaid.info/Bootstraptest/agentlogin.php' method='POST'>
<p id="result"></p>
<!-- Sign In Form -->
<input required="" id="userid" name="username" type="text" class="form-control" placeholder="Registered Email" class="input-medium" required="">
<input required="" id="passwordinput" name="password" class="form-control" type="password" placeholder="Password" class="input-medium">
<!-- Button -->
<button id="signinbutton" name="signin" class="btn btn-success" style="width:100px;">Sign In</button>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javasript" src="http://rentaid.info/Bootstraptest/test.js"></script>
</body>
</html>
Javascript
$("button#signinbutton").click(function() {
if ($("#username").val() == "" || $("#password").val() == "") {
$("p#result).html("Please enter both userna");
} else {
$.post($("#loginform").attr("action"), $("#loginform:input").serializeArray(), function(data) {
$("p#result").html(data);
});
$("#loginform").submit(function() {
return false;
});
}
});
php
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
ob_start();
session_start();
include 'connect.php';
//get form data
$username = addslashes(strip_tags($_POST['username']));
$password = addslashes(strip_tags($_POST['password']));
$password1 = mysqli_real_escape_string($con, $password);
$username = mysqli_real_escape_string($con, $username);
if (!$username || !$password) {
$no = "Please enter name and password";
echo ($no);
} else {
//log in
$login = mysqli_query($con, "SELECT * FROM Agent WHERE username='$username'")or die(mysqli_error());
if (mysqli_num_rows($login) == 0)
echo "No such user";
else {
while ($login_row = mysqli_fetch_assoc($login)) {
//get database password
$password_db = $login_row['password'];
//encrypt form password
$password1 = md5($password1);
//check password
if ($password1 != $password_db)
echo "Incorrect Password";
else {
//assign session
$_SESSION['username'] = $username;
$_SESSION['password'] = $password1;
header("Location: http://rentaid.info/Bootstraptest/aboutus.html");
}
}
}
}
?>
Edit
$("button#signinbutton").click(function(){
if($("#username").val() ==""||$("#password").val()=="")
$("p#result).html("Please enter both userna");
else
$.post ($("#loginform").attr("action"),
$("#loginform:input").serializeArray(),
function(data) {
$("p#result).html(data); });
});
$("#loginform").submit(function(){
return false;
});
First of all, Remove :-
header("Location: http://rentaid.info/Bootstraptest/aboutus.html");
and if you want to display the data, echo username and password.
$_SESSION['username'] = $username;
$_SESSION['password'] = $password1;
echo $username."<br>".;
echo $password1;
The reason you are being redirected is that you are also calling $.submit. The classic form submit will redirect you to a new page, which is exactly what you don't want when you're using AJAX. If you remove this call:
$("#loginform").submit(function() {
return false;
});
you probably should have working solution. If not, let me know :)
Modify your javascript section so that
$("button#signinbutton").click(function() {
if ($("#username").val() == "" || $("#password").val() == "") {
$("p#result).html("Please enter both userna");
} else {
$.post($("#loginform").attr("action"), $("#loginform:input").serializeArray(), function(data) {
$("p#result").html(data);
});
}
});
$("#loginform").submit(function() {
return false;
});
is outside the function call.

Categories

Resources