AngularJS $http.get not working. Not retrieving data - php

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.

Related

API returning empty array instead of data in Laravel Vue

I am doing a Laravel Vue project for school and i am supposed to get a user by sending its email from the client, but when the server responds i get an empty array from the response data instead of the data i want from the database.
Login.vue
login() {
this.showMessage = true;
this.typeofmsg = "alert";
this.message = "Loggin in...";
axios.post('api/login', this.user)
.then(response => {
const token = response.data.access_token;
this.$store.commit('setAccessToken', token);
return axios.get('api/users/me', this.user.email);
})
.then(response => {
console.log(response);
})
.catch(error => {
console.log("Error = " + error.message);
});
},
routes/api.js
Route::get('users/me', 'UserControllerAPI#myProfile');
UserControllerAPI
public function myProfile(Request $request){
$email = $request->email;
$user = User::where('email', $email)->first();
return new UserResource($user);
}
If i try to get it with postman it works
And in the dev tools console i get this
Sorry if i wasn't clear enought or it is something wrongly made, i have been trying to fix this since yesterday and its driving me crazy. Any help appreciated
Edit: Had the route wrong, but i changed it and i get the same, no data. I changed the console picture too
Change this line:
return axios.get('api/users/me', this.user.email);
to
return axios.get('api/users/me', { params: { email: this.user.email } });
You have api/user/me and in route you have /userS/me
so I guess you have to either remove S or add S in one of the places.
so try to change in route
Route::get('users/me', 'UserControllerAPI#myProfile');
to
Route::get('/user/me', 'UserControllerAPI#myProfile');

Ionic 2 giving wrong response while making post request with php and mysql

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

can't receive response from server in slim

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.

Having trouble setting cookie via AJAX login with Yii2

I'm using Yii2 and I have setup a login process which works fine (cookies as well) via the standard login page which is not AJAX.
I have built a dropdown login field which works fine at logging them in, however it doesn't seem to set the cookie as the user doesn't stay logged in and there is no bookie created.
I figured that this was because of AJAX and the cookie wasn't being created on the users system, but upon further reading it seems it should work.
I have verified that the cookie value is being set correctly, the only issue is the cookie doesn't seem to being created.
My login code:
JS:
function doLogin() {
// Set file to prepare our data
var loadUrl = "../../user/login/";
// Set parameters
var dataObject = $('#login_form').serialize();
// Set status element holder
var status_el = $('#login_status');
// Make sure status element is hidden
status_el.hide();
// Run request
getAjaxData(loadUrl, dataObject, 'POST', 'json')
.done(function(response) {
if (response.result == 'success') {
//.......
} else {
//.......
}
})
.fail(function() {
//.......
});
// End
}
function getAjaxData(loadUrl, dataObject, action, type) {
if ($('meta[name="csrf-token"]').length) {
// Add our CSRF token to our data object
dataObject._csrf = $('meta[name="csrf-token"]').attr('content');
}
return jQuery.ajax({
type: action,
url: loadUrl,
data: dataObject,
dataType: type
});
}
Controller:
public function actionLogin() {
// Check if they already logged in
if (!Yii::$app->user->isGuest and !Yii::$app->request->isAjax) {
return $this->redirect('/');
}
if (Yii::$app->request->isAjax) {
// Set our data holder
$response = ['output' => '', 'result' => 'error'];
}
// Let's send the POST data to the model and see if their login was valid
if (Yii::$app->request->isAjax and $this->user->validate() and $this->user->login()) {
$response['result'] = 'success';
} elseif (!Yii::$app->request->isAjax and Yii::$app->request->isPost and $this->user->validate() and $this->user->login()) {
//.......
} else {
//.......
}
if (Yii::$app->request->isAjax) {
echo Json::encode($response);
}
}
Model:
public function login() {
// Set cookie expire time
$cookie_expire = 3600 * 24 * Yii::$app->params['settings']['cookie_expire'];
return Yii::$app->user->login($this->getUser(), ($this->remember_me ? $cookie_expire : 0));
}
As I suspected (see my earlier comment) response might not be correctly generated in case of simply echoing the data. Or maybe Content-Type header matters. If someone can confirm this it will be great.
Anyway, I'm glad it works now (data needs to be returned).
And you can use Response handy format as well.
public function actionLogin() {
// ...
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return $response;
}
}

Authentication using Cakephp and PhoneGap

I am working on an application using Cakephp on the server side and PhoneGap at the client Side, with JSON as a intermediate to access the server side.
Now, I am working specifically on a login form where the user needs to enter his/her username and password. I put in my controller the following:
public function api_login() {
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Authorization");
if ($this->request->data && isset($this->request->data['username']) && isset($this->request->data['password'])) {
$arrUser = $this->User->find('all',array(
'conditions'=>array(
'username'=> $this->request->data['username'],
'password' => $this->request->data['password']
)
));
if (count($arrUser) > 0 ) {
$this->Session->write('Auth.User',$arrUser[0]['User']);
$arrReturn['status'] = 'SUCCESS';
$arrReturn['data'] = array('loginSuccess' => 1,'user_id' => $arrUser[0]['User']['id'] );
}
else {
$arrReturn['status'] = 'NOTLOGGEDIN';
$arrReturn['data'] = array( 'loginSuccess' => 0 );
}
} else {
$arrReturn['status'] = 'NOTLOGGEDIN';
$arrReturn['data'] = array( 'loginSuccess' => 0 );
}
echo json_encode($arrReturn);
}
and in the client side, I am retrieving what JSON encoded as follows:
<script>
$(document).ready(function(){
$('form').on('submit',function(e){
e.preventDefault();
$username = $("#form-username").val();
$password = $("#form-password").val();
$.ajax({
url : "http://localhost/teslaphonegap_cakephp/" + 'login.json',
cache : false,
data : {
'username' : $username,
'password' : $password },
dataType : 'json',
type : 'POST',
success : function(result) {
if(result.status=="SUCCESS"){
alert("success");
console.log(result);
}else{
alert("username or pass are wrong");
console.log(result);
} },
error : function(xhr, status, err) {
alert("ERROR");
}
});
});
});
</script>
and in my Model I used the beforeSave() in order to hash the passwords before they get added at the very beginning in the Database:
public function beforeSave($options = array()) {
$value=$this->data['User']['password'];
$encrypted = Security::encrypt($value, Configure::read('Security.cipherCriptKey'));
$this->data['User']['password'] = $encrypted;
return true;
}
Now, when I try to login it always returns the error message because it compares a value that is unhashed with other values that are already hashed in my Database. How can I solve this issue? I used the afterFind() but it didn't work:
public function afterFind($results, $primary = false) {
foreach ($results as $key => $val) {
if(isset($val['User']['password'])){
$results['User']['password'] = Security::decrypt($val['User']['password'], Configure::read('Security.cipherCriptKey'));
}
return $results;
}
}
-- EDIT
and in my core.php I used the following:
Configure::write('Security.cipherCriptKey','su0HKssPmdbwgK6LdQLqzp0Y7zOmyaTI');
First of all, your afterFind() callback won't work as expected.
The line
$results['User']['password'] = Security::decrypt($val['User']['password'], Configure::read('Security.cipherCriptKey'));
should be written as
$results[$key]['User']['password'] = Security::decrypt($val['User']['password'], Configure::read('Security.cipherCriptKey'));
However, changing this won't fix your problem. If you search the database for a record with a password matching $this->request->data['password'], it will return no results. Note that the password in the database is hashed.
You have to fetch the record from table users that matches $this->request->data['username'], decrypt the value of field password and compare it against $this->request->data['password'].
Decryption is already taken care by afterFind(), so your code could be written as follows:
if ($this->request->data && isset($this->request->data['username']) && isset($this->request->data['password'])) {
$arrUser = $this->User->find('first',array(
'conditions'=>array(
'username'=> $this->request->data['username'],
)
));
if ($this->request->data['password'] == $arrUser['User']['password']) {
$this->Session->write('Auth.User',$arrUser['User']);
$arrReturn['status'] = 'SUCCESS';
$arrReturn['data'] = array('loginSuccess' => 1,'user_id' => $arrUser['User']['id'] );
//rest of your code

Categories