We're using php-framework "slim" to build an e-shop. Now we are meeting a problem that we can send a request to server and modify the database(we checked table and it is changed indeed), whereas web end can't get the response from the database(iOS and android end can both get it). Here is the part of the code which sends the request, updates database and gets the response:
$app->post('/tblUser', function($request, $response, $args) {
get_tblUser_id($request->getParsedBody());
});
function get_tblUser_id($data)
{
$db = connect_db();
$sql = "update tblphoneverify set dtCreate = NOW() where strPhone = $data[phone]";
$db->query($sql);
$updateId = $db->affected_rows;
$db = null;
$msg = array(
'stat' => '',
'msg' => ''
);
$msg['stat'] = '1';
$msg['msg'] = 'registration success';
return json_encode($msg);
}
then this ajax segment triggers the click event to execute post and receives the state of the result:
$(function(){
$("#getcheck").click(function(){
$.ajax({
type:"post",
url:"http://192.168.1.108/blue/public/tblUser",
data: {"phone":"13331111111"},
dataType:"json",
//async:false,
contentType: "application/x-www-form-urlencoded",
success:function(data){
alert(1);
},
error:function(XMLHttpRequest, textStatus, errorThrown){
alert(XMLHttpRequest.readyState);
alert(XMLHttpRequest.status);
alert(XMLHttpRequest.statusText);
alert(XMLHttpRequest.responseText);
alert(textStatus);
alert(errorThrown);
}
})
})
})
the code always skips the "success" part and jumps to "error" directly.
So what is wrong with our code? Thanks in advance.
You should send a response from a route callable. Don't json_encode yourself, instead let Slim do it.
Firstly, return an array from get_tblUser_id:
function get_tblUser_id($data)
{
$db = connect_db();
$sql = "update tblphoneverify set dtCreate = NOW() where strPhone = $data[phone]";
$db->query($sql);
$updateId = $db->affected_rows;
$db = null;
$msg = array(
'stat' => '',
'msg' => ''
);
$msg['stat'] = '1';
$msg['msg'] = 'registration success';
return $msg;
}
Note that you have a SQL injection vulnerability here. Change the SQL to something like this:
$sql = "update tblphoneverify set dtCreate = NOW() where strPhone = ?";
$db->query($sql, [$data[phone]]);
Next, you need to send a response as JSON from the route callable. Slim has a method to do this:
$app->post('/tblUser', function($request, $response, $args) {
$msg = get_tblUser_id($request->getParsedBody());
return $response->withJson($msg);
});
Slim will now send back your the msg array with the correct content-type header set, which should help your JavaScript to decode it.
Related
I'm doing login from an app using php and mysql. When I put the URL on the browser with credentials appended with it, if the credentials are valid, it prints correct response like success:true. If credentials are not valid, it prints success:false. But when I put do ionic serve and do a login from the app, it prints success:true on console all the time, even if the credentials are not valid.
This is my IONIC-2 code:
var headers = new Headers();
headers.append("Accept",'application/json');
headers.append('Content-Type','application/json');
let options = new RequestOptions({headers:headers});
let postParams={
username: logincreds.username,
password: logincreds.password,
}
this.http.post("http://vaishalishaadi.com/AppLogin.php", postParams, options)
.subscribe(data=>{
console.log(postParams);
console.log(data);
/*if(data.json().success=="success"){
}
else{
} */
}, error => {
console.log(error);
});
Following code is of PHP:
header('Content-type: application/json');
if($check){
session_start();
$_SESSION['u_id'] = $check->u_id;
$_SESSION['u_name'] = $check->u_firstname;
$login_response=["success"=>"true"];
//print(json_encode($login_response));
//echo $check->u_id;
$data[] = array(
'pram'=$username
'id' => $check->u_id,
'fname' => $check->u_firstname,
'lname' => $check->u_lastname,
);
$result = "{'success':true, 'data':" . json_encode($data) . "}";
}
else{
$result = "{'success':false}";
}
echo($result);
Found Solution Over It
Just changed the way I was passing parameters and also removed 'options' argument from post request.
let params = new URLSearchParams();
params.append('username',logincreds.username);
params.append('password',logincreds.password);
this.http.post(url, params)
.subscribe(data=>{
console.log(postParams);
console.log(data);
/*if(data.json().success=="success"){
}
else{
} */
}, error => {
console.log(error);
})
Use URLSearchParams instead of using array to collect parameters being passed to server
Alright, this is probably super simple but I've been breaking my head over this all day and I cannot get it to work.
I have a page that displays a list of users from a mysql query. On this page it should also be possible to add users. To do this, I'm sending an AJAX call to process.php which does some validation and sends an error if there is one. If there is no error, I want AJAX to update the page.
The problem is, that if there are no errors (a user has been added), I want to return the updated userlist. This means storing the output of my getUsers(); function in an array, which isn't possible.
How can I achieve this?
p.s. I realise this is crappy code and I should be using OOP/PDO, but this isn't for a production environment and it works. So I'll leave it like this for the time being.
users.php
<article>
<ul>
<?php getUsers(); ?>
</ul>
</article>
<form id="addUserForm">
...
<input type="hidden" name="addUser">
</form>
$("#addUserForm").on("submit",function() {
event.preventDefault();
var data = $("#addUserForm").serialize();
$.ajax({
type: "POST",
url: "process.php",
data: data,
dataType: "json",
success: function(response) {
if (response.success) {
$("article ul).html(response.data);
} else {
$(".errorMessage).html("<p>" + response.error + </p>");
}
}
});
});
functions.php
function getUsers()
{
global $db;
$query = mysqli_query($db, "SELECT * FROM users");
while($row = mysqli_fetch_assoc($query))
{
echo "<li>" . $row["user_firstname"] . "</li>";
}
}
function addUser($email, $password)
{
global $db;
$result = mysqli_query($db, "INSERT INTO users ... ");
return $result
}
process.php
if (isset($_POST["addUser"]))
{
... // Serialize data
if (empty ...)
{
$responseArray = ["success" => false, "error" => "Fields cannot be empty"];
echo json_encode($responseArray);
}
// If user is successfully added to database, send updated userlist to AJAX
if (addUser($email, $password))
{
$responseArray = ["success" => true, "data" => getUsers();];
echo json_encode($responseArray)
}
}
Your getUsers() function is printing and not returning the data to json connstructor
function getUsers()
{
global $db;
$query = mysqli_query($db, "SELECT * FROM users");
while($row = mysqli_fetch_assoc($query))
{
echo "<li>" . $row["user_firstname"] . "</li>";
}
}
it has to be something like this
function getUsers()
{
global $db;
$query = mysqli_query($db, "SELECT * FROM users");
$list = "";
while($row = mysqli_fetch_assoc($query))
{
$list. = "<li>" . $row["user_firstname"] . "</li>";
}
return $list;
}
And there is a syntax error in the following line
if (addUser($email, $password)
close it with ")"
You can capture the output of the getUsers function without changing the current behavior if that's what you're after. In the success output change
$responseArray = ["success" => true, "data" => getUsers();];
echo json_encode($responseArray)
to
ob_start();
getUsers();
$usersList = ob_get_clean();
$responseArray = ["success" => true, "data" => $usersList];
echo json_encode($responseArray)
What this does is captures the output and stores it into a varable $usersList which you can then return as a string.
You'd be better off returning the users as an array and dealing with generating the markup on the client side IMO, but that's up to you. This is just another way to get what you have working.
More information about php's output buffer here
Are you trying to get the error returned by ajax or you want to have custom error? (e.g. string returned by your php script). If you're referring to ajax error you should have this:
EDIT: Since you mentioned you want a custom error returned by process.php
Process.php
if (isset($_POST["addUser"]))
{
... // Serialize data
if (empty ...)
{
$responseArray = ["success" => false, "error" => "Fields cannot be empty"];
echo json_encode($responseArray);
}
// If user is successfully added to database, send updated userlist to AJAX
if (addUser($email, $password))
{
$responseArray = ["success" => true, "data" => getUsers();];
echo json_encode($responseArray)
}else{
echo 1;
}
//I added else echo 1;
}
Your ajax will be:
$("#addUserForm").on("submit",function() {
event.preventDefault();
var data = $("#addUserForm").serialize();
$.ajax({
type: "POST",
url: "process.php",
data: data,
dataType: "json",
success: function(response) {
if(response != 1){
$("article ul").html(response.data);
}else{
alert('Custom error!');
}
},
error: function(jqXhr, textStatus, errorThrown){
console.log(errorThrown);
}
});
});
BTW you're missing ) in your posted code if (addUser($email, $password))
This is how I do:
try{dataObj = eval("("+response+")");}
catch(e){return;}
alert(dataObj->example_key);
I have being battling almost for day now about something that sound quite simple. I'm trying to pass an object using angular post ajax. I'm using PHP with codeigniter framework and I'm not getting any values pass. there have to be something wrong with the way I'm sending the object in angular because php is not getting anything. It's going to the right place because I'm getting a respond error saying "Trying to get property of non-object, line 173" line 173 is $AccessKey = $data->AccessKey;
this is my angular code
app.controller('loginController', function($scope, $http){
//$scope.formData = {};
$scope.processForm = function(){
$http({
method : 'POST',
url : 'http://localhost:8888/employees/login',
data : '{"AccessKey":"candoa01#gmail.com","Password":"candoa21"}'
})
.success(function(data){
console.log(data);
})
};
});
this is my php. i think here maybe I'm not using the right object name to retrieve the values.
public function login()
{
$data = $this->input->post('data');
//$data = '{"AccessKey":"candoa01#gmail.com","Password":"candoa21"}';
$data = json_decode($data);
$AccessKey = $data->AccessKey;
$Password = $data->Password;
$sql = "SELECT *
FROM Employees
WHERE Employees.AccessKey = ?
AND Employees.Password = ?";
$query = $this->db->query($sql, array($AccessKey, $Password));
if($query->num_rows() > 0)
{
$query = json_encode($query->result());
return $this->output
->set_content_type('application/json')
->set_output($query);
}
else
{
return 'Invalid AccessKey Or Password';
}
}
}
Try this, use params instead of data & remove ' in params
$http({
url: 'http://localhost:8888/employees/login',
method: "POST",
params: {"AccessKey":"candoa01#gmail.com","Password":"candoa21"}
})
As per your sever side code you have to pass the data as show below.
$scope.processForm = function(){
$http({
method : 'POST',
url : 'http://localhost:8888/employees/login',
data : {
data: JSON.stringify({
AccessKey: "candoa01#gmail.com",
Password:"candoa21"
})
}
})
.success(function(data){
console.log(data);
})
};
You receiving data wrong way because you are not posting data json format.This should be
$AccessKey = $this->input->post('AccessKey');
$Password = $this->input->post('Password ');
Or you can use this way
$data = $this->input->post();
$AccessKey = $data['AccessKey'];
$Password = $data['Password'];
I'm new to AngularJS but I've already done a lot of things.
I did a $http.post, that worked like a charm.
Heres the Angular code
$scope.login = function(user, pass) {
$scope.bIsVisible = false;
var dados = {"user": user, "pass": pass};
console.log(dados);
$http.post('http://base.corretoconcursos.com.br/cadernos/index.php/manageUsers/login', dados)
.success(function(data, status, headers, config) {
if (data == false)
{
$scope.isLogged = false;
$scope.bIsVisible = true;
} else {
$scope.isLogged = true;
$scope.userData = data;
console.log(data);
}
})
.error(function(data, status, headers, config) {
alert('failed');
$scope.bIsVisible = true;
});
And the manageUsers/login function
function login()
{
$postdata = file_get_contents("php://input");
$data = json_decode($postdata);
$username = $data->user;
$password = md5($data->pass);
$datafrombase = $this->UsersModel->getUser(array(
'user' => $username,
'pass' => $password
));
if ($datafrombase != null) {
$user = array(
'user' => $datafrombase['user'],
'type' => $datafrombase['type'],
'logged_in' => true
);
$this->session->set_userdata($user);
}
if ($datafrombase != null)
print_r(json_encode($datafrombase));
else
return false;
}
Alright. It's working. I retrieve some data from database and OK. The real problem is when I do a $http.get and simply by doing a request on database or not, it doesn't send back the data that I want, when I do the console.log(data), it shows me an entirely HTML page, in fact, the one that is displaying. I'm getting a 200 status OK, but, a HTML page is coming. Don't know why.
Heres the Angular code
$scope.setLoggedOn = function(on) {
if (on) {
$http.get('http://base.corretoconcursos.com.br/cadernos/index.php/manageUsers/retrieveLogin')
.success(function(data, status) {
console.log(data);
})
.error(function(data, status, headers, config) {
alert('failed');
});
}
else
$scope.isLogged = false;
};
And heres the PHP code function I'm retrieving.
function retrieveLogin()
{
$user = null;
$user = array(
'user' => $this->session->userdata('user'),
'type' => $this->session->userdata('type'),
'logged_in' => true
);
print_r(json_encode($user));
}
I'm stuck. I've even tried doing just a 'return true'; inside the php function, return 'string'; but nothing will work. What so wrong am I doing?
Figured it out. If you're using CodeIgniter along sessions; and checking in the constructor if people are logged in to let them see that page or not; when you do the $http.get it will run the constructor and run that condition, and if they cannot see that page, even if you're just doing a request from that controller via AJAX, it won't let you make the request.
I thought that the $http.get would only request the function (i-e, verifyUserInDatabase();), and give the data, but turns out, it doesn't.
Thanks for the help.
$datafrombase is never set in retrieveLogin() so angular isn't going to receive anything.
I have a poll and when user click on one of the options, it sends data through ajax:
$.ajax({
type: 'POST',
url: '/poll.php',
data: {option: option, IDpoll: IDpoll},
dataType: 'json',
async: false,
error: function(xhr, status, error) {
alert(xhr.responseText);
},
success: function(data) {
if(data.msg == "0") {
$( "#pollArea" ).load( "/pollVote.php", { allow: true }, function() {
alert( "Ďakujeme za Váš hlas!" );
});
}
else {
alert(data.msg);
alert("V tejto ankete ste už hlasovali.");}
}
});
This works fine. Now data are passed to the file poll.php:
if (isset($_POST['option']) && isset($_POST['IDpoll'])) {
require 'includes/config.inc.php';
$ip = $_SERVER['REMOTE_ADDR'];
$option = $pdo->quote($_POST['option']);
$IDpoll = $pdo->quote($_POST['IDpoll']);
$date = date("d.m.Y H:i:s");
$poll = new Poll();
$msg = $poll->votePoll($IDpoll, $ip, $option, $date);
$arr = array(
'msg' => $msg
);
echo json_encode($arr);
This also works, the problem happened in class Poll - method VotePoll:
public function votePoll($IDpoll, $ip, $option, $date)
{
try {
$query = "SELECT * FROM `votes` WHERE `IDpoll` = '$IDpoll' AND `ip` = '$ip'";
$result = $this->pdo->query($query);
if ($result->rowCount() == 0) {
/* do stuff */
}
catch (PDOException $e) {
return $e->getMessage();
}
}
And the error message from the ajax call is following: Call to a member function rowCount() on a non-object. I know what this message means, but I can't find out why the variable $result isn't considered as PDO object. Strange thing is, that when I try to call function votePoll manually, it works perfectly and when I use var_dump on result it is PDO object. So where is the mistake?
EDIT: I forgot to say I was just editing this function. Originally it worked with mysqli but I wanted to switch to pdo (so query and stuff like that are okay).
So, this problem was in these lines:
$option = $pdo->quote($_POST['option']);
$IDpoll = $pdo->quote($_POST['IDpoll']);
PDO quote function add quotes to the string so option became 'option' etc. Then it was sent to query where additional quotes were added, so the result was ''option'' and that is error.