AngularJs POST request for json not working - angularjs

Hi i tried POST json data in two ways its response in null
var jsonData = $scope.addedCat;
console.log(jsonData);
var request = $http({
method:"POST",
url:base_url+"Category_controller/json_test",
data: JSON.stringify(jsonData),
dataType: "application/json"
});
request.success(
function(response){
console.log(response);
});
var cat_j = $scope.addedCat;
var data = $.param({ json:JSON.stringify(cat_j)});
$http.post(base_url+"Category_controller/json_test/",data).success(function(data, status) {
console.log(data);
console.log(status);
})
How we decode the json data in php.
I tried like this in Codeignitor framework.
$cjson = $this->input->post('jsonData');
$cat_json = json_decode($cjson);
echo json_encode($cat_json);

On your server php file , try that instead, and you get the parametes passed from client:
//get parameters
$params = json_decode(file_get_contents('php://input'), true); //read values from angular directive

Superglobal $_post only support application/x-www-form-urlencoded and multipart/form-data-encoded.
For application/json you should use php://input which can give you the raw bytes of the data. Here is a sample code of how to get the input data:
// get the raw POST data
$rawData = file_get_contents("php://input");
// this returns null if not valid json
print_r(json_decode($rawData));

$data = json_decode(file_get_contents('php://input'), true);
and do $data['jsonData']
now this $data['jsonData'] === $this->input->post('jsonData');

Related

How to use JSON data in your Ajax success

I send some data using the AJAX request.
On my PHP page I have following code.
$rouid = "";
if (isset($_POST['routeid'])) {
$rouid = $_POST['routeid'];
$array = array('routeid' => $rouid);
echo json_encode($array);
}
I am encoding the data into JSON.
Now I want to send this json back to my original page where I sent data from.
How can I get this $array variable into ajax request success.
var routeid=$('#routeid').val();
$.ajax({
url:"yoururlhere",
type:"post",
data:{routeid: routeid},
dataType:"json",
contentType:"application/json",
success:function(response){
console.log(response);
var ROUTEID=response.routeid;
},error:function(err){
alert("ERROR")
}
});

how to receive array data in ajax request page wordpress

I am sending array to PHP through angularJs $http, but when I receiving data it was showing null, I don't know is that my procedure is correct or not,
js file is
var newdisable_comments_on_post_types = JSON.stringify(allTabData.disable_comments_on_post_types);
$http({
method:'post',
url:url,
params:{
'disable_comments_on_post_types': newdisable_comments_on_post_types
}
});
while sending in the header it sending like this
disable_comments_on_post_types:{"post":false,"page":false,"attachment":false}
in the PHP file, i did some of the procedure to receive it
$a = $_POST['disable_comments_on_post_types']['post'];// method 1
$a = $_POST['disable_comments_on_post_types'] // method 2
$x=1
foreach($a as $val){
$b[$x]=$val;
$x++;
}
$a = $_POST['disable_comments_on_post_types']->post;// method 3
I am getting null in response every method while I returning data to check
echo json_encode($a);
am I doing any wrong or in WordPress we cant send an array to PHP?
Change Your $http service to this:
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"
$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: allTabData.disable_comments_on_post_types
}).success(function () {});

angular POST not working with servlet

I am trying to use angularjs POST (or even GET) to a servlet with the following:
var json = { hello: "world" }
var deffered = $q.defer();
$http({
method: "POST",
url: url,
headers: { "Content-Type" : "application/json" },
request: JSON.stringify(json)
}).then(data) {
if(data.data) {
deferred.resolve({
response : data
});
)
})
return deffered.promise;
within the servlet, simple:
String val = request.getParameter("request")
it never seems to see it
I have tried:
data: JSON.stringify({ request: json })
data: { request: json }
"request" : JSON.stringify(json)
etc
if I comment out the getParameter and just return a generic value using Gson
JsonObject json = new JsonObject();
json.addProperty("This", "works");
response.getWriter().print(new Gson().toJson(json));
that comes back fine so is there something within the angular POST I am doing wrong here? I have also tried using "GET" instead but same result.
EDIT: I would like to understand POST method and the "proper" way to get the data from the json object if getParameter is wrong please~
getParameter() returns http request parameters, you should add this params by using :
params: JSON.stringify(json)
Not with
request: JSON.stringify(json)
Take a look in params in get and params in post.

Angular JS return undefined response

I am trying to make a http request and get the results which
I am able to do in the browser with the following
http://dev.markitondemand.com/MODApis/Api/v2/InteractiveChart/json?parameters={"Normalized":false,"NumberOfDays":5,"DataPeriod":"Day","Elements":[{"Symbol":"ACN","Type":"price","Params":["c"]}]}
But when I execute the following code the response returned is undefined.Can you tell me what am I doing wrong here
var test = JSON.stringify({"Normalized":false,
"NumberOfDays":5,
"DataPeriod":"Day",
"Elements":[{"Symbol":"ACN",
"Type":"price",
"Params":["c"]
}]
});
console.log(test);
$http({
url:"http://dev.markitondemand.com/MODApis/Api/v2/InteractiveChart/json",
method : "GET",
parameters: test
}).then(
/* success */
function(response) {
var stock = {};
stock = angular.fromJson(response);
var Data = stock.Dates;
console.log(Data);
$scope.content = response.data;
$scope.statuscode = response.status;
$scope.statustext = response.statustext;
console.log('success');
},
/* failure */
function(result) {
console.log('error');
});
Please guide me
Your Content-Type in response header is not properly set.
Check whether Content-Type in response header is application/json or not.
Currently it look like this Content-Type:text/javascript; charset=UTF-8
So, your response is not recieved in JSON format.Check for proper JSON encoding

Working with HTTP POST request with AngularJS

I'm developing a jsp which sends POST requests to a servlet. I would like to write content in raw payload instead of key-value form.
var addItemApp = angular.module('addItem',[]);
addItemApp.controller('addItemCtrl', function($scope, $http){
$scope.addItemBnClicked = function(){
var rqst = $http.post('http://127.0.0.1:8180/JSP/ws', "This is a test content");
rqst.success(function(rspnData, status, headers, config){
alert("Status: " + status);
});
}
});
Checking on the server side, I found that the payload doesn't contain anything. Please help, Thanks. ^^
%%%%%%%%%%%%%%% Edit %%%%%%%%%%%%%%%
I use the following code to get the payload.
String line = "";
String rqstRawBody = "";
while((line = servletRqst.getReader().readLine()) != null){
rqstRawBody += line;
}
System.out.println("rqstRawBody: " + rqstRawBody);
The rqstRawBody is finally an empty string. I believe the above java code is okay, as I get raw payload correctly for those requests sent using the chrome-app Rest Client.
You should change the Content-Type HTTP header. By default Angular sets that to application/json for a POST request.
var config = { headers: { 'Content-Type': 'text/plain' } };
var data = { someKey: 'SomeValue'};
$http.post('/url', data, config).then(...);
Or you can set it as the default for all requests as shown in the documentation:
module.run(function($http) {
$http.defaults.headers.common['Content-Type']= 'text/plain'
});

Resources