I am implementing a app with a login-screen. and I don't know how i should implement the json response for sencha touch.
this is my login.js
Ext.Ajax.request({
url: 'http://localhost/alt/FIFA-Europaliga/admin/index.php?page=login_try_app',
method: 'post',
params: {
login: Ext.getCmp('username').getValue(),
password: Ext.getCmp('passwort').getValue(),
},
failure: function (response) {
var loginResponse = Ext.JSON.decode(response.responseText);
if (loginResponse.success === "false") {
alert('fail');
}
},
success: function (response) {
//console.log(response);
//console.log(response.responseText);
var loginResponse = Ext.JSON.decode(response.responseText);
if (loginResponse.success === "true") {
Ext.Viewport.setActiveItem("mainview",{
type: "pop",
direction: "left"
});
}
},
});
and this is my login_try.php
<?php
$result = "{'success':false}";
if (count($_POST) > 0) {
$_POST = $sys->db->sql_filter($_POST);
$login = $_POST['login'];
$password = $_POST['password'];
$user = new User($login, $password);
if ($user->login($sys->db)) {
session_start();
$_SESSION['user'] = $user;
$result = "{'success':true}";
} else {
$result = "{'success':false}";
}
} else {
$result = "{'success':false}";
}
echo $result;
echo json_encode($result);
?>
now I get the full login.php file from the server as response. and I want only a true or false
Can you help me?
Thank you!
Sebastian
Probably ' issue. Try using array and json_encode(). Do not echo $result as is.
// default false
$result = array('success' => false);
//...
$result['success'] = true;
}
echo json_encode($result);
And there is no reason to make success false in the middle of the code (default false already).
Related
Here my php code. I need to redirect to another page when if($users[$name] === $password) or when $users[$name] = $password; but it does not work.What is wrong?Here ajax too.
$(document).ready(function() {
$('#submit').click(function() {
var name = $('#username').val();
var password = $('#password').val();
$.ajax({
type: 'POST',
url: 'php/login_script.php',
data: {
user: name,
pass: password
},
success: function(a) {
alert(a);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<?php
if(!isset($_POST['user'])||!isset($_POST['pass'])){
die();
}
$file = "users.json";
$users = json_decode(file_get_contents($file), true);
$name = $_POST['user'];
$password = $_POST['pass'];
if(isset($users[$name])) {
if($users[$name] === $password){
header("Location:chat.html");
exit;
}
else {
echo "Wrong password";
}
}
else {
$users[$name] = $password;
file_put_contents($file, json_encode($users, JSON_PRETTY_PRINT));
header("Location:chat.html");
exit;
}
Because you're fetching the page with ajax the redirection will happen to the ajax request which means you will get back a 301 response.
This should work:
$(document).ready(function() {
$('#submit').click(function() {
var name = $('#username').val();
var password = $('#password').val();
$.ajax({
type: 'POST',
url: 'php/login_script.php',
data: {
user: name,
pass: password
},
success: function(a) {
document.location = 'chat.html';
},
error: function() {
alert('Invalid password');
}
});
});
});
and
<?php
if(!isset($_POST['user'], $_POST['pass']) || empty($_POST['user']) || empty($_POST['pass'])){
// Send bad request so redirect doesn't happen
http_response_code(400);
die();
}
$file = "users.json";
$users = json_decode(file_get_contents($file), true);
$name = $_POST['user'];
$password = $_POST['pass'];
if(isset($users[$name])) {
if($users[$name] != $password){
http_response_code(400);
echo "Wrong password";
}
}
else {
$users[$name] = $password;
file_put_contents($file, json_encode($users, JSON_PRETTY_PRINT));
}
This will return 200 on success and 400 on failure which will trigger the success and error parts of the $.ajax request.
The thing you need to realize about PHP is all of the PHP stuff is done before sending the page to the user, so calling a redirect on php/login_script.php does nothing.
What you need to do is return something to indicate success of the login.
Here's what you should do to understand my explanation:
Replace header("Location:chat.html"); with echo "success"; in your PHP code.
Change your jQuery to the following:
success: function(a)
{
if (a === "success")
{
window.location.replace("chat.html");
}
}
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'm creating a follow button, more or less like the twitter one.
You click the button, and you follow the user.
You click again, and you unfollow the user.
I have done this code
HTML
<div data-following="false" class='heart canal'><i class='fa fa-heart awesome'></i></div>
AJAX
$(document).ready(function() {
$(".heart.canal").click(function() {
if($(".heart").attr("data-following") == '0'){
$(".heart").attr('data-following', '1');
} else if($(".heart").attr("data-following") == '1'){
$(".heart").attr('data-following', '0');
}
var usuario = $(".left h4").attr("data-id");
var seguidor = $("#user_account_info .profile_ball").attr("data-id");
var seguir = $(".heart").attr("data-following");
$.ajax({
type: "POST",
url: "./include/php/follow.php",
data: { user: usuario, follower: seguidor, follow: seguir },
success: function(response) {
if(response == '0'){
$(".heart").addClass("like");
} else if(response == '1'){
$(".heart").removeClass("like");
}
}
});
return false;
});
});
PHP
<?php
$dsn = "mysql:host=localhost;dbname=tapehd;charset=utf8";
$usuario = "root";
$contraseƱa = "";
$conexion = new PDO($dsn, $usuario, $contraseƱa);
$resultado = null;
$sql = "";
$user = $_POST["user"];
$seguidor = $_POST["follower"];
$follow = $_POST["follow"];
if($follow == '0'){
$sql = "INSERT INTO seguidores(id_canal, id_seguidor) VALUES('$user', '$seguidor')";
} else if($follow == '1'){
$sql = "DELETE FROM seguidores WHERE id_canal = '$user' AND id_seguidor= '$seguidor'";
}
if($conexion){ $resultado = $conexion->query($sql); }
return $follow;
?>
The problem is, everytime I click the button, I only insert data in the database. I mean, I only create follows.
When I click twice, it doesnt remove the follow.
Is there anyway to insert data when data-following = true and remove it when data-following = false ?
UPDATED
I have changed the boolean false and true for 2 strings, 0 and 1. But it doesn't work anyway.
There are numerous problems here. For one, like #Mark said, you need to understand that when sending ajax requests to PHP, you are sending strings. Also, in your JS, you are binding a click function to the .heart.canal, but then the function changes all elements with that class rather than the actual clicked element. Lastly, once you send the right information to PHP you need to print your results in order to see it in ajax.
Try the following:
JS:
$(document).ready(function () {
$(".heart.canal").click(function () {
var $heart = $(this);
if ($heart.data("following")) {
$heart.data("following", false)
} else {
$heart.data("following", true);
}
var usuario = $(".left").find("h4").data("id");
var seguidor = $("#user_account_info").find(".profile_ball").data("id");
$.ajax({
type: "POST",
url: "follow.php",
data: {user: usuario, follower: seguidor, follow: $heart.data("following")},
success: function (result) {
if (result) {
console.log("true");
} else {
console.log("false");
}
}
});
return false;
});
});
PHP:
$user = (int)$_POST["user"];
$seguidor = (int)$_POST["follower"];
$follow = ($_POST["follow"] === 'true') ? true : false;
if ($follow) {
// insert
} else {
// delete
}
print $follow;
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 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';
...