function logsig() {
var username = $("#username").val();
var password = $("#password").val();
var dataString = '&username=' + username + '&password=' + password;
if(username=='' || password=='') {
$('#success').fadeOut(400).hide();
$('#error').fadeOut(400).show();
} else {
$.ajax({
type: "POST",
dataType: "JSON",
url: "<?=base_url()?>index.php/home/logsig",
data: dataString,
json: {session_state: true},
success: function(data) {
if(data.session_state == true) {
window.location = "<?=base_url()?>";
} else if(data.session_state == false) {
$("#login_failure").fadeIn(400);
}
}
});
}
}
How can I pass multiple json encoded values to my form above. What I'm doing is if user logs in, 'session_state' is passed, and if user has a 'pending' account, 'pending' is passed. Both json values have an expression to be executed.
public function logsig() {
header('Content-type:application/json');
$postedEmail = $this->input->post('username');
$password = $this->input->post('password');
$hashedPass = $this->encrypt->sha1($password);
$query = $this->db->query("SELECT * FROM users WHERE username = '{$postedEmail}' AND password = '{$password}'");
if ($query->num_rows() > 0) { // if user is already registered and is logging in, execute the following sql/php commands.
$row = $query->row();
if ($row->status == "pending") {
echo json_encode(array('pending' => true));
} else {
echo json_encode(array('pending' => false));
}
//$this->session->set_userdata('userid', $idgen);
//$this->session->set_userdata('email', $postedEmail);
$this->session->set_userdata('logged', "1"); // 1 means user is logged in.
echo json_encode(array('session_state' => true));
} else {
echo json_encode(array('session_state' => false)); // false sends to jquery that member isn't registered
}
}
You should collect all your data and at the end output it as the single JSON string. For example:
$output= array();
if ($query->num_rows() > 0) {
$row = $query->row();
// Status flag
$output['pending'] = $row->status == "pending";
$this->session->set_userdata('logged', "1"); // 1 means user is logged in.
// Session state
$output['session_state'] = true;
}
else {
$output['session_state'] = false;
}
header('Content-type: application/json');
die(json_encode($output));
Or in this case even better (optimized true-branch):
$row = $query->row();
$this->session->set_userdata('logged', "1"); // 1 means user is logged in.
// Session state
$output = array(
'pending' = $row->status == "pending",
'session_state' = false
);
Related
This question already has answers here:
Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?
(13 answers)
Closed 7 years ago.
I want to do this simple log in task using php web service. I am just trying to authenticate username and password on the basis of text result I am echoing in my php.
PHP:
<?php
// Include confi.php
include_once('confi.php');
$found = false;
$email = isset($_POST['email']) ? mysql_real_escape_string($_POST['email']) : "";
$password = isset($_POST['password']) ? mysql_real_escape_string($_POST['password']) : "";
if(!empty($email) && !empty($password)){
$login=mysql_num_rows(mysql_query("select *
from `login`
where `email`='$email'
and `password`='$password'"));
$result =array();
if($login!=0)
{
echo "success";
}
else
{
echo "failed";
}
}
#mysql_close($conn);
/* Output header */
header('Content-type: text/plain');
?>
If the username and password match; it displays success.
Jquery
<script>
$(function () {
$("#logon").click(function () {
var email = $("#username").val();
var password = $("#pass").val();
var dataString = "email=" + email + "&password=" + password;
if ($.trim(email).length > 0 & $.trim(password).length > 0) {
$.ajax({
type: "POST",
url: "http://*****/login.php",
data:dataString,
crossDomain: true,
cache: false,
beforeSend: function () { $("#logon").html('Connecting...'); },
success: function (data) {
if (data == "success") {
alert(result+"You are in");
localStorage.login = "true";
localStorage.email = email;
window.location.href = "test.html";
}
else if (data == "failed") {
alert("Login error");
$("#logon").html('Login');
}
}
});
}
});
});
</script>
you are missing the json function you have to encode what ever you want to send to back to request
<?php
/*output the header here*/
header("Content-Type: application/json");
// Include confi.php
include_once('confi.php');
$response['Status'];// declare a variable to store msg
$found = false;
$email = isset($_POST['email']) ?
mysql_real_escape_string($_POST['email']) : "";
$password = isset($_POST['password']) ?
mysql_real_escape_string($_POST['password']) : "";
if(!empty($email) && !empty($password)){
$login=mysql_num_rows(mysql_query("select *
from `login`
where `email`='$email'
and `password`='$password'"));
$result =array();
if($login!=0)
{
$response['Status']=""success";
}
else
{
$response['Status']="failed";
}
}
#mysql_close($conn);
here make the change
$result= json_encode($message);
echo $result;
?>
in you jquery data to ajax function add
dataType:"json",
success: function (data) {
if (data.Status == "success") { //here check the condition
alert(result+"You are in");
localStorage.login = "true";
localStorage.email = email;
window.location.href = "test.html";
}
else if (data.Status== "failed") { //here check the condition
alert("Login error");
$("#logon").html('Login');
}
}
I have 2 php file, one is "Db_function.php" and "index.php", "index.php" will make a function call in "Db_function.php".
I want to make a call to "index.php" by ajax, here's my code
Html file
<Html>
<body>
<script type="text/javascript" src="js/index.js"></script>
<input type="button" value="Get" onclick="get()">
</body>
</html>
Js file
function get() {
$.ajax({ url: 'index.php',
data: {tag:'get_backup', email:'mail#mail.com', password:'123'},
type: 'post',
datatype:'json'
success: function(output) {
alert(output);
}
});
}
index.php
/*with connect value*/
if ($tag == 'get_backup'){
// store user
$email = $_POST['email'];
$password = $_POST['password'];
$user = $db->get_backup($email, $password);
Db_funtion.php
public function get_backup($email, $password) {
$result = mysql_query("SELECT * FROM users WHERE email = '$email'") or die(mysql_error());
// check for result
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
$result = mysql_fetch_array($result);
$salt = $result['salt'];
$encrypted_password = $result['encrypted_password'];
$hash = $this->checkhashSSHA($salt, $password);
// check for password equality
if ($encrypted_password == $hash) {
// user authentication details are correct
$response = array();
$result2 = mysql_query("SELECT * FROM contact_store WHERE (email ='$email' AND backup_name='$email')") or die(mysql_error());
if (mysql_num_rows($result2) > 0) {
// looping through all results
// contact_stores node
$response["contact_stores"] = array();
while ($row = mysql_fetch_array($result2)) {
// temp user array
$contact_store = array();
$contact_store["backup_name"] = $row["backup_name"];
$contact_store["email"] = $row["email"];
$contact_store["data"] = $row["data"];
// push single contact_store into final response array
array_push($response["contact_stores"], $contact_store);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no contact_stores found
$response["success"] = 0;
$response["message"] = "No contact_stores found";
// echo no users JSON
echo json_encode($response);
}
}
} else {
// user not found
return false;
}
}
Json return like this
{"contact_stores":[{"backup_name":"nhi#gmail.com","email":"nhi#gmail.com","data":"[]"}],"success":1}
But my problem is when i press get button in html file, nothing happen.
Any help for me ?
It seems like you are not defining the get() function that you provide in the input element.
Try this HTML:
<input id="get" type="button" value="Get">
with this javascript:
$('#get').click(function() {
$.ajax({ url: 'index.php',
data: {tag:'get_backup', email:'mail#mail.com', password:'123'},
type: 'post',
datatype:'json'
success: function(output) {
alert(output);
}
})
});
i want to make login form with session (with PHP + ajax), i send username from controller with json but it doesn't work. i don't know whats wrong, please help
this is the function in controller :
public function actionLogin()
{
$username = isset($_POST['username'])?$_POST['username']:null;
$password = isset($_POST['password'])?sha1($_POST['password']):null;
$json = new JsonHelper();
$result = array();
if($username && $password !=''){
$checkLogin = Administrator::model()->findByAttributes(
array('username'=>$username, 'password'=>$password));
$checkUser = Administrator::model()->findByAttributes(
array('username'=>$username));
$checkPass = Administrator::model()->findByAttributes(
array('password'=>$password));
$login = count($checkLogin);
$user = count($checkUser);
$pass= count($checkPass);
if($login==1)
{
$result['status'] = 'success';
$result['username'] = $username;
$json->addData('ajax', $result);
}
elseif($user == 1 && $pass == 0)
{
$result['status'] = 'wrongPass';
$json->addData('ajax', $result);
}
elseif($user == 0 && $pass == 1)
{
$result['status'] = 'wrongUser';
$json->addData('ajax', $result);
}
}
echo json_encode($json->getJson());
}
and this is the form_login.js file :
function login(){
var form = $('#login-form');
var formId = form.attr('id');
var action = form.attr('data-action');
var method = form.attr('data-method');
var formData = serializer(form); //don't mind this function
$.ajax(
{
url: action,
cache: false,
processData: false,
contentType: false,
type: method,
data: formData,
success: function(json)
{
// AJAX SUCCESS
var json = JSON.parse(result);
if(json['result']['ajax']['status']=='success')
{
//$_SESSION['username'] =json['username'];
window.location = baseUrl + "/appsterize/dashboard/index";
}
else if(json['result']['ajax']['status']=='wrongPass')
{
// Password wrong
alert("The password you entered is incorrect.");
}
else if(json['result']['ajax']['status']=='wrongUser')
{
// Username isn't exist
alert("Username isn't exist");
}
},
error: function(xhr, status, error)
{
// AJAX ERROR
var string = "<strong>Error!</strong> " + xhr['responseText'];
$(alertError).attr('data-text', string);
$(alertError).click();
},
});
}
some error is 'Uncaught ReferenceError: alertError is not defined'
Have an element with id = 'alertError'?
Could this be the solution:
$("#alertError").attr('data-text', string);
...
Basically, what #serakfalcon said above:
...
error: function(xhr, status, error)
{
// AJAX ERROR
var errorMsg = "<strong>Error!</strong> " + xhr['responseText'];
alert(errorMsg);
},
...
I want to check if the username is already taken, here is my script, which outputs "undefined". Can anyone help me, please? :)
This is in my jQuery - $("#registerusername").val() is the value of an input.
$.post('checkregister.php',{username: $("#registerusername").val()}, function(data){
window.alert(data.exists);
if(data.exists){
window.alert("Name already found");
}else{
window.alert("Name NOT found");
}
}, 'JSON');
This is in my checkregister.php
header('content-type: text/json');
if(!isset($_POST['username']))
exit;
$db = new PDO('mysql:host=localhost;dbname=testdatabase','root','pw000');
$query = $db->prepare("SELECT * FROM users WHERE username = '" . $_POST['username'] . "'");
$query->execute();
echo json_encode(array('exists' => $query->rowCount() > 0));
First, You might want to strengthen your php against sql injection by 'sanitizing' the input.
Next why return JSON from the php? It would be much simpler to just return either true or false.
$db = new PDO('mysql:host=localhost;dbname=testdatabase','root','pw000');
$query = $db->prepare("SELECT * FROM users WHERE username = '" . $_POST['username'] . "'");
$query->execute();
if( $query->rowCount() > 0 ){
echo 'true';
}
else{
echo 'false';
}
Then in your javascript:
$.post('checkregister.php',{username: $("#registerusername").val()}, function(data){
window.alert(data);
if(data == 'true'){
window.alert("Name already found");
}else{
window.alert("Name NOT found");
}
});
edit---
You could also just return a boolean variable from php rather than a string, but either will work
Simple Example..
Jquery
var username = $.trim($('#username').val());
if(username != '') {
$.ajax({
url : 'localhost/phpScript.php',
data : {username : username},
dataType : 'JSON',
type : 'POST',
cache : false,
success : function(result) {
if(result == '1') { alert('Username Found.'); }
else if(result == '0') { alert('Username Not Found!'); }
},
error : function(err) {
console.log(err);
}
});
}
PHP/MySQL (Make sure that you escape value for user input, Before giving it to MySql)
if(isset($_POST['username'])) {
$username = $_POST['username'];
$sql = "SELECT username FROM users WHERE username = '".$username."' LIMIT 1";
$query = mysql_query($sql);
if(mysql_num_rows($query) == '1') {
echo '1';
} else {
echo '0';
}
}
I am using a log in script that I found on experts exchange to make a cookie when a user logs on.
The login page processes like this:
function process_login() {
var username = $.trim($('#input_username').val());
var password = $.trim($('#input_password').val());
username = $.trim(username);
password = $.trim(password);
var remember = document.getElementById("remember_user_checkbox").checked;
if (!username || !password) {
return false;
}
remember == true ? remember = "true" : remember = "false";
$.ajax({
type: "POST",
cache: false,
url: "login_user.php",
data: "username=" + username + "&password=" + password + "&remember=" + remember,
dataType: "json",
success: function (data) {
if (data == "FALSE") {
$('#input_password').val("");
alert("The username or password you have entered is incorrect.");
return false;
}
window.location = "orders-home.php?<?=time()?>";
}
});
}
And submits to login-user.php, here:
<?php
include('login-config.php');
$username = pg_escape_string($_POST['username']);
$password = pg_escape_string($_POST['password']);
//no encryption for now
//php gets this as a string
$remember = $_POST['remember'];
if ( $remember == "true" )
{
$remember = TRUE;
}
else
{
$remember = FALSE;
}
$user_query = "SELECT * FROM users WHERE username = '$username' AND password = '$password' LIMIT 1";
$user_result = pg_query( $con , $user_query );
if ( !$user_result )
{
echo json_encode("FALSE");
}
$arr = array();
if (!$user_result)
{
die( pg_last_error($con) );
}
else
{
while ( $row = pg_fetch_array($user_result) )
{
//put the customer id in a session so we can put it in a cookie later
//then when the page is refreshed the stored customer id will be used
//as their ksisoldby identifier
if ( $row['cust_id'] )
{
$_SESSION['customer_id'] = $row['cust_id'];
$_SESSION['customer_name'] = $row['first_name']." ".$row['last_name'];
$_SESSION['uid'] = $row['id'];
if ( $remember )
{
remember_user($row["id"]);
}
}
$arr[] = array(
"first_name" =>$row['first_name'],
"last_name" =>$row['last_name'],
"customer_id" =>$row['cust_id'],
"accepted_terms" =>$row['accepted_terms'],
);
}
}
if ( empty($arr) ){
echo json_encode('FALSE');
}
else
{
$path = '/webtrack';
$site = 'www.isco.net';
if ($remember === TRUE)
{
$remember_time = time()+60*60*24*30;
setcookie('username', $username, $remember_time, $path, $site);
setcookie('customer_id', $_SESSION['customer_id'], $remember_time, $path, $site);
setcookie('customer_name', $_SESSION['customer_name'], $remember_time, $path, $site);
// setcookie('uuk', $uuk, $remember_time, $path, $site);
}
else
{
setcookie('username', $username, false, $path, $site);
setcookie('customer_id', $_SESSION['customer_id'], false, $path, $site);
setcookie('customer_name', $_SESSION['customer_name'], false, $path, $site);
}
echo json_encode($arr);
}
?>
I then print from that cookie onto the main screen
<div class="fl customer_id">
<?= strtoupper($_COOKIE['customer_name']); ?>
</div>
But I getting the error
Notice: Undefined index: customer_name in /home/iscotest/public_html/webtrack/orders-home.php
The actual site is www.isco.net. But the website is hosted at iscotest.com. isco.net simply points to iscotest.com. Could this be why my cookie isn't being set?
It is quite a problem because this totally ceases the load of the page, as that cookie information is used to retrieve the data that is displayed
The other odd thing is that this error isn't appearing consistently. I get the error on safari and chrome on one computer, but the site functions normally on another computer in safari and chrome.
Thanks for any help
When you use setcookie () to create a COOKIE this will only be available on another page. Therefore, it can be a problem with your AJAX.