POST parameter not working in twilio REST api - php

I am trying to (and have to) use the twilio rest api to create/update channel for ip messaging using angularjs.
Below is my code: The problem i am facing is, the POST parameter is not working. Channel is created with name is null value. Please help me.
.controller('updatechannel',function($scope, $http) {
$http({
method : "POST",
url : "https://ip-messaging.twilio.com/v1/Services/IS*******/Channels" ,
headers:{
'authorization': '*******',
'Content-Type':
'application/x-www-urlencoded'
},
data :{
"friendlyName":"NEW_FRIENDLY_NAME"
}
}).success(function(data,status, header, config) {
$scope.channelname = data;
}).error ( function (data, status, header, config) {
$scope.channelname = 'ERROR';
});
})

try something like this.
var con = "your url"
var params = $.param({ //your parameters
friendlyName: "NEW_FRIENDLY_NAME",
ormore:"one more parame"
});
$http.post(con, params, config
).success(function (data, status, headers, config) {
$scope.channelname = data;
})
.error(function (data, status, header, config) {
$scope.channelname = 'ERROR';
});

Related

Redirect AJAX response URL from PHP header

I have an AJAX POST that is sending back a successful response from my PHP file newPNRsubmit.php :
if(isset($_POST['ticketentry'])){
$_SESSION['ticketEntry'] = 1;
header("location: pnr-details?id=".$pnrid);
}
However I would like to use the AJAX response that I am receiving into window.location
This is the response:
XHR finished loading: GET "https://example.com/pnr-details?id=240".
This is my AJAX structure:
$.ajax({
type: "POST",
url: "newPNRsubmit.php",
data: {
bookingdate: bookingdate,
airline_id: airline_id
},
cache: false,
success: function(data, url) {
$('#NewPNRModal').modal( 'hide' );
},
error: function(xhr, status, error) {
console.error(xhr);
}
});
return false;
How can I correctly parse the URL that I am receiving into window.location ?
UPDATE: This is the response from console tab. The second GET XHR is showing the link I need for window.location. Should I update the header location to send JSON data in my PHP file in order for this to work?
Either return a URL in the body instead of a header, or get the header like so:
success: function(data, URL, jqXHR) {
window.location.href = jqXHR.getResponseHeader("location");
}

Ionic/AngularJS 2nd request not sending data but getting success answer

I get the following issue when the user click the "login" button. Everything get well until the "addOrCreateUser" function. Here the POST request seems to be executed (I get an OK alert). Nevertheless, I have no log in my server side. I tried to lunch the "addOrCreateUser" based on a button click and then it works. Any idea?
.controller("LoginController", function ($scope, $cordovaOauth, $http, $localStorage, $location) {
$scope.form = {};
$scope.login = function () {
$cordovaOauth.facebook("xxxxxxxxxxxx", ["email"]).then(function (result) {
$localStorage.accessToken = result.access_token;
getUser($localStorage.accessToken);
}, function (error) {
alert("There was a problem signing in! See the console for logs");
console.log(error);
})
}
function getUser(token) {
$http.get("https://graph.facebook.com/v2.6/me", {
params: {
access_token: token,
fields: "id,email",
format: "json"
}
}).then(function (result2) {
$scope.form = {
'id' : result2.data.id,
'email' : result2.data.email
}
addOrCreateUser($localStorage.accessToken, $scope.form);
}, function (error) {
alert("There was a problem getting your profile. Check the logs for details.");
console.log(error);
});
}
function addOrCreateUser (token, form) {
$http.defaults.headers.common['Auth-Token'] = token;
$http({
url: API_URL + "/profiles",
data: form,
method: 'POST',
headers: {'Content-Type': 'application/json'}
}).success(function (data, status, headers, config) {
alert("ok" + data )
}).error(function (data, status, headers, config) {
alert("ko")
});
}
})

Http Post not sending data to another page in angular js

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

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 - Cannot pass parameter

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

Categories