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

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

Json returns undifined

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;

I am not able to get response in angular js $http.post

I want to check whether the email id already exists in the db. If the email id exists, it should return false, else true. I'm not able to get the response. I've attached the controller code and the php code. [the variable validUser is undefined]
Controller.js
signUpApp.controller("signUpCtrl",function($scope,$http){
$scope.register = function(form,user){
if (form.$valid)
{
$http.post("http://localhost/checkUser.php?email="+user.email)
.then(function(response){
validUser=response;
});
if(validUser=="true")
{
alert("valid user");
}
else
{
alert("already exists");
}
}
}
});
checkUser.php
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$conn = new mysqli("localhost", "root", "", "user_details");
//$data = json_decode(file_get_contents("php://input"));
//$email = mysql_real_escape_string($data->email);
$email = $_POST['email'];
$result = $conn->query("SELECT count(*) as count from user where email='$email'");
$outp = "";
$rs = $result->fetch_array(MYSQLI_ASSOC)
if ($rs['count']==0)
{
$outp ="true";
}
else
{
$outp ="false";
}
$conn->close();
echo($outp);
?>
You're not checking the response in the correct place, or rather - at the correct time.
$http.post returns immediately. Your .then callback is called when the response is returned from the server. The code after the call to post (your if statements) is executed right after $http.post returns, and before the response is received from the server.
You should place your validation code inside your callback:
$http.post(...).then(function(response) {
validUser = response;
if(validUser==="true") {
...
} else if (validUser==="false") {
...
}
}
You're if statement needs to be inside the .then callback, otherwise you'll end up checking it before youre ajax request gets responded to
signUpApp.controller("signUpCtrl",function($scope,$http){
$scope.register = function(form,user){
if (form.$valid)
{
$http.post("http://localhost/checkUser.php?email="+user.email)
.then(function(response){
validUser=response;
if(validUser=="true")
{
alert("valid user");
}
else
{
alert("already exists");
}
});
}
}
});

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

check database connection after button is click

I am building a website that has a reservation. I use ajax to send information from forms into the another page which insert the information into my database. To make it even useful, I want to make a test connection into my database. After a user fills up all the fields required he will click the submit button and a test connection must check first before sending the data. And when the connection fails, it will tell the user that the connection is not set(maybe his internet connection is lost, or the server itself is failing). In that way, the website prevents prompting the user that their reservation data is sent, but actually NOT.
EDITED:
Here's my running and fixed code:
$("#esubmit2").click(function(){
var event2 = document.getElementsByName("eevent2")[0].value;
var engager2 = document.getElementsByName("eengager2")[0].value;
var contact2 = document.getElementsByName("econtact2")[0].value;
var eadd2 = document.getElementsByName("eeadd2")[0].value;
var venue2 = document.getElementsByName("evenue2")[0].value;
var datein2 = document.getElementsByName("edatein2")[0].value;
var message2 = document.getElementsByName("emessage2")[0].value;
var reg2 = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if(event2 == "" || event2 == " "){
$("#eevent2").focus();
return false;
}
else if(engager2 == "" || engager2 == " "){
$("#eengager2").focus();
return false;
}
else if(contact2 == "" || contact2 == " "){
$("#econtact2").focus();
return false;
}
else if(venue2 == "Venue:"){
$("#evenue2").focus();
return false;
}
else if(datein2 == "" || datein2 == " "){
$("#edatein2").focus();
return false;
}
else if(message2 == "" || datein2 == " "){
$("#emessage2").focus();
return false;
}
else if(eadd2 != ""){
if(reg2.test(eadd2) == false){
$("#eeadd2").focus();
$("#eeadd2").css("backgroundColor","#800517");
$("#eeadd2").css("color","#FFFFFF");
return false;
}
else{
sendreserve_event2(); // call function sendreserve()
return false;
}
}
else{
sendreserve_event2(); // call function sendreserve()
return false;
}
})
function sendreserve_event2(){ // send informations to database
var data_string = $("form#eform2").serialize(); // IMPORTANT
$.ajax({
type: "POST",
url: "submitreserve_eventpc.php",
data: data_string,
success: function(json) {
if(json == 1){
$("#eevent2").val("");
$("#eengager2").val("");
$("#econtact2").val("");
$("#eeadd2").val("");
$("#evenue2").val("Venue:");
$("#edatein2").val("");
$("#emessage2").val("");
$("#eeadd2").css("backgroundColor","#FFFFFF");
$("#eeadd2").css("color","#555");
alert("Reservation Successful!!! \n\nPlease wait for your reservation code to be send to your e-mail account or contact number.\n\nThank you!");
return false;
}
else{
alert("Sorry for the inconvenience but the connection to our database failed.\nPlease check you internet connection or refresh you page.\n\nIf one of the above failed please report to our admin.\nThank You.");
return false;
}
}//end success function
}); //end ajax call
return false; // IMPORTANT
}
submitreserve_eventpc.php:
if($test){
mysql_query("INSERT INTO tblevent(eventName,engager,contactNumber,emailAdd,venue,checkinDate,message) VALUES('$event2','$engager2','$contact2','$eadd2','$venue2','$datein2','$message2')");
$ok = 1;
}
else{
$ok = 0;
}
echo json_encode($ok);
If there's any improvement that you see please edit. For now this met my needs :)
You should do something like this.
Your php.file
<?php
$con=mysql_connect('localhost','root','root');
if($con){
// do insertion data here into the database
$sql = "Insert into table query";
if($sql){
echo "Data inserted successfully";
}else{
echo "Sorry! some error occured ".mysql_error();
}
}else{
echo "Unable to connect to the server";
}
?>
You could try something like this.
function sendreserve_event2(){ // send informations to database
var data_string = $("form#eform2").serialize(); // IMPORTANT
$.ajax({
type: "POST",
url: "submitreserve_eventpc.php",
data: data_string
}).done(function(data) {
data = $.parseJSON(data);
message = data.message;
if (message == "success")
{
$("#eevent2").val("");
$("#eengager2").val("");
$("#econtact2").val("");
$("#eeadd2").val("");
$("#evenue2").val("Venue:");
$("#edatein2").val("");
$("#emessage2").text("");
$("#eeadd2").css("backgroundColor","#FFFFFF");
$("#eeadd2").css("color","#555");
$("#esubmit2").blur();
alert("Reservation Successful!!! \n\nPlease wait for your reservation code to be send to your e-mail account or contact number.\n\nThank you!");
} else {
console.log(message);
}
});
return false; // IMPORTANT
}
In your PHP file could be changed to what is below.
$myDatabase = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$myDatabase)
{
$message = 'Could not connect: ' . mysql_error();
} else {
$event2 = $_POST['eevent2'];
$engager2 = $_POST['eengager2'];
$contact2 = $_POST['econtact2'];
$eadd2 = $_POST['eeadd2'];
$venue2 = $_POST['evenue2'];
$datein2 = $_POST['edatein2'];
$message2 = $_POST['emessage2'];
mysql_query("INSERT INTO tblevent(eventName,engager,contactNumber,emailAdd,venue,checkinDate,message) VALUES('$event2','$engager2','$contact2','$eadd2','$venue2','$datein2','$message‌​2')");
$message = 'success';
}
$response = array('message' => $message);
echo json_encode($response); // This is the data that your AJAX function gets in .done

Categories