I use ajax to check if it's the first time that the user logs in:
$.ajax({
url: '/checkFirstLogin.php',
type: 'post',
dataType: 'json',
data: {'user_id': userId},
success: function(data) {
if(data == 'firstTime') {
showWelcome();//this open a popup
}else{
alert('been here before');
}
},//end success
}); // end ajax call
checkFirstLogin.php simply does this:
<?php require 'core/init.php';
$user_id = filter_var($_POST['user_id'], FILTER_SANITIZE_NUMBER_INT);
$myUser = new User($user_id);
$myUser->checkFirstLogin();
if($myUser){
$response = 'firstTime';
echo json_encode($response);
}else{
$response = 'beenHere';
echo json_encode($response);
}
User::checkFirstLogin():
public function checkFirstLogin(){
$sth = $this->_db->prepare("SELECT COUNT(user_id) FROM users WHERE first_login = '0' AND user_id= ? ");
$sth->bindParam(1, $this->data()->user_id, PDO::PARAM_INT);
$sth->execute();
$data_exists = ($sth->fetchColumn() > 0) ? true : false;
return $data_exists;
}
json response is always "firstTime" even when first_time = 1 in the database.
You're checking $myUser, not the actual return value of the function; what you mean to do is probably something like;
$is_new_user = $myUser->checkFirstLogin();
if($is_new_user) {
$response = 'firstTime';
...
Related
I'm currently using Slim and Ajax to develop a mobile application. In my database I have a column which stores session codes for logins. I need to be able to once logged in, compare the username entered to the database and retrieve the sessionCode based on that.
My current PHP is this:
$app->post('/logIn/', 'logIn');
function logIn()
{
$request = \Slim\Slim::getInstance()->request();
$q = json_decode($request->getBody());
//$hashedPassword = password_hash($q->password, PASSWORD_BCRYPT);
$sql = "SELECT * FROM users where username=:username AND password=:password";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("username", $q->username);
$stmt->bindParam("password", $q->password);
$stmt->execute();
//$row=$stmt->fetch(PDO::FETCH_ASSOC);
$row=$stmt->fetch(PDO::FETCH_OBJ);
//$verify = password_verify($q->password, $row['password']);
$db = null;
echo json_encode($row);
} catch (PDOException $e) {
echo $e->getMessage();
}
} //PHP 5.4 LogIn
$app->get('/getSessionCode/:username','getSessionCode');
function getSessionCode($username)
{
$request = \Slim\Slim::getInstance()->request();
$q = json_decode($request->getBody());
$sql = "SELECT * FROM users WHERE username=:username";
try{
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("username", $username);
$stmt->execute();
$row=$stmt->fetchALL(PDO::FETCH_OBJ);
$dbh=null;
echo json_encode($row);
}
catch(PDOException $e){
if(db != null) $db = null;
echo $e->getMessage();
}
}
Ajax Code:
$("#checkLogIn").click(function()
{
username = $("#enterUser").val();
$.ajax({
type: 'POST',
contentType: 'application/json',
url: rootURL + '/logIn/',
dataType: "json",
data: checkLogIn(),
success: function(data)
{
if(data != false)
{
$.ajax({
type: 'GET',
url: rootURL + "/getSessionCode/" + username,
dataType: "json",
success: sessionData
});
}
else
{
alert("Username and/or Password was incorrect");
}
}
})
});
function checkLogIn(data)
{
return JSON.stringify({
"username": $("#enterUser").val(),
"password": $("#enterPass").val(),
});
}
function sessionData(data){
session = data.sessionCode;
alert(username);
alert(session);
$.mobile.changePage("#mainMenu");
}
When I run the application and log in. It runs though no problem but when it reaches alert(session) it returns undefined. I have both session and username set globally as variables so that isn't an issue and when it reaches alert(username), it returns the username I entered.
I was able to solve my issue by adding in a for loop into the sessionData function
function sessionData(data){
for(var i = 0; i < 1; i++)
{
sessionStorage.code = data[i].sessionCode;
}
$.mobile.changePage("#mainMenu");
}
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 am new to php/ajax/jquery and am having some problems. I am trying to pass json to the php file, run some tasks using the json data and then issue back a response. I am using the facebook api to get log in a user,get there details, traslate details to json, send json toe the server and have the server check if the users id already exists in the database. Here is my javascript/jquery
function checkExisting() {
FB.api('/me', function(response) {
console.log('Successful login for: ' + response.id );
var json = JSON.stringify(response);
console.log(json);
$.ajax({
url: "php.php",
type: "POST",
data: {user: json},
success: function(msg){
if(msg === 1){
console.log('It exists ' + response.id );
} else{
console.log('not exists ' + response.id );
}
}
})
});
}
Here is my php file
if(isset($_POST['user']) && !empty($_POST['user'])) {
$c = connect();
$json = $_POST['user'];
$obj = json_decode($json, true);
$user_info = $jsonDecoded['id'];
$sql = mysql_query("SELECT * FROM user WHERE {$_GET["id"]}");
$count = mysql_num_rows($sql);
if($count>0){
echo 1;
} else{
echo 0;
}
close($c);
}
function connect(){
$con=mysqli_connect($host,$user,$pass);
if (mysqli_connect_errno()) {
echo "Failed to connect to Database: " . mysqli_connect_error();
}else{
return $con;
}
}
function close($c){
mysqli_close($con);
}
I want it to return either 1 or 0 based on if the users id is already in the table but it just returns a lot of html tags. . The json looks like so
{"id":"904186342276664","email":"ferrylefef#yahoo.co.uk","first_name":"Taak","gender":"male","last_name":"Sheeen","link":"https://www.facebook.com/app_scoped_user_id/904183432276664/","locale":"en_GB","name":"Tadadadn","timezone":1,"updated_time":"2014-06-15T12:52:45+0000","verified":true}
Fix the query part:
$sql = mysql_query("SELECT * FROM user WHERE {$_GET['id']}");
Or another way:
$sql = mysql_query("SELECT * FROM user WHERE ". $_GET['id']);
Then it's always better to use dataType in your ajax
$.ajax({
url: "php.php",
type: "POST",
data: {user: json},
dataType: "jsonp", // for cross domains or json for same domain
success: function(msg){
if(msg === 1){
console.log('It exists ' + response.id );
} else{
console.log('not exists ' + response.id );
}
}
})
});
Where is $jsonDecoded getting assigned in your PHP? Looks unassigned to me.
I think you meant to say:
$obj = json_decode($json, true);
$user_info = $obj['id'];
And your SELECT makes no sense. Your referencing $_GET during a POST. Maybe you meant to say:
$sql = mysql_query("SELECT * FROM user WHERE id = {$user_info}");
I am building a website that uses jQuery/AJAX to send data to a php page, and from there insert it into a database. For some reason, the code isn't inserted and I get no response at all.
my javascript:
function insert_data(){
var title = debate_title.value;
var subtitle = debate_sub.value;
var sides = debate_sides.value;
$(function() {
$.ajaxSetup({
error: function(jqXHR, exception) {
if (jqXHR.status === 0) {
window.location.replace('errors/noConnection.html');
} else if (jqXHR.status == 404) {
window.location.replace('errors/noConnection.html');
} else if (jqXHR.status == 500) {
window.location.replace('errors/noConnection.html');
} else if (exception === 'parsererror') {
window.location.replace('errors/noConnection.html');
} else if (exception === 'timeout') {
window.location.replace('errors/noConnection.html');
} else if (exception === 'abort') {
window.location.replace('errors/noConnection.html');
} else {
window.location.replace('errors/noConnection.html');
}
}
});
});
$.ajax({
type: "POST",
url: "post_debate.php",
data: { post_title: title, post_sub: subtitle, post_sides: sidesm, ajax: 1 },
dataType: "json",
timeout: 5000, // in milliseconds
success: function(data) {
if(data!==null){
window.location.replace('show_debate.php?id=' + data);
}else{
window.location.replace('errors/noConnection.html');
}
}
});
}
My PHP code (post_debate.php):
<?php
require('connect.php');
$title = $_POST['post_title'];
$subtitle = $_POST['post_sub'];
$sides = $_POST['post_sides'];
$ajax = $_POST['ajax'];
$date = new DateTime();
$timeStamp = $date->getTimeStamp();
if($ajax==1){
$query = mysql_query("INSERT INTO debates VALUES('','$title','$subtitle','$sides','0','0','$timeStamp')");
$get_data = mysql_query("SELECT id FROM debates WHERE title='$title', subtitle='$subtitle', sides='$sides', timestamp='$timeStamp'");
while($id=mysql_fetch_array($get_data)){
$final_id = $id['id'];
}
exit($final_id);
}else{
die("404 SERVER ERROR");
}
?>
Thanks!
EDIT - NOT SOLVED YET
My new PHP code:
<?php
header("content-type: application/json");
require('connect.php');
$title = $_POST['post_title'];
$subtitle = $_POST['post_sub'];
$sides = $_POST['post_sides'];
$ajax = $_POST['ajax'];
$date = new DateTime();
$timeStamp = $date->getTimeStamp();
if($ajax==1){
$query = mysql_query("INSERT INTO debates VALUES('','$title','$subtitle','$sides','0','0','$timeStamp')");
$get_data = mysql_query("SELECT id FROM debates WHERE title='$title', subtitle='$subtitle', sides='$sides', timestamp='$timeStamp'");
while($id=mysql_fetch_array($get_data)){
$final_id = $id['id'];
}
print (json_encode(array("Id"=>$final_id)));
}else{
die("404 SERVER ERROR");
}
?>
my new Javascript .ajax:
$.ajax({
type: "POST",
url: "post_debate.php",
data: { post_title: title, post_sub: subtitle, post_sides: sides, ajax: 1 },
dataType: "json",
timeout: 5000, // in milliseconds
success: function(data) {
if(data!==null){
window.location.replace('show_debate.php?id=' + data['Id']);
}else{
window.location.replace('errors/noConnection.html');
}
}
});
Your code is expecting JSON as a response...
dataType: "json",
(Documentation Here)
But you're returning a non-json value without an appropriate content-type header.
Try changing your PHP script from
exit($final_id);
to (untested)
header("content-type: application/json");
print (json_encode(array(
"Id"=>$final_id
)));
Also, put a breakpoint on your success callback in your Javascript code (using Firebug or a similar tool) and examine what data contains. It should now be an associative array so you can do
window.location.replace('show_debate.php?id=' + data['Id']);
Improvement:
Instead of doing a SELECT to get the recently inserted Id, use mysql_insert_id(). Something like this...
$query = mysql_query("INSERT INTO debates VALUES('','$title','$subtitle','$sides','0','0','$timeStamp')");
$final_id = mysql_insert_id();
print (json_encode(array("Id"=>$final_id)));
Also, an alternate way to test what your PHP is returning if you can't see the response in your development tool is to browse to the page directly (You'd have to change all your $_POST to $_REQUEST)
I have some ajax code that executes on mouseclick. It calls a file called update.php that does a bunch of stuff, including checking for user permissions, numerous database calls, etc. In the end, I also want to be able to return a few variables from PHP for the callback to use, but not sure how to reference them - or if there's a better way to return this info.
$.ajax({
type: "POST",
url: "update.php",
data: dataString,
success: callback
});
function callback(data, status)
{
// $("div").text(data);
$("div.numbert").text("[first variable here]");
$("div.numbert2").text("[second variable here]");
}
From my update.php file (some snippets):
if ($check_access > 0)
{
// Update database
$sql = "UPDATE db SET access = '1' WHERE user = '$user'";
$result = mysql_query($sql) or die(mysql_error());
// Give access - function returns data to variable
$value = GiveAccess($user);
// Email - function returns data to variable
$emaillist = emailAdmins($user);
} else {
$message = "Sorry you do not have access";
}
So I'd like to figure out how to use the variables $message, $value and $emaillist in my callback if possible.
I'm wondering if I just need to make multiple $.ajax POST calls, with each .php function that returns a variable having it's own call?
Thanks!
----UPDATE-------
Updated code trying to use the json methods - thanks for all the help - but seems I'm missing one last thing.
$.ajax({
type: "POST",
url: "update.php",
data: dataString,
dataType: 'json',
success: callback
});
function callback(data, status)
{
// $("div").text(data);
$("div.numbert").text(data.value);
$("div.numbert2").text(data.emaillist);
and update.php:
$storage = array();
// Update database
$sql = "UPDATE db SET access = '1' WHERE user = '$user'";
$result = mysql_query($sql) or die(mysql_error());
// Give access - function returns data to variable
$storage['value'] = "some user";
// Email - function returns data to variable
$storage['emaillist'] = "some stuff";
header('Content-type: application/json');
echo json_encode($storage);
exit(0);
Thanks again.
You can use a JSON wrapper:
$messages = array();
$messages['value'] = GiveAccess($user);
$messages['emaillist'] = emailAdmins($user);
$messages['message'] = "Sorry you do not have access";
echo json_encode($messages);
And then simply use:
data.value data.emaillist data.message
in your Javascript.
Easiest way would be to use JSON...
$.ajax({
type: "POST",
url: "update.php",
data: dataString,
dataType: 'json',
success: callback
});
function callback(data, status)
{
// $("div").text(data);
if(data.error){
alert(error.message||'Unknown Error');
} else {
$("div.numbert").text(data.access||'No value');
$("div.numbert2").text(data.emailList||'No value');
}
}
PHP:
if ($check_access > 0)
{
// Update database
$sql = "UPDATE db SET access = '1' WHERE user = '$user'";
$result = mysql_query($sql) or die(mysql_error());
$responseData = array();
// Give access - function returns data to variable
$responseData['access'] = GiveAccess($user);
// Email - function returns data to variable
$responseData['emailList'] = emailAdmins($user);
} else {
$responseData['error'] = array('code' => 403, 'message' => "Sorry you do not have access");
}
header('Content-type: application/json');
print json_encode($responseData);
exit(0);
No, just return a JSON object or a dataset that's delimited that you can parse.
You can return your values using json:
$storage = array();
if ($check_access > 0)
{
// Update database
$sql = "UPDATE db SET access = '1' WHERE user = '$user'";
$result = mysql_query($sql) or die(mysql_error());
// Give access - function returns data to variable
$value = GiveAccess($user);
$storage['value'] = $value;
// Email - function returns data to variable
$emaillist = emailAdmins($user);
$storage['emaillist'] = $emaillist;
} else {
$message = "Sorry you do not have access";
$storage['message'] = $message;
}
header("Content-Type: application/json; charset=utf8");
$return = json_encode($storage);
echo $return;
exit;
You can then iterate over the object and go
function callback(data, status)
{
// $("div").text(data);
$("div.numbert").text(data.value);
$("div.numbert2").text(data.emaillist);
}