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');} });
Related
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.
I am working on login form in Angular Js.The HTML and validation part is working fine.
The problem is when i send data using HTTP POST method to my servicecall PHP page and want to save it to DB.
I have tried all the way by setting this in JS
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
I have tried by setting enctype of form to
enctype="application/x-www-form-urlencoded"
as well.But none of them is working i am not able to get data via $_REQUEST, $_POST, $_GET any of these method.
I have also tried using PHP library function.
$postdata = file_get_contents("php://input");
But it gives some weird string which i can't handle because number of POST data could be hundreds.
So this there any other way to solve the problem.
Code for http request is
var req = {
method: 'POST',
url: 'servicecall.php',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: {
username: $scope.loginData.username,
password: $scope.loginData.password,
action : 'checkLogin'
} //First way of sending data
//Second way of sending data which is also not working
//data: "{username:"+$scope.loginData.username+",password:"+$scope.loginData.password+",action:checkLogin}"
}
$http(req).then(function(response){
console.log(response);
}, function(response){
alert("Error "+response);
});
At PHP page i do
print_r($_REQUEST);
print_r($_POST);
But it prints just blank array like array{}
Following the code that I am using for same purpose. Hope that may help you.
var app = angular.module('angularApp', []);
app.controller('loginCtrl', function ($scope, $http) {
$scope.login = function () {
var request = $http({
method: "post",
url: "login.php",
data: {
email: $scope.email,
password: $scope.password
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
/* Successful HTTP post request or not */
request.success(function (data) {
if(data == "1"){
$scope.responseMessage = "Successfully Logged In";
}
else {
$scope.responseMessage = "Username or Password is incorrect";
}
});
}
});
I am trying make an ajax request to php from angular js. But I am not getting the data I have sent. Please let me know where I am going wrong.
The following is the ajax call.
<script type="text/javascript">
angular.module('app', []).controller("MyController", function($scope, $http) {
var req = {
method: 'POST',
url: 'pujastrail/www/rest/get.php',
headers: {
'Content-Type': "application/x-www-form-urlencoded; charset=utf-8"
},
data: { lang: "fr" }
}
$http(req).success(function(data, status, headers, config){alert("done"+data);}).error(function(data, status, headers, config){alert("error"+res);});
});
</script>
The following is the php code.
<?php
if (isset($_POST['lang']) && !empty($_POST['lang'])) {
$lang = $_POST['lang'];//this needs to be sent back to js file
} else {
$lang = "eRROR";// but this is being sent back to the js file
}
echo (json_encode($lang));
?>
I have tried this using $_REQUEST also but it didnot work.
In your angular code, you need to encode the parameter data as a string like lang=fr instead of {lang: 'fr'}.
Try using $.param(obj) or $.param({lang: "fr"}) to convert it like this:
var req = {
method: 'POST',
url: 'pujastrail/www/rest/get.php',
headers: {
'Content-Type': "application/x-www-form-urlencoded; charset=utf-8"
},
data: $.param({ lang: "fr" })
}
source source
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