I new to PHP and this might not even be a problem. I have a JavaScript function that sends fetch request. When I send to the api.php, I get a null when I var_dump() the variable $studentnumber. I checked the fetch request and it's sending data in the request, so there is something wrong with PHP reading the form data... maybe?. Thanks in advance this was for a school assignment.
Fetch Request
function login() {
var studentnumber = document.getElementById("studentnumber");
var password = document.getElementById("password");
var logindetails = new FormData();
logindetails.append('studentnumber', studentnumber.value);
logindetails.append('password', password.value);
fetch('http://localhost/gaq/api/api.php?action=login', {
method: 'POST',
body: logindetails,
}
)
.then(function(response){
if (response.status == 202) {
var studentnumber = document.getElementById("studentnumber");
var logindetails = new FormData();
logindetails.append('studentnumber', studentnumber.value);
fetch('http://localhost/gaq/api/api.php?action=processlogin', {
method: 'POST',
body: logindetails,
});
console.log("Success");
} else {
console.log("Error");
}
})
}
API.PHP File
<?php
include 'database.php';
include 'session.php';
session_start();
//header('Content-Type: application/json');
$functions = new gaqfunctions();
if(!isset($_SESSION['user_session'])) {
$_SESSION['user_session'] = new gaqsession;
http_response_code(501);
die();
}
if(isset($_GET['action'])) {
switch($_GET['action']) {
case "login":
if($_SESSION['user_session']->userloginstatus()) {
$studentnumber = $_POST['studentnumber'];
$password = $_POST['password'];
$response = $_SESSION['user_session']->login($studentnumber, $password);
http_response_code(206);
if ($response == true) {
http_response_code(202);
} else {
http_response_code(404);
}
} else {
http_response_code(401);
}
break;
case "processlogin":
if($_SESSION['user_session']->userloginstatus()) {
$studentnumber = $_POST['studentnumber'];
var_dump($studentnumber);
//$studentnumber = isset($_POST['studentnumber']) ? $_POST['studentnumber'] : 0;
$_SESSION['user_session']->loginprocess($studentnumber);
http_response_code(206);
} else {
http_response_code(401);
}
break;
default:
http_response_code(400);
break;
}
}
?>
Related
Good day guys I have the following login page. Which I access using ajax from my view page. The problem the data that is returned when I try to display on ajax I get an error on the console.
login.js:35 Uncaught TypeError: Cannot read property 'success' of
undefined
at Object.success (login.js:35)
at i (jquery-2.2.0.min.js:2)
at Object.fireWith [as resolveWith] (jquery-2.2.0.min.js:2)
at z (jquery-2.2.0.min.js:4)
at XMLHttpRequest. (jquery-2.2.0.min.js:4)
<?php
ob_start();
function __autoload($classname)
{
require_once("../../database/$classname.php");
}
class userlogin extends database
{
private $errors = array();
private $message = array();
private $redirect = array();
private $data = array();
private $username;
private $password;
function login()
{
if (empty($_POST['username']) || empty($_POST['password'])) {
$this->message['error'] = "Please enter username and password";
} else {
$this->username = $_POST['username'];
$this->password = $_POST['password'];
try {
$this->stmt = $this->dbh->prepare("SELECT adminID,adminEmail,adminPassword,admintype FROM admin where adminEmail = ? ");
$this->stmt->execute(array(
$this->username
));
$this->results = $this->stmt->fetchall();
if (count($this->results) > 0) {
foreach ($this->results as $key => $row) {
if (password_verify($this->password, $row['adminPassword'])) {
$_SESSION['user'] = $row['adminID'];
$_SESSION['email'] = $this->username;
$_SESSION['usertype'] = $row['admintype'];
switch ($row['admintype']) {
case 's':
$this->redirect['redirect'] = "seo/index.php?route=home";
break;
case 'a':
$this->redirect['redirect'] = "admin/index.php?route=home";
break;
}
$this->message['success'] = "ok";
} else {
$this->message['error'] = "Username and password does not match";
}
}
} else {
$this->message['error'] = "Username does not exist";
}
}
catch (PDOException $pdo) {
$this->error = $pdo->getMessage();
error_log($this->error);
}
$this->data['message'] = $this->message;
$this->data['redirects'] = $this->redirect;
ob_end_clean();
echo json_encode($this->data);
}
}
}
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$login = new userlogin();
$login->login();
}
?>
and my js
function proccessLogin(){
var username = $('input[type="email"][name="email"]').val();
var password = $('input[type="password"][name="upass"]').val();
$.ajax({
type : "POST",
data : {username:username,password:password},
url : "controller/login.php",
beforeSend : function(){
$('button').html('Checking...');
},
success : function(data){
console.log(data);
if(data.message.success == "ok"){
$('#results').removeClass('error');
$('#results').addClass('success');
$('#results').html('login Success, loading user data..');
$('button').html('Loading Profile.. i class="fa fa-spinner fa-pulse fa-1x fa-fw"></i>');
var redirectUrl = JSON.stringify(data.redirects);
redirectUrl = redirectUrl.replace(/[{"":}]/g, '');
var url = redirectUrl.replace('redirect','');
setTimeout(' window.location.href = "'+ url + '"; ', 6000);
}else{
$('button').html("Sign in");
$('#results').removeClass('success');
$('#results').addClass('error');
$('#results').html(data.message.error);
}
},
error : function(xhr){
console.log('Error : ' + xhr);
}
});
return false;
}
Console log results :
{"message":{"success":"ok"},"redirects":{"redirect":"seo\/index.php?route=home"}}
I want to be able to display the message from the json array if success is ok I will display custome message else display what is coming from response. the problem is property undefined.
line 35 :
if(data.message.success == "ok"){
I think the response data is String and you need to call
$.parseJSON(data);
before you can access message and then success
=============
If you want to use dataType: "json", you need to send your JSON as JSON by using PHP's header() function:
/* Send as JSON */
header("Content-Type: application/json", true);
/* Return JSON */
echo json_encode($json);
/* Stop Execution */
exit;
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");
}
}
I have this code. The problem is: It is not obeying 'ORDER BY NAME ASC' on query and I don't know why. It is happening in all 3 functions.
Here is the code:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once("dbconfig.php");
class location extends dbconfig {
public static $data;
function __construct() {
if (in_array('__construct', get_class_methods(get_parent_class($this)))) {
parent::__construct();
}
}
public static function getCountries() {
try {
$query = "SELECT id, name FROM countries ORDER BY name ASC";
$result = dbconfig::run($query);
if(!$result) {
throw new exception("Country not found.");
}
$res = array();
while($resultSet = mysqli_fetch_assoc($result)) {
$res[$resultSet['id']] = $resultSet['name'];
}
$data = array('status'=>'success', 'tp'=>1, 'msg'=>"Countries fetched successfully.", 'result'=>$res);
} catch (Exception $e) {
$data = array('status'=>'error', 'tp'=>0, 'msg'=>$e->getMessage());
} finally {
return $data;
}
}
public static function getStates($countryId) {
try {
$query = "SELECT id, name FROM states WHERE country_id=".$countryId." ORDER BY name ASC";
$result = dbconfig::run($query);
if(!$result) {
throw new exception("State not found.");
}
$res = array();
while($resultSet = mysqli_fetch_assoc($result)) {
$res[$resultSet['id']] = $resultSet['name'];
}
$data = array('status'=>'success', 'tp'=>1, 'msg'=>"States fetched successfully.", 'result'=>$res);
} catch (Exception $e) {
$data = array('status'=>'error', 'tp'=>0, 'msg'=>$e->getMessage());
} finally {
return $data;
}
}
public static function getCities($stateId) {
try {
$query = "SELECT id, name FROM cities WHERE state_id=".$stateId." ORDER BY name ASC";
$result = dbconfig::run($query);
if(!$result) {
throw new exception("City not found.");
}
$res = array();
while($resultSet = mysqli_fetch_assoc($result)) {
$res[$resultSet['id']] = $resultSet['name'];
}
$data = array('status'=>'success', 'tp'=>1, 'msg'=>"Cities fetched successfully.", 'result'=>$res);
} catch (Exception $e) {
$data = array('status'=>'error', 'tp'=>0, 'msg'=>$e->getMessage());
} finally {
return $data;
}
}
}
Javascript
function ajaxCall() {
this.send = function(data, url, method, success, type) {
type = type||'json';
var successRes = function(data) {
success(data);
};
var errorRes = function(e) {
console.log(e);
alert("Error found \nError Code: "+e.status+" \nError Message: "+e.statusText);
};
$.ajax({
url: url,
type: method,
data: data,
success: successRes,
error: errorRes,
dataType: type,
timeout: 60000
});
}
}
function locationInfo() {
var rootUrl = "../PDOClasses/CountriesList/api.php";
var call = new ajaxCall();
this.getCities = function(id) {
$(".cities option:gt(0)").remove();
var url = rootUrl+'?type=getCities&stateId=' + id;
var method = "post";
var data = {};
$('.cities').find("option:eq(0)").html("Carregando..");
call.send(data, url, method, function(data) {
$('.cities').find("option:eq(0)").html("Selecione a cidade");
if(data.tp == 1){
$.each(data['result'], function(key, val) {
var option = $('<option />');
option.attr('value', key).text(val);
$('.cities').append(option);
});
$(".cities").prop("disabled",false);
}
else{
alert(data.msg);
}
});
};
this.getStates = function(id) {
$(".states option:gt(0)").remove();
$(".cities option:gt(0)").remove();
var url = rootUrl+'?type=getStates&countryId=' + id;
var method = "post";
var data = {};
$('.states').find("option:eq(0)").html("Carregando..");
call.send(data, url, method, function(data) {
$('.states').find("option:eq(0)").html("Selecione o estado");
if(data.tp == 1){
$.each(data['result'], function(key, val) {
var option = $('<option />');
option.attr('value', key).text(val);
$('.states').append(option);
});
$(".states").prop("disabled",false);
}
else{
alert(data.msg);
}
});
};
this.getCountries = function() {
var url = rootUrl+'?type=getCountries';
var method = "post";
var data = {};
$('.countries').find("option:eq(0)").html("Carregando..");
call.send(data, url, method, function(data) {
$('.countries').find("option:eq(0)").html("Selecione o paĆs");
console.log(data);
if(data.tp == 1){
$.each(data['result'], function(key, val) {
var option = $('<option />');
option.attr('value', key).text(val);
$('.countries').append(option);
});
$(".countries").prop("disabled",false);
}
else{
alert(data.msg);
}
});
};
}
$(function() {
var loc = new locationInfo();
loc.getCountries();
$(".countries").on("change", function(ev) {
var countryId = $(this).val();
if(countryId != ''){
loc.getStates(countryId);
}
else{
$(".states option:gt(0)").remove();
}
});
$(".states").on("change", function(ev) {
var stateId = $(this).val();
if(stateId != ''){
loc.getCities(stateId);
}
else{
$(".cities option:gt(0)").remove();
}
});
});
and api
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ob_start();
header("Access-Control-Allow-Origin: *");
header('Content-Type: application/json');
include_once("location.php");
$loc = new location();
try {
if(!isset($_GET['type']) || empty($_GET['type'])) {
throw new exception("Type is not set.");
}
$type = $_GET['type'];
if($type=='getCountries') {
$data = $loc->getCountries();
}
if($type=='getStates') {
if(!isset($_GET['countryId']) || empty($_GET['countryId'])) {
throw new exception("Country Id is not set.");
}
$countryId = $_GET['countryId'];
$data = $loc->getStates($countryId);
}
if($type=='getCities') {
if(!isset($_GET['stateId']) || empty($_GET['stateId'])) {
throw new exception("State Id is not set.");
}
$stateId = $_GET['stateId'];
$data = $loc->getCities($stateId);
}
} catch (Exception $e) {
$data = array('status'=>'error', 'tp'=>0, 'msg'=>$e->getMessage());
} finally {
echo json_encode($data);
}
ob_flush();
Can someone help me please? I'm about 3 hours trying asort and other functions but no success.
javascript > api > php
I am trying to make a POST request to a Url using Ajax. My JS/JQuery code looks like this
var params = {
'username' : 'eddard.stark#got.com',
'name' : 'Eddard Stark'
};
$.post("/user/add", params, function(data) {
// no errors
var user = eval('(' + data + ')');
$("#spanId").html("User Id " + user.id);
// Here - http://stackoverflow.com/questions/16472116/ajax-error-cannot-catch-thrown-exception-from-php
// they are saying that it can be handled here. But How?
}).fail(function(err, status) {
// error 4xx : client side errors (e.g. controller/action does not exist)
// error 5xx : server side errors (like db failure)
$("#spanId").html("Error " + err);
}).always(function() {
$(elm).hide();
$('#spanId').show();
});
PHP code for /user/add action is
function add()
{
$username = null;
$name = null;
if (!empty($_POST)) {
if (isset($_POST['username']) { $username = $_POST['username']; }
if (isset($_POST['name']) { $name = $_POST['name']; }
}
if (is_null($username) || is_null($name)) {
throw new Exception('Invalid request');
}
$user = $this->User->search($username);
if (isset($user)) {
thorw new Exception('User not available');
}
// ... more code ...
}
How can I print those exceptions in Ajax?
Edit:
There is another way to handle this. Set below header before throwing an exception
header("HTTP/1.1 400 User not available");
// throw exception
Then fail handler from my Ajax code can print it like
$("#spanId").html("Error : " + err.statusText)
But I don't want to do this. I want to print it in success handler itself.
here a little demonstration of my comment.
in your ajax
.done(function (response) {
if( (response.exception) === "noExp" )
{
alert("success!!!");
//no exception
}
else
{
//handle it
}
}
in php
function add()
{
$username = null;
$name = null;
$exception = "noExp";
if (!empty($_POST)) {
if (isset($_POST['username']) { $username = $_POST['username']; }
if (isset($_POST['name']) { $name = $_POST['name']; }
}
if (is_null($username) || is_null($name)) {
//throw new Exception('Invalid request');
$exception = "invalid request";
}
$user = $this->User->search($username);
if (isset($user)) {
//thorw new Exception('User not available');
$exception = "User not available";
}
// ... more code ...
$result = array(
"exception" => $exception,
//other returns
)
echo json_encode($result);
}
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).