I am trying to access object properties from a request from my Angular app. I am using Laravel 5.1
Angular:
console.log('getQuestionAnswers', params);
return $http({
method: 'GET',
url: url + ver + '/questions/checkMany',
params: {
'questions[]' : params
},
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer ' + $rootScope.access_token
},
cache: true
});
Console.log of params:
Laravel:
public function getAnswers(Request $request)
{
$input = $request->all();
$question_objs = $input['questions'];
foreach ($question_objs as $question_answer_object) {
return $question_answer_object;
Response to Angular with: return $question_objs;
Response to Angular with: return $question_answer_object;
Looks like so far so good!
But if I try to access a property within laravel, like question_id:
return $question_answer_object['question_id'];
I get error:
"Illegal string offset 'question_id'
Laravel already parses the JSON,
// From Illuminate/Http/Request.php all() method:
if (! isset($this->json)) {
$this->json = new ParameterBag((array) json_decode($this->getContent(), true));
}
and when I return it, I can see it's an object. Why can't I access the properties? I've also tried json_decode without luck.
With JSON Decode:
$test = json_decode($question_answer_object, true);
return $test['question_id'];
This seems to work. But why?
Accessing the property on the object as such:
return $question_answer_object->question_id;
Gives the following error:
"Trying to get property of non-object"
The $question_answer_object['question_id'] variable is a string comprising JSON encoded data; to access that, you need to decode it first:
$decoded= json_decode($question_answer_object['question_id'], true);
return $decoded['question_id'];
If you're not sending the request as application/json, use $request->json().
You can get some information about this issues here.
Returned question is an object, not an array. You have to acces it with ->
return $question_answer_object->question_id;
Related
I am just trying to fetch an array of key value pairs from PHP and send the response back to AngularJS $http GET request:
PHP Code get_projects.php file:
<?php
header('Content-Type: application/json');
$data = [{"id" => 1, "name" => 'Audi'}, {"id" => 2, "name" => 'BMW'}, {"id" => 3, "name" => 'Honda'}];
$encode = json_encode($data);
echo $encode;
?>
AngularJS Controller code:
app.controller('MainController', ['$scope', '$http', function ($scope, $http) {
$scope.name = 'Search';
$scope.projects = '';
$http({
method: 'GET',
url: 'includes/get_projects.php',
params: {}
}).then(function success(response) {
$scope.projects = response.data;
alert($scope.projects);
});
}]);
The alert($scope.projects); always returns [object Object]. The echo gettype($encode); prints string but the alert statement prints [object Object]. I have tried angular.fromJson() but still it prints [object Object].
I am really confused with the concept of json_encode() function in PHP. Please help me fix the problem.
You converted the PHP array to a string by serializing it using JSON. $encode therefore is a string, which is fine.
Your frontend now gets the response and (since it came with the content type of application/json) already deserialized it for you from a JSON string to a JavaScript object.
Attempting to convert an object to a string will give you something like [object Object]. alert isn't the right tool here since it can work with a string only.
Try console.log instead and check your devtools console output, there you'll see an explorable object. (Even better: In your devtools debugger, set a breakpoint in the success handler and inspect the object at that point.)
Bottom line: It's all working fine, you just didn't use the right method to look at your object.
#CherryDT I think i fixed the problem.
var make = [];
for (var key in response.data) {
if(response.data.hasOwnProperty(key)){
make.push({
"id": response.data[key].id,
"name": response.data[key].name
});
}
}
$scope.projects = JSON.stringify(make);
$scope.projects = angular.fromJson($scope.projects);
PHP send the array as string with json_encode.
AngularJS response.data takes the response as Object.
Loop through the response.data object and push the key/values to variable make.
Create a string with JSON.stringify.
Convert the JSON string to Object using angular.fromJson.
I have viewed couple of blogs which assign the response.data object directly to $scope variable but in my case it did not work.
AngularJS version i am using is : AngularJS v1.2.8
So I have a josn object which has an array of objects which I want to send to a react native app through https but the problem is that I get null in react native
The code of the php :
<?php
class Product {
// Properties
public $title;
public $price;
}
header('Content-Type: application/json');
$ProductList =array();
$aa=$a->{'shopping_results'};
foreach($aa as $y => $y_value) {
$product = new Product();
$product->{'title'} = $y_value ->{'title'};
$product->{'price'} = $y_value ->{'price'};
array_push($ProductList,$product);
}
echo $x=json_encode(array('listx' => $ProductList),JSON_UNESCAPED_UNICODE);// the JSON_UNESCAPED_UNICODE for the Arabic letters
?>
When I try to view the content of this json on the browser this is what I get
https://i.stack.imgur.com/gXT4X.png
The react native code
await fetch(URL, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
// , body: JSON.stringify({ name: "tea" })
})
.then((response) => response.text()) //tried .json() got JSON Parse error: Unexpected EOF
.then((responseJson) => {
console.log(responseJson);//This prints blank
console.log("hi");
this.setState({ output: responseJson });//nothing shows
})
.catch((error) => {
console.error(error);
});
Note: I tried to receive a text from HTTPs request and it worked (The connection is fine)
You need to set HTTP headers, methods in your PHP code so as to accept requests from your react native app (basically I'm telling you to implement REST APIs). If already implemented, just make sure you are giving the correct endpoint in your react-native's fetch URL. And one more thing, when you are trying to retrieve data from the server make sure to set method: 'GET'.
If you're a beginner/ don't have prior knowledge about REST APIs, then here's a reference for you : https://www.positronx.io/create-simple-php-crud-rest-api-with-mysql-php-pdo/ I'm sure it'll give you some basic idea about your need.
I'm trying to send a text that is typed via ajax to a php page that will make a query using that text that is received. I want to know how to send the value of variable nmClient to the php page. I tried the following code and the return was 500 (Internal Server Error). I'm using the framework Symfony
Jquery
var name = $("#name").val();
$.ajax({
url: "../search",
type: "POST",
data: {'name':name},
dataType: "json"
}).done(function(response) {
console.log(response);
}).fail(function(jqXHR, textStatus ) {
console.log("Request failed: " + textStatus);
}).always(function() {
console.log("done");
});
PHP
public function searchAction(Request $resquest)
{
if ($request->isXMLHttpRequest()) {
$name = $request->get('name');
return new JsonResponse(array('name' => $name));
}
return new Response('This is not ajax!', 400);
}
I believe you're trying to access the parameter name in the incorrect place. The get() method is available on the ParameterBag instance, not the Request instance. Try the following:
$name = $request->request->get('name');
Per the docs here:
Each property is a ParameterBag instance (or a sub-class of), which is a data holder class:
request: ParameterBag;
query: ParameterBag;
cookies: ParameterBag;
attributes: ParameterBag;
files: FileBag;
server: ServerBag;
headers: HeaderBag.
All ParameterBag instances have methods to retrieve and update their data:
get() Returns a parameter by name.
Here is the example from that same page:
// the query string is '?foo[bar]=baz'
$request->query->get('foo');
In the docs example case, the parameters are passed via the GET method as a query string but they access them via the query ParameterBag instance. You'll want to use the request Parameter Bag instance since your parameters are passed via the POST method.
In my AngularJS Service I have an array of id's which I want to pass to a PHP server so it can delete them but somehow I keep on getting a 500/Internal Server Error response.
In my server log it's saying that the request is missing one argument which means the passing to the server wasn't successful.
I have something like this in my service:
destroySelected : function (ids) {
// console.log(ids);
// return $http.delete('/posts/destroySelected', ids);
return $http({
method: 'DELETE',
url: '/posts/destroySelected/',
headers: {'Content-Type': 'application/json;charset=utf-8'},
data: {ids : ids}
});
}
For my php controller I have this:
public function destroySelected($ids) {
echo "<pre>" . var_export($ids, true) . "<pre>";
die;
return response()->json(Post::get());
}
my route:
Route::delete('posts/destroySelected/', 'PostController#destroySelected');
It's empty, but I wanted to double check that it's being passed successfully before I do anything else.
Can someone tell me what's going wrong here?
You didn't provided any data to the controller :)
You have : url: '/posts/destroySelected/' and data: {ids : ids}
So, your final url will be /posts/destroySelected/?ids=1 (for example)
The parameter $ids on your request require an url route parameter (for example route /posts/destroySelected/{ids}) and not a query parameter (_GET/_POST)
Solution:
return $http({
method: 'DELETE',
url: '/posts/destroySelected/' + ids,
headers: {'Content-Type': 'application/json;charset=utf-8'}
});
To get the query parameter (_GET), you can use:
<?php
public function destroySelected(Request $request) {
$ids = $request->input('ids'); // will get the value of $_REQUEST['ids'] ($_GET or $_POST)
// var_dump($request->all()); for all values
echo "<pre>" . var_export($ids, true) . "<pre>";
die;
return response()->json(Post::get());
}
I ask my API for data as it used to be,
I think my API is not displaying data correctly but I can't find what I am doing wrong.
Here is my code
JS looks like:
function getSoapData(){
var myPromise = $http({
method: 'GET',
url: 'http://example.com/api/v1/Soap.php?vin=' + $scope.vin
});
return myPromise;
};
$scope.doWE = function(){
getData().success(function(data){
console.log(data);
$scope.cases = data;
getSoapData().then(function(soapData){
$scope.soapCases = soapData;
console.log(soapData);
});
});
};
PHP looks like:
$data = array (
"caseNumber" =>$claim['#attributes']['id'],
"date_created" =>$claim['country'],
"country" =>$claim['creation'],
"currency" =>$claim ['specific']['currency'],
"insurer_memberid" =>$claim['insurance']['id'],
"laborcosts" =>$claim ['specific']['partsCost'],
"model" =>$claim ['specific']['model_name'],
"orgName" =>$claim['insurance']['name'],
"paintLabor" =>$claim['specific']['paintmaterial'],
"totalcosts" =>$claim ['assessment']['damage-value']
);
echo $this->convertToJson($data);
and data which comes looks like:
{"caseNumber":"2003-09-30.BEL.BE01001129143","date_created":"BEL","country":"2003-09-30","currency":null,"insurer_memberid":"1671","laborcosts":null,"model":null,"orgName":"ZELIA INSURANCE","paintLabor":null,"totalcosts":"11157.02"}
However, I get this error:
Error: [orderBy:notarray] Expected array but received:
{"data":"Array","status":200,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"url":"http://example.com/api/v1/Soap.php?vin=VF38BRHZE80728805","headers":{"Accept":"application/json,
text/plain, /"}},"statusText":"OK"}
Error expect problem on this line:
<tr ng-repeat-start="soapCase in soapCases | orderBy:sortField:reverse">
It says it expects an array but didn't get it. I really don't think it should expect an array instead of JSON.
Any advice as to what I'm doing wrong?
EDIT:
I have one similar function getdata() function that looks like:
function getData(){
var myPromise = $http({
method: 'GET',
url: 'http://www.audahistory.cz/api/v1/History.php?vin=' + $scope.vin
});
return myPromise;
};
with result:
http://pastebin.com/s31jhnip
but this works correctly
In your PHP code you're building an array, but indexed with strings, so it gets converted to a JSON object. ng-repeat expects array, so someting like:
[{"caseNumber":"2003-09-30.BEL.BE01001129143","date_created":"BEL","country":"2003-09-30","currency":null,"insurer_memberid":"1671","laborcosts":null,"model":null,"orgName":"ZELIA INSURANCE","paintLabor":null,"totalcosts":"11157.02"}]
So in PHP you should insert this associative array into normal array:
$result = array();
$result[] = $data;
And then try to convert it into JSON.
echo $this->convertToJson($result);
If there's no data returned you have two options:
Return an empty array converted to JSON
Return HTTP 404 error response and handle that in Angular.