Angularjs - Cannot pass parameter - php

I'm using Angularjs for my mobile app project. My problem is I can't pass my all my parameters to my own API. My API can't detect any post parameters that my app send to it.
$http.post("http://xxxxxxxx/api/verify_login.php", {
"username": "admin",
"password": "12345678",
"secret_key": "123456789"
}).success(function(data, status, headers, config) {
alert(JSON.stringify(data));
}).error(function(data, status, headers, config) {
alert(JSON.stringify(status));
});
If using Postman it works.

how about this :
var postData = '{"username":"'+varUsername+'", "password" : "'+varPassword+'", "secret_key" : "'+varSecretyKey+'"}';
$http({
method: 'POST',
url: 'http://xxxxxxxx/api/verify_login.php',
data: postData,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(response) {
$scope.result = response;
alert(JSON.stringify(data));
});
This will post data as :
username=hisname&password=hispassword&secret_key=hiskey
keep in mind that, angularjs will automatically convert your postdata as JSON.

Looks like this StackOverflow answer helps solve half the problem. Look at the accepted answer. To paraphase the quote on this post:
By default, jQuery transmits data using Content-Type: x-www-form-urlencoded and the familiar foo=bar&baz=moe serialization. AngularJS, however, transmits data using Content-Type: application/json and { "foo": "bar", "baz": "moe" } JSON serialization, which unfortunately some Web server languages—notably PHP—do not unserialize natively.
There is a nice way to get it do this - override the default transformRequest - this is show in a nice post by Ben Nadel here - Here's a snippet:
var request = $http({
method: "post",
url: "process.cfm",
transformRequest: transformRequestAsFormPost,
data: {
id: 4,
name: "Kim",
status: "Best Friend"
}
});
He has a fairly simple implementation - if you find that this doesn't work for you, you can use the a detailed version here - you can inject this factory in your controller.
.factory("transformRequestAsFormPost", function() {
function transformRequest(data, getHeaders) {
var headers = getHeaders();
headers["Content-type"] =
"application/x-www-form-urlencoded; charset=utf-8";
return (serializeData(data));
}
return (transformRequest);
function serializeData(data) {
if (!angular.isObject(data)) {
return ((data === null) ? "" : data.toString());
}
var buffer = [];
for (var name in data) {
if (!data.hasOwnProperty(name)) {
continue;
}
var value = data[name];
buffer.push(encodeURIComponent(name) + "=" + encodeURIComponent((value ===
null) ? "" : value));
}
var source = buffer.join("&").replace(/%20/g, "+");
return (source);
}
});

Related

Passing an array trought $_POST to my php then trying to recover and use it in a foreach [duplicate]

In the code below, the AngularJS $http method calls the URL, and submits the xsrf object as a "Request Payload" (as described in the Chrome debugger network tab). The jQuery $.ajax method does the same call, but submits xsrf as "Form Data".
How can I make AngularJS submit xsrf as form data instead of a request payload?
var url = 'http://somewhere.com/';
var xsrf = {fkey: 'xsrf key'};
$http({
method: 'POST',
url: url,
data: xsrf
}).success(function () {});
$.ajax({
type: 'POST',
url: url,
data: xsrf,
dataType: 'json',
success: function() {}
});
The following line needs to be added to the $http object that is passed:
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
And the data passed should be converted to a URL-encoded string:
> $.param({fkey: "key"})
'fkey=key'
So you have something like:
$http({
method: 'POST',
url: url,
data: $.param({fkey: "key"}),
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
})
From: https://groups.google.com/forum/#!msg/angular/5nAedJ1LyO0/4Vj_72EZcDsJ
UPDATE
To use new services added with AngularJS V1.4, see
URL-encoding variables using only AngularJS services
If you do not want to use jQuery in the solution you could try this. Solution nabbed from here https://stackoverflow.com/a/1714899/1784301
$http({
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: xsrf
}).success(function () {});
I took a few of the other answers and made something a bit cleaner, put this .config() call on the end of your angular.module in your app.js:
.config(['$httpProvider', function ($httpProvider) {
// Intercept POST requests, convert to standard form encoding
$httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
$httpProvider.defaults.transformRequest.unshift(function (data, headersGetter) {
var key, result = [];
if (typeof data === "string")
return data;
for (key in data) {
if (data.hasOwnProperty(key))
result.push(encodeURIComponent(key) + "=" + encodeURIComponent(data[key]));
}
return result.join("&");
});
}]);
As of AngularJS v1.4.0, there is a built-in $httpParamSerializer service that converts any object to a part of a HTTP request according to the rules that are listed on the docs page.
It can be used like this:
$http.post('http://example.com', $httpParamSerializer(formDataObj)).
success(function(data){/* response status 200-299 */}).
error(function(data){/* response status 400-999 */});
Remember that for a correct form post, the Content-Type header must be changed. To do this globally for all POST requests, this code (taken from Albireo's half-answer) can be used:
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
To do this only for the current post, the headers property of the request-object needs to be modified:
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: $httpParamSerializer(formDataObj)
};
$http(req);
You can define the behavior globally:
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
So you don't have to redefine it every time:
$http.post("/handle/post", {
foo: "FOO",
bar: "BAR"
}).success(function (data, status, headers, config) {
// TODO
}).error(function (data, status, headers, config) {
// TODO
});
As a workaround you can simply make the code receiving the POST respond to application/json data. For PHP I added the code below, allowing me to POST to it in either form-encoded or JSON.
//handles JSON posted arguments and stuffs them into $_POST
//angular's $http makes JSON posts (not normal "form encoded")
$content_type_args = explode(';', $_SERVER['CONTENT_TYPE']); //parse content_type string
if ($content_type_args[0] == 'application/json')
$_POST = json_decode(file_get_contents('php://input'),true);
//now continue to reference $_POST vars as usual
These answers look like insane overkill, sometimes, simple is just better:
$http.post(loginUrl, "userName=" + encodeURIComponent(email) +
"&password=" + encodeURIComponent(password) +
"&grant_type=password"
).success(function (data) {
//...
You can try with below solution
$http({
method: 'POST',
url: url-post,
data: data-post-object-json,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for (var key in obj) {
if (obj[key] instanceof Array) {
for(var idx in obj[key]){
var subObj = obj[key][idx];
for(var subKey in subObj){
str.push(encodeURIComponent(key) + "[" + idx + "][" + encodeURIComponent(subKey) + "]=" + encodeURIComponent(subObj[subKey]));
}
}
}
else {
str.push(encodeURIComponent(key) + "=" + encodeURIComponent(obj[key]));
}
}
return str.join("&");
}
}).success(function(response) {
/* Do something */
});
Create an adapter service for post:
services.service('Http', function ($http) {
var self = this
this.post = function (url, data) {
return $http({
method: 'POST',
url: url,
data: $.param(data),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
}
})
Use it in your controllers or whatever:
ctrls.controller('PersonCtrl', function (Http /* our service */) {
var self = this
self.user = {name: "Ozgur", eMail: null}
self.register = function () {
Http.post('/user/register', self.user).then(function (r) {
//response
console.log(r)
})
}
})
There is a really nice tutorial that goes over this and other related stuff - Submitting AJAX Forms: The AngularJS Way.
Basically, you need to set the header of the POST request to indicate that you are sending form data as a URL encoded string, and set the data to be sent the same format
$http({
method : 'POST',
url : 'url',
data : $.param(xsrf), // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
});
Note that jQuery's param() helper function is used here for serialising the data into a string, but you can do this manually as well if not using jQuery.
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
Please checkout!
https://uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs
For Symfony2 users:
If you don't want to change anything in your javascript for this to work you can do these modifications in you symfony app:
Create a class that extends Symfony\Component\HttpFoundation\Request class:
<?php
namespace Acme\Test\MyRequest;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\ParameterBag;
class MyRequest extends Request{
/**
* Override and extend the createFromGlobals function.
*
*
*
* #return Request A new request
*
* #api
*/
public static function createFromGlobals()
{
// Get what we would get from the parent
$request = parent::createFromGlobals();
// Add the handling for 'application/json' content type.
if(0 === strpos($request->headers->get('CONTENT_TYPE'), 'application/json')){
// The json is in the content
$cont = $request->getContent();
$json = json_decode($cont);
// ParameterBag must be an Array.
if(is_object($json)) {
$json = (array) $json;
}
$request->request = new ParameterBag($json);
}
return $request;
}
}
Now use you class in app_dev.php (or any index file that you use)
// web/app_dev.php
$kernel = new AppKernel('dev', true);
// $kernel->loadClassCache();
$request = ForumBundleRequest::createFromGlobals();
// use your class instead
// $request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
Just set Content-Type is not enough, url encode form data before send.
$http.post(url, jQuery.param(data))
I'm currently using the following solution I found in the AngularJS google group.
$http
.post('/echo/json/', 'json=' + encodeURIComponent(angular.toJson(data)), {
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
}).success(function(data) {
$scope.data = data;
});
Note that if you're using PHP, you'll need to use something like Symfony 2 HTTP component's Request::createFromGlobals() to read this, as $_POST won't automatically loaded with it.
AngularJS is doing it right as it doing the following content-type inside the http-request header:
Content-Type: application/json
If you are going with php like me, or even with Symfony2 you can simply extend your server compatibility for the json standard like described here: http://silex.sensiolabs.org/doc/cookbook/json_request_body.html
The Symfony2 way (e.g. inside your DefaultController):
$request = $this->getRequest();
if (0 === strpos($request->headers->get('Content-Type'), 'application/json')) {
$data = json_decode($request->getContent(), true);
$request->request->replace(is_array($data) ? $data : array());
}
var_dump($request->request->all());
The advantage would be, that you dont need to use jQuery param and you could use AngularJS its native way of doing such requests.
Complete answer (since angular 1.4). You need to include de dependency $httpParamSerializer
var res = $resource(serverUrl + 'Token', { }, {
save: { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
});
res.save({ }, $httpParamSerializer({ param1: 'sdsd', param2: 'sdsd' }), function (response) {
}, function (error) {
});
In your app config -
$httpProvider.defaults.transformRequest = function (data) {
if (data === undefined)
return data;
var clonedData = $.extend(true, {}, data);
for (var property in clonedData)
if (property.substr(0, 1) == '$')
delete clonedData[property];
return $.param(clonedData);
};
With your resource request -
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
This isn't a direct answer, but rather a slightly different design direction:
Do not post the data as a form, but as a JSON object to be directly mapped to server-side object, or use REST style path variable
Now I know neither option might be suitable in your case since you're trying to pass a XSRF key. Mapping it into a path variable like this is a terrible design:
http://www.someexample.com/xsrf/{xsrfKey}
Because by nature you would want to pass xsrf key to other path too, /login, /book-appointment etc. and you don't want to mess your pretty URL
Interestingly adding it as an object field isn't appropriate either, because now on each of json object you pass to server you have to add the field
{
appointmentId : 23,
name : 'Joe Citizen',
xsrf : '...'
}
You certainly don't want to add another field on your server-side class which does not have a direct semantic association with the domain object.
In my opinion the best way to pass your xsrf key is via a HTTP header. Many xsrf protection server-side web framework library support this. For example in Java Spring, you can pass it using X-CSRF-TOKEN header.
Angular's excellent capability of binding JS object to UI object means we can get rid of the practice of posting form all together, and post JSON instead. JSON can be easily de-serialized into server-side object and support complex data structures such as map, arrays, nested objects, etc.
How do you post array in a form payload? Maybe like this:
shopLocation=downtown&daysOpen=Monday&daysOpen=Tuesday&daysOpen=Wednesday
or this:
shopLocation=downtwon&daysOpen=Monday,Tuesday,Wednesday
Both are poor design..
This is what I am doing for my need, Where I need to send the login data to API as form data and the Javascript Object(userData) is getting converted automatically to URL encoded data
var deferred = $q.defer();
$http({
method: 'POST',
url: apiserver + '/authenticate',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: userData
}).success(function (response) {
//logics
deferred.resolve(response);
}).error(function (err, status) {
deferred.reject(err);
});
This how my Userdata is
var userData = {
grant_type: 'password',
username: loginData.userName,
password: loginData.password
}
The only thin you have to change is to use property "params" rather than "data" when you create your $http object:
$http({
method: 'POST',
url: serviceUrl + '/ClientUpdate',
params: { LangUserId: userId, clientJSON: clients[i] },
})
In the example above clients[i] is just JSON object (not serialized in any way). If you use "params" rather than "data" angular will serialize the object for you using $httpParamSerializer: https://docs.angularjs.org/api/ng/service/$httpParamSerializer
Use AngularJS $http service and use its post method or configure $http function.

Vue Resource Post Request Content-Type

Vue-Resource Post Request:
this.$http.post(form.action, new FormData(form)).then(function (response) {
FetchResponse.fetch(this, response.data)
})
Request are Send as Content-Type:"application/json;charset=utf-8" But No data can be displayed by PHP Post.
Set Up Header Vue-Resource:
request.headers.set('Content-Type', '');
But Request Content-Type:", multipart/form-data; boundary=----WebKitFormBoundaryTsrUACAFB1wuhFOR"
there is a comma at the beginning of the query.
Jquery Post Request:
$.ajax({
url : form.action,
type : 'POST',
data : new FormData(form),
success : function (reqData) {
FetchResponse.fetch(ss, reqData)
},
});
The same query works seamlessly with jQuery. jQuery Content-Type: "multipart/form-data; boundary=----WebKitFormBoundaryTsrUACAFB1wuhFOR"
Issue:
https://github.com/vuejs/vue-resource/issues/398
Please try instead to post a simple JSON object and enable the 'emulateJSON' vue-resource option:
const formData = {
someProp: this.someProp,
someValue: 'some value'
};
this.$http.post(this.postUrl, formData, {emulateJSON: true})
.then(response => {
console.log(response.body);
}, response => {
console.error(response.body);
});

http post return strange JSON [duplicate]

I am new to AngularJS, and for a start, I thought to develop a new application using only AngularJS.
I am trying to make an AJAX call to the server side, using $http from my Angular App.
For sending the parameters, I tried the following:
$http({
method: "post",
url: URL,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param({username: $scope.userName, password: $scope.password})
}).success(function(result){
console.log(result);
});
This is working, but it is using jQuery as well at $.param. For removing the dependency on jQuery, I tried:
data: {username: $scope.userName, password: $scope.password}
but this seemed to fail. Then I tried params:
params: {username: $scope.userName, password: $scope.password}
but this also seemed to fail. Then I tried JSON.stringify:
data: JSON.stringify({username: $scope.userName, password: $scope.password})
I found these possible answers to my quest, but was unsuccessful. Am I doing something wrong? I am sure, AngularJS would provide this functionality, but how?
I think you need to do is to transform your data from object not to JSON string, but to url params.
From Ben Nadel's blog.
By default, the $http service will transform the outgoing request by
serializing the data as JSON and then posting it with the content-
type, "application/json". When we want to post the value as a FORM
post, we need to change the serialization algorithm and post the data
with the content-type, "application/x-www-form-urlencoded".
Example from here.
$http({
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: {username: $scope.userName, password: $scope.password}
}).then(function () {});
UPDATE
To use new services added with AngularJS V1.4, see
URL-encoding variables using only AngularJS services
URL-encoding variables using only AngularJS services
With AngularJS 1.4 and up, two services can handle the process of url-encoding data for POST requests, eliminating the need to manipulate the data with transformRequest or using external dependencies like jQuery:
$httpParamSerializerJQLike - a serializer inspired by jQuery's .param() (recommended)
$httpParamSerializer - a serializer used by Angular itself for GET requests
Example with $http()
$http({
url: 'some/api/endpoint',
method: 'POST',
data: $httpParamSerializerJQLike($scope.appForm.data), // Make sure to inject the service you choose to the controller
headers: {
'Content-Type': 'application/x-www-form-urlencoded' // Note the appropriate header
}
}).then(function(response) { /* do something here */ });
See a more verbose Plunker demo
Example with $http.post()
$http.post(
'some/api/endpoint',
data: $httpParamSerializerJQLike($scope.appForm.data), // Make sure to inject the service you choose to the controller
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded' // Note the appropriate header
}
}
).then(function
How are $httpParamSerializerJQLike and $httpParamSerializer different
In general, it seems $httpParamSerializer uses less "traditional" url-encoding format than $httpParamSerializerJQLike when it comes to complex data structures.
For example (ignoring percent encoding of brackets):
• Encoding an array
{sites:['google', 'Facebook']} // Object with array property
sites[]=google&sites[]=facebook // Result with $httpParamSerializerJQLike
sites=google&sites=facebook // Result with $httpParamSerializer
• Encoding an object
{address: {city: 'LA', country: 'USA'}} // Object with object property
address[city]=LA&address[country]=USA // Result with $httpParamSerializerJQLike
address={"city": "LA", country: "USA"} // Result with $httpParamSerializer
All of these look like overkill (or don't work)... just do this:
$http.post(loginUrl, `username=${ encodeURIComponent(username) }` +
`&password=${ encodeURIComponent(password) }` +
'&grant_type=password'
).success(function (data) {
The problem is the JSON string format, You can use a simple URL string in data:
$http({
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: 'username='+$scope.userName+'&password='+$scope.password
}).success(function () {});
Here is the way it should be (and please no backend changes ... certainly not ... if your front stack does not support application/x-www-form-urlencoded, then throw it away ... hopefully AngularJS does !
$http({
method: 'POST',
url: 'api_endpoint',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: 'username='+$scope.username+'&password='+$scope.password
}).then(function(response) {
// on success
}, function(response) {
// on error
});
Works like a charm with AngularJS 1.5
People, let give u some advice:
use promises .then(success, error) when dealing with $http, forget about .sucess and .error callbacks (as they are being deprecated)
From the angularjs site here "You can no longer use the JSON_CALLBACK string as a placeholder for specifying where the callback parameter value should go."
If your data model is more complex that just a username and a password, you can still do that (as suggested above)
$http({
method: 'POST',
url: 'api_endpoint',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: json_formatted_data,
transformRequest: function(data, headers) {
return transform_json_to_urlcoded(data); // iterate over fields and chain key=value separated with &, using encodeURIComponent javascript function
}
}).then(function(response) {
// on succes
}, function(response) {
// on error
});
Document for the encodeURIComponent can be found here
If it is a form try changing the header to:
headers[ "Content-type" ] = "application/x-www-form-urlencoded; charset=utf-8";
and if it is not a form and a simple json then try this header:
headers[ "Content-type" ] = "application/json";
From the $http docs this should work..
$http.post(url, data,{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
.success(function(response) {
// your code...
});
$http({
method: "POST",
url: "/server.php",
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: "name='Олег'&age='28'",
}).success(function(data, status) {
console.log(data);
console.log(status);
});
you need to post plain javascript object, nothing else
var request = $http({
method: "post",
url: "process.cfm",
transformRequest: transformRequestAsFormPost,
data: { id: 4, name: "Kim" }
});
request.success(
function( data ) {
$scope.localData = data;
}
);
if you have php as back-end then you will need to do some more modification.. checkout this link for fixing php server side
Though a late answer, I found angular UrlSearchParams worked very well for me, it takes care of the encoding of parameters as well.
let params = new URLSearchParams();
params.set("abc", "def");
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded'});
let options = new RequestOptions({ headers: headers, withCredentials: true });
this.http
.post(UrlUtil.getOptionSubmitUrl(parentSubcatId), params, options)
.catch();
This worked for me. I use angular for front-end and laravel php for back-end. In my project, angular web sends json data to laravel back-end.
This is my angular controller.
var angularJsApp= angular.module('angularJsApp',[]);
angularJsApp.controller('MainCtrl', function ($scope ,$http) {
$scope.userName ="Victoria";
$scope.password ="password"
$http({
method :'POST',
url:'http://api.mywebsite.com.localhost/httpTest?callback=JSON_CALLBACK',
data: { username : $scope.userName , password: $scope.password},
headers: {'Content-Type': 'application/json'}
}).success(function (data, status, headers, config) {
console.log('status',status);
console.log('data',status);
console.log('headers',status);
});
});
This is my php back-end laravel controller.
public function httpTest(){
if (Input::has('username')) {
$user =Input::all();
return Response::json($user)->setCallback(Input::get('callback'));
}
}
This is my laravel routing
Route::post('httpTest','HttpTestController#httpTest');
The result in browser is
status 200
data JSON_CALLBACK({"username":"Victoria","password":"password","callback":"JSON_CALLBACK"});
httpTesting.js:18 headers function (c){a||(a=sc(b));return
c?a[K(c)]||null:a}
There is chrome extension called postman. You can use to test your back-end url whether it is working or not.
https://chrome.google.com/webstore/detail/postman-rest-client/fdmmgilgnpjigdojojpjoooidkmcomcm?hl=en
hopefully, my answer will help you.

How take data from json response in angularjs

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

angularjs - POST an array of objects(JSON data) to a PHP page

An example of how my JSON data is like:
$scope.a = [{
"email": "keval#gmail",
"permissions": {
"upload": "1",
"edit": "1"
}
}, {
"email": "new#aa",
"permissions": {
"upload": "1",
"edit": "1"
}
}];
I want to post the same, and here's my approach:
$http({
method: 'POST',
url: 'backend/savePermissions.php',
data: {
mydata: $scope.a
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.success(function(data) {
console.log(data);
});
And the PHP is to take the request and respond:
echo $_POST['mydata'];
I tried JSON.stringify before the call and json_decode while echoing it back; still didn't work. Been trying all the possibilities I can think of, and what I find on the web/other questions, but still not working.
I've made plnkr for you
http://plnkr.co/edit/K8SFzQKfWLffa6Z4lseE?p=preview
$scope.postData = function () {
$http.post('http://edeen.pl/stdin.php', {user:$scope.formData}).success(
function(data){
$scope.response = data
})
}
as you can see I'm sending a raw JSON without formating it, then in php
<?php
echo file_get_contents('php://input');
I read the JSON directly and echo it but you can do whatever you want
read more about php://input here http://php.net/manual/en/wrappers.php.php
I was using it for a long time for REST services to avoid transforming JSON to string to many times
I use this, with which I can send Array JSON:
var array = {}
array['key1'] = value1;
array['key2'] = value2;
$http.post(URL, array)
.success(function(data){
})
.error(function(){
});
try using $httpParamSerializer or $httpParamSerializerJQLike
$http({
method: 'POST',
url: 'backend/savePermissions.php',
data: $httpParamSerializer($scope.a),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.success(function(data) {
console.log(data);
});

Categories