I'm using AngularJS $http.post to call PHP in my login-function. The PHP gives back a token and if not exists the word "ERROR".
PHP-Code:
....
echo json_encode($token);
} else {
echo "ERROR";
}
Controller.js:
var request = $http({
method: "post",
url: constantService.url + 'login.php',
data,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
request.success(function(response) {
$localstorage.set("token", JSON.stringify(response));
var showAlert = function() {
var alertPopup = $ionicPopup.alert({
title: ' successful token-based login',
template: response
});
alertPopup.then(function(res) {
console.log(res);
$state.go('home');
});
};
showAlert();
});
request.error(function(data, status, headers, config) {
console.log('An error occurred ');
var showAlert = function() {
var alertPopup = $ionicPopup.alert({
title: 'Error',
template: 'check your login credentials'
});
alertPopup.then(function(res) {
});
};
showAlert();
});
When i get back a correct token it's working without problems. When i get back the word "ERROR" ( no token exists ) i get the following error in chrome inspector:
**SyntaxError: Unexpected token E**
at Object.parse (native)
at fromJson (http://localhost:8100/lib/ionic/js/ionic.bundle.js:9764:14)
at defaultHttpResponseTransform (http://localhost:8100/lib/ionic/js/ionic.bundle.js:17278:16)
at http://localhost:8100/lib/ionic/js/ionic.bundle.js:17363:12
at forEach (http://localhost:8100/lib/ionic/js/ionic.bundle.js:9022:20)
at transformData (http://localhost:8100/lib/ionic/js/ionic.bundle.js:17362:3)
at transformResponse (http://localhost:8100/lib/ionic/js/ionic.bundle.js:18088:23)
at processQueue (http://localhost:8100/lib/ionic/js/ionic.bundle.js:21888:27)
at http://localhost:8100/lib/ionic/js/ionic.bundle.js:21904:27
at Scope.$eval (http://localhost:8100/lib/ionic/js/ionic.bundle.js:23100:28)
Whats the correct way to give back the word "ERROR" an handle it in my
response.error-function ? Is this a JSON-encoding/decoding problem ?
Tried all to solve this issue but without success.
THX.
By default angular content-type is application/json.
i think your overriding of header is not working, may be because of data before headers you sent.
var request = $http({
method: "post",
url: constantService.url + 'login.php',
data : data, // here key : value pair is missing
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
so angular thinks you providing a json response and parsing it as json. so when your response is ERROR is just trying to parse as json and throwing parse error.
and about callbacks. the error function will not fired until you sent error code or browser ditect a error. here is the error codes link
in your case both ERROR and json_encode(token) will fire the success function. so you should process in success function also as error function.
you might do in your php file
if(/*success condition */){
$json = array('status'=>'success','token'=>$token);
}else{
$json = array('status'=>'error','reason'=>'failed to generate token or somthing');
}
echo json_encode($json);
and in your success function
request.success(function(response) {
if(response.status === 'success' ){
$localstorage.set("token", JSON.stringify(response));
var showAlert = function() {
var alertPopup = $ionicPopup.alert({
title: ' successful token-based login',
template: response
});
alertPopup.then(function(res) {
console.log(res);
$state.go('home');
});
};
showAlert();
}else{
console.log(response.message);//you can do as you error function
}
});
and don't forget to remove the headers setting if you don't need it.
or if you need it do a JSON.parse(response) in top of success function.
Related
hello everyone i have some issue
in my controller i do http post to server and run of the server some file with php server side language and check if i the user is register in mydb
this is my code:
$scope.sendPost = function()
{
var login =
'mylogin='+ JSON.stringify({
email: $scope.email,
pass: $scope.pass
})
$http({
method : 'POST',
url : 'http://igortestk.netai.net/login.php',
data: login,
Content-Type:'text/plain',
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(data){
console.log(data);
console.log(resultlogin);
console.log(json);
}).error(function(error){
console.log(error);
})
from the sever side i back json_encode in php of some status of login
so my question is how i take the json value from the server response
this is my server response :
{"statuslogin":1}]
edit: this is my server side code in php;
$query="select * from `User` where Email='$email' and Pass='$pass'";
$result=mysql_query($query ,$con);
if(mysql_num_rows($result)==1){
$reponse['statuslogin']=1;
}
else{
$reponse['statuslogin']=0;
}
$output=json_encode($reponse);
print $output;
edit2:
ok it's doesnt work beacuse the data of the response is a string and data[0] i get "[" this bracket : data: "[{"statuslogin":1}]" so maybe some other solution ?
You can get the value with:
console.log(data.statuslogin);
In case of one array:
console.log(data[0].statuslogin);
$http({
method: "POST",
url: "http://igortestk.netai.net/login.php",
data: login,
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
}).success(function (data) {
console.log(data[0].statuslogin); // In the console will print: 1
// If you need to show a message according the result, you can do this:
$scope.message = (data[0].statuslogin === 1) ? "Login success" : "Login error, please check";
}).error(function (error) {
console.log(error);
});
However, according the AngularJS Documentation, the success method is deprecated:
The $http legacy promise methods success and error have been
deprecated. Use the standard then method instead.
https://docs.angularjs.org/api/ng/service/$http
Then, you might use the standard form with the shortcut form, by using then(). Something like this:
$http.post("http://igortestk.netai.net/login.php", data, { headers: { "Content-Type": "application/x-www-form-urlencoded" }}).then(function(response)
{
console.log(response.data[0].statuslogin); // In the console will print: 1
}, function(response)
{
console.log(response);
});
Demo
PHP File: loginajax.php
<?php
header("Access-Control-Allow-origin: *");
header("Content-Type: application/json");
header("Cache-Control: no-cache");
$reponse['statuslogin']=1;
$output=json_encode($reponse);
echo $output;
flush();
?>
(function() {
var app = angular.module("myApp", []);
app.controller("Controller", ["$scope", "$http",
function($scope, $http) {
$scope.email = "email#server.com";
$scope.pass = "123456";
var login =
'mylogin=' + JSON.stringify({
email: $scope.email,
pass: $scope.pass
});
$http({
method: "POST",
url: "http://dfjb.webcindario.com/loginajax.php",
data: login,
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
}).success(function(data) {
console.log(data.statuslogin); // In the console will print: 1
// If you need to show a message according the result, you can do this:
//$scope.message = (data[0].statuslogin === 1) ? "Login success" : "Login error, please check";
}).error(function(error) {
console.log(error);
});
}
]);
})();
<html data-ng-app="myApp">
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body data-ng-controller="Controller">
</body>
</html>
In the network tab of Google Chrome console, i have this json response:
The better way to access JSON data service is with ngResource which can be used to consume Restful API in AngularJs.
.factory('UserService', function ($resource) {
return $resource('http://jsonplaceholder.typicode.com/users/:user',{user: "#user"});
});
To perform Resource get just do:
$scope.users = UserService.query();
resource object has the following methods:
{ 'get': {method:'GET'},
'save': {method:'POST'},
'query': {method:'GET', isArray:true},
'remove': {method:'DELETE'},
'delete': {method:'DELETE'} };
To get a specific user:
$scope.oneUser = UserService.get({user: 1});
More info can be found here: https://docs.angularjs.org/api/ngResource/service/$resource
Maybe this will help you
$http('http://igortestk.netai.net/login.php').post(data).then(function(data){ if(data.statuslogin === 1){alert('welcome');} });
I am using the Human API found here: https://docs.humanapi.co/docs/connect-backend
At one point in connecting to the API, I need to send data back to them as JSON. I get a JSON object called sessionTokenObject which contains this:
{
humanId: "1234567890",
clientId: "abcdefg",
sessionToken: "9876zyx",
}
To which I'm supposed to add a clientSecret. Essentially, I'm taking what's in the JSON object, converting it individual variables, passing them through to another page via URL parameters and then reconstructing everything so that I can add the clientSecret like so:
$pop_clientid = $_GET['clientid'];
$pop_humanid = $_GET['humanid'];
$pop_userid = $_GET['userid'];
$pop_sessiontoken = $_GET['clientid'];
$my_sessiontokenobject = '{
humanId: "'.$pop_humanid.'",
clientId: "'.$pop_clientid.'",
sessionToken: "'.$pop_sessiontoken.'",
clientSecret: "thesecretgoeshere"
}'; ?>
<script type="text/javascript">
jQuery(document).ready(function($) {
$.ajax({
type: "POST",
url: 'https://user.humanapi.co/v1/connect/tokens',
data: '<?php echo $my_sessiontokenobject; ?>',
success: null,
dataType: 'application/json'
});
});
</script>
If I don't wrap the data value in the .ajax() call in apostrophes, I get a 422 error back from https://user.humanapi.com/v1/connect/tokens
If I do, I get an "Uncaught SyntaxError: Unexpected token ILLEGAL" error.
Can anyone see what's wrong with my code, or perhaps even tell me if trying to recreate a JSON object and then pass it back via .ajax() in the manner I am is just completely incorrect?
Try with this: (Returns a 404 Not found error, but it seems that it is in their side)
connectBtn.addEventListener('click', function(e) {
var opts = {
// grab this from the app settings page
clientId: clientId,
// can be email or any other internal id of the user in your system
clientUserId: clientUserId,
clientSecret: clientSecret,
finish: function(err, sessionTokenObject) {
console.log(sessionTokenObject);
// When user finishes health data connection to your app
// `finish` function will be called.
// `sessionTokenObject` object will have several fields in it.
// You need to pass this `sessionTokenObject` object to your server
// add `CLIENT_SECRET` to it and send `POST` request to the `https://user.humanapi.co/v1/connect/tokens` endpoint.
// In return you will get `accessToken` for that user that can be used to query Human API.
sessionTokenObject.clientSecret = clientSecret;
jQuery(document).ready(function($) {
$.ajax({
type: "GET",
url: url,
dataType: 'jsonp',
contentType: "application/json",
data: sessionTokenObject,
});
});
// clientId=ceb8b5d029de3977e85faf264156a4e1aacb5377&humanId=f54fa4c56ca2538b480f90ed7b2c6d22
// $.post(url, sessionTokenObject, function(res){
// console.log(res);
// });
},
close: function() {
// do something here when user just closed popup
// `close` callback function is optional
}
}
HumanConnect.open(opts);
});
Human API Code for Testing, this code generates accessToken from Human API Developer Side but its not coming as in response while i execute this code
<script src='https://connect.humanapi.co/connect.js'></script>
<script>
var options = {
clientUserId: encodeURIComponent('email'), //Unique ID of user on your system (we send this back at the end)
clientId: '',
publicToken: '',
finish: function (err, sessionTokenObject) {
/* Called after user finishes connecting their health data */
//POST sessionTokenObject as-is to your server for step 2.
console.log(sessionTokenObject);
sessionTokenObject.clientSecret = 'Client Secret Key';
$.ajax({
type: 'POST',
url: 'https://user.humanapi.co/v1/connect/tokens',
method: 'POST',
data: sessionTokenObject
})
.done(function (data) {
console.log(data);
// show the response
if (data.success) {
alert(data.success);
} else {
alert(data.error);
}
})
.fail(function (data) {
console.log(data);
// just in case posting your form failed
alert("Posting failed.");
});
// Include code here to refresh the page.
},
close: function () {
/* (optional) Called when a user closes the popup
without connecting any data sources */
alert('user clicked on close Button');
},
error: function (err) {
/* (optional) Called if an error occurs when loading
the popup. */
}
}
function openHumanApiModel() {
HumanConnect.open(options);
}
</script>
I am trying to create a simple AJAX call using JSON, but I keep getting a parse error on the result and when I check the resultText it shows the source code of the entire page, with the JSON response showing a success above the page headers.
Here is my AJAX call, where #class is a select box with values.
$("#class").change( function () {
if($('#class').val().length > 0){
$.ajax({
type: "GET",
url: "http://192.168.0.9/ajax",
data: 'class_id=' + $("#class").val(),
datatype: 'json',
async: 'true',
beforeSend: function() {
alert("Before send!");
},
success: function(result){
if (result.status){
$('#result').html(result);
} else {
alert('request unsuccessful!');
}
},
complete: function() {
alert("Complete!");
},
error: function (request,error) {
alert('A jQuery error has occurred. Status: ' + error +':'+ request.responseText);
$("#result").html(request.responseText);
}
});
} else {
alert('Please make a selection');
}
return false;
});
This is my PHP function that returns the result
$result = array();
$result['status'] = "success";
$result['message'] = "Types";
header("Content-Type: application/json; charset=utf-8", true);
echo json_encode($result);
Finally, this is the response I am getting in my error alert:
A jQuery error has occurred status:parseerror
{"status":"success", "message":"Types"}<!DOCTYPE html>
<html>
...rest of my page from where the request was sent
I am hoping this is a simple error and someone can tell me what I am doing wrong?
Perhaps your parameter should be pass in JSON format:
data: "{'class_id':'" + $("#class").val() + "'}",
Try to remove datatype:'json' from the Javascript and header("Content-Type: application/json; charset=utf-8", true); it should be recognize itself
My success/error handling is not working as expected. In this example my php runs as intended, however, the intent of the processing failed. Let's say I was looking up a username in the database... if I found the username I would return $ajax_result['success'] = 'success';, but if I did not find the username I would return nothing. The success call works fine, but the error call is not firing.
The error in firebug I am getting is TypeError: response is null and therefore the error alert I have set does not fire.
What is the best way to solve this without actually returning $ajax_result['success'] = 'whatever';
example return from php would be something like this when processing went as expected:
$ajax_result['success'] = 'success'; // add success info
echo json_encode($ajax_result); // return result array to ajax
for 'errors' I am simply returning :
echo json_encode($ajax_result); // which is null in this case
the ajax:
var showInfo = function() {
$('#show-user').on('click', function () {
var $form = $(this).closest('form');
$.ajax({
type: 'post',
url: '/spc_admin/process/p_delete_user_show.php',
data: $form.serialize(),
dataType : 'json'
}).done(function (response) {
if (response.success == 'success') {
alert('success');
}
else
{
alert('error');
}
});
});
}
You can not json_encode a null value, easiest and cleanest way to make this work would probably be to make success a bool and set it to either true or false depending on if it succeeded or not (This is ususaly what most user expects a 'success' or 'result' parameter in response to be, not a string).
//PHP:
header('Content-Type: application/json'); // To let the client know that its json-data.
$ajax_result['success'] = $wasSuccessfull; // true or false
die(json_encode($ajax_result)); // Exit the script with the json response.
//JavaScript:
if (response.success) {
alert('success');
} else {
alert('error');
}
try this one:
if (!response.success) {
alert('error');
}
else
{
alert('success');
}
I have an AJAX call in my view to an action in my controller. However, I always get an Error 400. Below is the code for my AJAX call:
$.ajax({
cache: false,
url: '/dummy/index.php/module/controller/checkCross',
dataType: 'json',
type: 'POST',
data : {"male":parents[0],"female":parents[1]},
success: function(result){
alert(result);
}
});
Below is the code in the controller:
public function actionCheckCross(){
if(Yii::app()->request->isPostRequest) { // check if POST
$flag = CrossingMatrix::model()->checkParentsIfCrossed($_POST['male'],$_POST['female']);
if($flag){
return true;
}
else{
return false;
}
} else { // direct URL request will be GET, so show error
throw new CHttpException(400, Yii::t('app', 'Direct access is not allowed.'));
}
}
Any ideas?
You are expecting json data, but you send empty page to browser. You should encode result like that:
echo CJavascript::jsonEncode((bool)$flag);
Yii::app()->end();
In your code you returned value. Notice that your yii exception message is Direct access is not allowed but your error is Your request is invalid.