Json returns undifined - php

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;

Related

Fetch Request Form Data Shown As Null

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;
}
}
?>

AJAX code seems to be ok, but it doesn't show anything

So I have a live chat, and when the user clicks the button, this function should kick into action and insert it into the database and into the HTML conversation section.
The first problem is that if i use dataType: "json" , then it enters the AJAX error case instead of success. But if I pull it out, like below, it enters the success case. But here comes the second problem: only the first alert is displayed, and if I try to alert the response, it doesn't show anything (+neither the alert('yes') is displayed).
function sendMessage(to_user_id) {
message = $(".message-input input").val();
$('.message-input input').val('');
if($.trim(message) == '') {
return false;
}
$.ajax({
url:"chat_action.php",
method:"POST",
data:{to_user_id:to_user_id, chat_message:message, action:'insert_chat'},
success:function(response) {
alert('no');
var resp = JSON.parse(response);
$('#conversation').html(resp.conversation);
$(".messages").animate({ scrollTop: $('.messages').height() }, "fast");
alert('yes');
},
});
}
EDIT1:
It might be useful to understand my files:
I have index.php which contains the actual chat. When the send button is clicked, it accesses the chat.js file that contains the script above. Then, this is the part of chat_action.php that deals with it and passes it further to Chat.php.
chat_action.php
session_start();
include ('Chat.php');
$chat = new Chat();
if($_POST['action'] == 'insert_chat') {
$chat->insertChat($_POST['to_user_id'], $_SESSION['userid'], $_POST['chat_message']);
}
Chat.php
<?php
class Chat{
private $host = 'localhost';
private $user = 'root';
private $password = "";
private $database = "chat_demo";
private $chatTable = 'chat';
private $chatUsersTable = 'chat_users';
private $chatLoginDetailsTable = 'chat_login_details';
private $dbConnect = false;
public function __construct(){
if(!$this->dbConnect){
$conn = new mysqli($this->host, $this->user, $this->password, $this->database);
if($conn->connect_error){
die("Error failed to connect to MySQL: " . $conn->connect_error);
}else{
$this->dbConnect = $conn;
}
}
}
public function insertChat($reciever_userid, $user_id, $chat_message) {
$sqlInsert = "
INSERT INTO ".$this->chatTable."
(reciever_userid, sender_userid, message, status)
VALUES ('".$reciever_userid."', '".$user_id."', '".$chat_message."', '1')";
$result = mysqli_query($this->dbConnect, $sqlInsert);
if(!$result){
return ('Error in query: '. mysqli_error($this->dbConnect));
} else {
$conversation = $this->getUserChat($user_id, $reciever_userid);
$data = array(
"conversation" => $conversation
);
echo json_encode($data);
}
}
public function getUserChat($from_user_id, $to_user_id) {
$fromUserAvatar = $this->getUserAvatar($from_user_id);
$toUserAvatar = $this->getUserAvatar($to_user_id);
$sqlQuery = "
SELECT * FROM ".$this->chatTable."
WHERE (sender_userid = '".$from_user_id."'
AND reciever_userid = '".$to_user_id."')
OR (sender_userid = '".$to_user_id."'
AND reciever_userid = '".$from_user_id."')
ORDER BY timestamp ASC";
$userChat = $this->getData($sqlQuery);
$conversation = '<ul>';
foreach($userChat as $chat){
$user_name = '';
if($chat["sender_userid"] == $from_user_id) {
$conversation .= '<li class="replies">';
$conversation .= '<img width="22px" height="22px" src="userpics/'.$fromUserAvatar.'" alt="" />';
} else {
$conversation .= '<li class="sent">';
$conversation .= '<img width="22px" height="22px" src="userpics/'.$toUserAvatar.'" alt="" />';
}
$conversation .= '<p>'.$chat["message"].'</p>';
$conversation .= '</li>';
}
$conversation .= '</ul>';
return $conversation;
}
private function getData($sqlQuery) {
$result = mysqli_query($this->dbConnect, $sqlQuery);
if(!$result){
die('Error in query: '. mysqli_error($this->dbConnect));
}
$data= array();
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$data[]=$row;
}
return $data;
}
public function getUserAvatar($userid){
$sqlQuery = "
SELECT avatar
FROM ".$this->chatUsersTable."
WHERE userid = '$userid'";
$userResult = $this->getData($sqlQuery);
$userAvatar = '';
foreach ($userResult as $user) {
$userAvatar = $user['avatar'];
}
return $userAvatar;
}
}
EDIT2:
From the console:
chat.js:106
index.php:1 Uncaught SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at Object.success (chat.js:107)
at j (jquery.min.js:2)
at Object.fireWith [as resolveWith] (jquery.min.js:2)
at x (jquery.min.js:4)
at XMLHttpRequest.<anonymous> (jquery.min.js:4)
you try to parsing not valid json, in your js maybe try this:
function sendMessage(to_user_id) {
message = $(".message-input input").val();
$('.message-input input').val('');
if($.trim(message) == '') {
return false;
}
$.ajax({
url:"chat_action.php",
method:"POST",
data:{to_user_id:to_user_id, chat_message:message, action:'insert_chat'},
success:function(response) {
alert('no');
try {
var resp = JSON.parse(response);
$('#conversation').html(resp.conversation);
} catch(e) { alert(e) }
$(".messages").animate({ scrollTop: $('.messages').height() }, "fast");
alert('yes');
},
});
}

Php ajax just want to display error message only form submit

After send my form data to php file its return if any error found. But its also return success before ajax redirect page. I want display error message only and if success, redirect another page.
ajax:
$("#msform").submit(function(){
$.ajax({
type:"post",
url:"pagesubmit.php",
data: $("#msform").serialize(),
dataType : 'json',
success: function(data){
if ( ! data.success) {
$(".help-block").fadeIn().html(data.error);
} else {
$(".help-block").fadeOut();
$("#msform")[0].reset();
window.location = 'http://dbsvawdez.com/' + data.success;
}
}
});
});
php:
include_once ("db.php");
global $dbh;
function check($name){
if(!$name || strlen($name = trim($name)) == 0){
$error ="* Username not entered";
}
else{
$name = stripslashes($name);
if(strlen($name) < 5){
$error ="* Name below 5 characters";
}
else if(!preg_match("/^([0-9a-z])+$/i", $name)){
$error ="* Name not alphanumeric";
}
else {
return 1;
}
}
}
$name = mysqli_real_escape_string($dbh, $_POST['name']);
$thisname = strtolower($name);
$retval = check($thisname);
if($retval ==1){ // if no error found
$success ='upage/userpage?user='.$_SESSION['username'].'';
}
$data = array();
$data['error'] = $error;
$data['success'] = $success;
if (!empty($data)) {
echo json_encode($data);
}
Solved the problem, in this way:
Ajax:
$("#msform").submit(function(){
// collect input name
ver name = var catag=$('#name').val();
$.ajax({
type:"post",
url:"pagesubmit.php",
data: $("#msform").serialize(),
success: function(data){
if ( data != 'success') {
$(".help-block").fadeIn().html(data);
} else {
$(".help-block").fadeOut();
$("#msform")[0].reset();
window.location = 'http://dbsvawdez.com/' + name;
}
}
});
});
php:
function check($name){
if(!$name || strlen($name = trim($name)) == 0){
echo "* Username not entered";
}
else{
$name = stripslashes($name);
if(strlen($name) < 5){
echo "* Name below 5 characters";
}
else if(!preg_match("/^([0-9a-z])+$/i", $name)){
echo "* Name not alphanumeric";
}
else {
return 1;
}
}
}
$name = mysqli_real_escape_string($dbh, $_POST['name']);
$thisname = strtolower($name);
$retval = check($thisname);
if($retval ==1){ // if no error found
echo 'success';
}
EDIT
Set your variables $success and $error
$success = "";
$error= "";
If you doesn't init them, you cannot use them and the .=operator is for concatenation not for set.
Then you should encode the response in php in JSON.
Something like
$response = json_encode(
array(
'success'=> true,
'route' => "mypage/info?user=$_SESSION['username']"
)
);
And return this, then access your response like you already do :
var success = response.success;
UPDATE
change this code to add an else statement :
if($retval ==1){ // if no error found
$success ='upage/userpage?user='.$_SESSION['username'].'';
}else{
$success = 'error';
}
and this line :
else {
return 1;
}
to :
else {
$error = 'none';
}
and in your javascript :
$("#msform").submit(function(){
$.ajax({
type :"post",
url :"pagesubmit.php",
data : $("#msform").serialize(),
dataType : 'json',
success : function(data){
if(data.success == 'error') {
$(".help-block").fadeIn().html(data.error);
}else{
$(".help-block").fadeOut();
$("#msform")[0].reset();
window.location = 'http://dbsvawdez.com/' + data.success;
}
}
});
});

Print exception in Ajax thrown from 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);
}

php ajax login form

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);
},
...

Categories