I'm trying to send data from my login FORM to backend writen in PHP using POST method.
my Angular code looks like:
$scope.getToken = function(){
// console.log $scope.login to make sure I'm not sending empty data
console.log($scope.login);
$http({
method: 'POST',
url: '../../api/v1/Oauth.php',
data: { 'login' : $scope.login, 'password' : $scope.password }
}).then(function successCallback(response) {
console.log(response);
}, function errorCallback(response) {
console.log(response);
});
};
and after that I try to catch it on my PHP:
if((isset($_POST['login']) AND isset($_POST['password'])))
{
$username = $_POST['login'];
$password = $_POST['password'];
echo $username;
}
else
var_dump($_POST);
This statement always go to else and return empty array.
Can someone advise me what I'm doing wrong or how can I debug this?
Because it looks that I send data fron angular correctly but it didn't come to server.
Thanks
Kind Regards
Andurit
Use this:
json_decode(file_get_contents('php://input'));
Check your network tab in your developer bar. You can see that you send payload data in the http body. That's why the $_POST array is empty.
Some older server side web libraries like Coldfusion/.NET/PHP have issues grabbing a POST BODY by default (which is how $http sends the data).
You can reference How to get body of a POST in php? to learn how to write your PHP in a way that it will accept the current and correct standard of sending data via a post.
To access the entity body of a POST or PUT request (or any other HTTP
method):
$entityBody = file_get_contents('php://input');
Also, the STDIN constant is an already-open stream to php://input, so
you can alternatively do:
$entityBody = stream_get_contents(STDIN);
try:
data: { login : $scope.login, password : $scope.password }
$http.post('url', {login: 'Alex', password: 'qwerty'}).then(function(){},function(){});
Related
I am doing Google Oauth login using Google Api's in Laravel 5.0. I get the data of currently logged in user's email,id_token and now I want to send these data to the controller(SigninController) for calling our own api and get the response back to the front end (signin.blade.php) via an Ajax query . But My Ajax query is not working. I am attaching the codes here .
My Signin.blade.php file's ajax looks like(I have included csrf header) :
$.ajax({
url: '/signin/oauth',
type:"POST",
data: data,
headers: { 'X-CSRF-Token' : token},
success:function(data){
console.log(data);
if(data){
console.log("Success nowwww for ajax expected data!");
// window.location.href = '{{url("/home")}}';
}
else{
console.log("Success ajax ! But not expected data!");
// window.location.href = '{{url("/signup")}}';
}
},error:function(){
alert("error!! ajax failure !!!!");
}
});
My routes.php looks like :
Route::post('/signin/oauth', [
'uses' => 'SigninController#signinProcessOauth',
'as' => 'post_signin_oauth',
]);
In my SigninController's signinProcessOauth function normal "Request for Form" is working but "Request->ajax()" maybe not working . It looks like :
.
.
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
.
.
public function signinProcessOauth(Request $request)
{
$getData = $request->ajax();
if ($getData) {
$authCode = $request['authCode'];
$idToken = $request['idToken'];
$userEmail = $request['userEmail'];
// call the api here and send the above data to the server and process the response like saving the cookie etc
return $authCode; // return according to the response,this will return in ajax success function,right now it is authcode just for testing purpose
}
return "error";
}
Everytime I run the code, I get "error!! ajax failure !!!!" response i.e. ajax's failure function is called . I can't figure it out Where the problem is? Or Is there any other way to to send the datam from view to controller and get back the response to the frontend ?
Thank you for reading such long post patiently . :) :)
Change your url as follow:
url: '{!! route('post_signin_oauth') !!}'
Hope this will work.
In your method $request is not an array, its an object. So you need to use -> to access properties.
everyone. I'm trying to create league of legend api, but I need to hide the api key. I know there is no way to hide the key from the front-end, so this is how I did it, I'm not sure this is the best way to do it. Please help me!! Thanks!
HTML.file
var getID = function(playerName) {
$.ajax({
type: "POST",
url:"test.php",
dataType:'json',
data: {'url': "api/lol/na/v1.4/summoner/by-name/"+playerName+"?"},
success: function(data){
playerID = data[playerName].id;
console.log(playerID);
}
});
};
So every time I'm calling ajax, I'm making a ajax request to the test.php file, and pass the url to it, then the php code will use the url to get request from the game server and send back the result to front-end.
test.php
<?php
header('Content-Type: application/json');
$url = $_POST['url'];
$json = file_get_contents('https://na.api.pvp.net/'.$url.'api_key=key');
$obj = json_decode($json);
echo json_encode($obj, JSON_PRETTY_PRINT);
?>
As long as the Ajax request will only trigger for a valid, authenticated user with an established session this looks good. Otherwise, anyone could call it with arbitrary 'playerNames'.
It will definitely prevent your API key from being exposed.
I just started fiddeling with pebble.js for a prototype. I have to make a connection to a server and send user data from the pebble (login information) to the server for a handshake and send back data from the server to the pebble. I am using pebble.js because its easy for prototyping.
Now I am using the ajax library (http://developer.getpebble.com/docs/pebblejs/#ajax) to setup the connection. I have the following code:
ajax(
{
url: URL,
method: 'post',
type: 'json',
data: {
auth : 'test'
}
},
function(data) {
// Success!
console.log(JSON.stringify(data));
},
function(error) {
// Failure!
console.log('no response');
}
);
In PHP on the server I get the complete header information by apache_request_headers(); and send it to the pebble with echo json_encode(apache_request_headers());
This results in an output of console.log(JSON.stringify(data))
{"Host":"192.168.0.113","Content-Type":"application/json","Accept":"*/*","Connection":"keep-alive","Cookie":"v2ci_session=55MmpPmzb2cvBWiq3VNgneHexYzBtIFr46Ycb94s2KNKwmnz%2FStJq3euLpUSuBmbsKmKou2915ZR5Cp%2FA7xXnK7FO5EHcnem3Xi6gLpAJPXCF51sQxVQn%2BP1fAmlDqEzSnZEVkbhAO3LkZzALdnjzUc2SPyRCdVx70xAnkohQVH%2BuaU7qZtlCtYwJ7MYQqwa1%2BXuPfw9Vb7vgduYqoWMB%2FVIab5uDPe1KnIxZ08reU1PHVTWXcXXyGCEwmYfCYDkXZSIH%2FcnM%2B4oKAu3kEalGX9jxEVvC6VKz4mAdg7O5Q4Ns%2BEKyTR5VqrpisfZcY2VWOX8ipjCuYMTTosY9Lm%2F0qSpU4P%2B2ObuXCbsJIYviK2EsQqj6%2BWNo0L3DEK6L2N7","User-Agent":"PebbleApp/20141016231206 CFNetwork/711.1.12 Darwin/14.0.0","Accept-Language":"nl-nl","Accept-Encoding":"gzip, deflate","Content-Length":"6"}
As you can see no data is send within the request.
Anyone have an idea why no data is send with the request?
Solved
I was able to solve it through the github of pebblejs. For people with the same problem:
When the 'type' is set to 'json' the ajax library does not only expect the response to be json, but also the data that is posted is posted as json. If you want to gather this data in an array in PHP use the following code:
json_decode(file_get_contents('php://input'), true);
I'm using AngularJS to $http.post an object, but I also want to include some kind of data in the URL (or some other way) to specify what this object contains and where to parse it in the PHP file. Any idea how I can send a variable similar to GET into the AngularJS post so in PHP I can route the object to the correct if statement for parsing?
Here is my AngularJS code:
$scope.saveSchool=function(){
var schoolData = angular.copy($scope.schoolsModal);
$http.post('data/data.php?schoolModal=save', schoolData).error(function(){
console.log('Did not post data to data.php');
});
};
And here is my PHP code in data.php file in hopes to receive and route the object to the correct if statement for parsing and eventually saving the data.
if (isset($_GET["schoolModal"])) {
if ($_GET["schoolModal"] == "save") {
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
echo "Acknowledged";
echo $postdata;
}
}
This doesn't work, as it doesn't throw any errors or return anything (PHP). This does work, but I'm unable to route the object in the php file (i would have to create a separate php file just for this angularjs json object).
$scope.saveSchool=function(){
console.log('saveSchool function initiated');
var schoolData = angular.copy($scope.schoolsModal);
$http.post('data/data.php', schoolData).error(function(){
console.log('Did not post data to data.php');
});
};
PHP Script that would need to be in it's own file, as I want to eventually have multiple post functions and parse the data as it's received:
if($_SERVER['REQUEST_METHOD']=='POST'){
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
echo $postdata;
}
That PHP code works just fine, but i'm unable to route the data to where it needs to go. I don't want to send ALL posts to that if statement. Any ideas, I'm new to AngularJS and PHP and doing my best to pick this up.
Consider this example from a project I did. It only has 1 param 'status', but obviously you can add all of your params to an object like that
postFavorite: function(id, type, record, resource) {
var xsrf = $.param({status: record.prop});
$http({
method: 'POST',
url: this.api_base + '/favorites/'+type+'/'+id,
data: xsrf,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
withCredentials: true
}).success(function(data, status, headers, config){
if(data.success){
console.log("Success:", data, status, headers, config);
}
});
},
First I am conface that I am Newbie to php,
I am using jquery(knockout js) at client side & PHP at server side. my code.
Client side: I am using knockout js(Javascript). to call my PHP service.
My Code:
self.VMSaveEditUserMode = function () {
try {
var params = { "ClientData": [controllerVM_.ClientID(), controllerVM_.VMList[0].ClientName(), controllerVM_.VMList[0].ShortName(), controllerVM_.VMList[0].Address(), controllerVM_.VMList[0].CreatedBy(), controllerVM_.VMList[0].CityName(), controllerVM_.VMList[0].PostalCode(), controllerVM_.VMList[0].ContactEmail(), controllerVM_.VMList[0].ContactPhone(), controllerVM_.VMList[0].IsCorporate()] };
$.ajax({
type: "POST",
url: URL + "index.php/phpService/SaveClient/" + controllerVM_.TokenKey(),
data: JSON.stringify(ko.toJS(params)),
contentType: "application/json",
async: true,
dataType: 'json',
cache: false,
success: function (response) {
},
error: function (ErrorResponse) {
if (ErrorResponse.statusText == "OK") {
}
else {
alert("ErrorMsg:" + ErrorResponse.statusText);
}
}
});
}
catch (error) {
alert("Catch:" + error);
}
}
Server Side My Code, I am using this PHP code to connect with DB.
PHP Code:
public function SaveClient($userToken)
{
$value = json_decode($Clientdata);
echo $value->ClientData[0];
}
*My Question *:
I am not clear on how to POST data in PHP ? I tried with $_POST[''] method as well as many more.
I am using eclipse as a php framework. so, not able to debug it when i post the data.Normally mode i am able to debug my code.but not from remotely.for that i made changes on php.ini file also.
How to get Response of Post Data on php code ?
How to debug via remote post ?
My Request sample:
suppose i use:
For, data: params, only at that time my request format is.
ClientData%5B%5D=4&ClientData%5B%5D=kamlesh&ClientData%5B%5D=KAM&ClientData%5B%5D=Junagadh&ClientData%5B%5D=me&ClientData%5B%5D=SANTA+ROSA&ClientData%5B%5D=76220&ClientData%5B%5D=kamlesh.vadiyatar%40gmail.com&ClientData%5B%5D=9998305904&ClientData%5B%5D=false
For, data: JSON.stringify(ko.toJS(params)),
{"ClientData":["4","kamlesh","KAM","Junagadh","me","SANTA ROSA","76220","kamlesh.vadiyatar#gmail.com","9998305904",false]}
If I understand correctly you need to create a PHP service which is able to receive REST-like requests from client.
In order to do thad you need to access raw POST data. In PHP its being done like this:
$ClientData = file_get_contents('php://input');
You can read more about php://input in the wrappers documentation.
Of course from the client's side the data need to be sent using the POST method and as raw data, i.e. as a string. You can obtain a string from object using JSON.stringify() which you already do.
If you pass an object, it will be converted to string internally by jQuery using query-string format. More on that in the jQuery documentation for $.ajax (the most importatnt options being data and processData).
Just pass the ajax data param as an object, don't convert it into JSON. Then in PHP use $_POST directly.
Use firebug or chrome dev tools to analyze the ajax request and see which data is sent
Use this simple jquery function to accomplish your task
$.ajax({
type: "POST",
url:"scripts/dummy.php",
data:"tbl="+table,
dataType:"json", //if you want to get back response in json
beforeSend: function()
{
},
success: function(resp)
{
},
complete: function()
{
},
error: function(e)
{
alert('Error: ' + e);
}
}); //end Ajax
in PHP use:
if(isset($_POST['ClientData'])){
$client_data = $_POST['ClientData']
}
now $client_data variable should contain the array.
For debugging purpose you can use php's built-in print_r() function. It's pretty handy.
here's is an example:
//make sure it's post request
if(isset($_POST)){
//now print the array nicely
echo "<pre>";
print_r($_POST);
echo "</pre>";
}