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
Related
I have the following in a js script:
let skippers = {};
for(let i = 0; i < skipperIds.length;i++){
skippers[skipperIds[i].value] = skipperIds[i].checked;
}
regData.skippers = skippers;
responseData = sendData2('https://sailwbob.com/lagin/public/register.php',regData);
where sendData2 is an async call using axios. skippers looks like
{1:true,20:false}
In my php file I have:
$skippers = ($_POST['skippers']);
$skipperIds = array_keys($skippers);
$skipperValues = array_values($skippers);
but this is not working. I think php converts an array in $_POST to a string but I'm not sure.
two qustions:
how do I convert $skippers back to an array?
I've been trying to use print_r to see the data on the server but as this is an async call it's not working as the print_r results are being sent back to the js script and not printing out on the screen. Is there a way to see the results of print_r?
Update:
I tried $x=json_decode($_POST); but got an error saying it was expecting a string.
here's the call to axios:
function sendData2(url,emailPass){
let bodyFormData = new FormData()
for (const [key, value] of Object.entries(emailPass)) {
//console.log(key,value)
bodyFormData.append(key,value)
}
return axios({
method: 'POST',
url: url,
data: bodyFormData,
headers: {'Content-Type': 'multipart/form-data'}
})
.then(function(response){
return response.data
})
.catch(function(response){
return response
})
}
update2:
$skippers shows $skippers = [object Object]. Is there a way to send this to the server correctly?
As discussed in this article, axios serializes Javascript objects to JSON and becase PHP doesn't support JSON as a data format for populating $_POST, you can retrieve them in PHP like this:
$_POST = json_decode(file_get_contents("php://input"),true);
$skippers = $_POST['skippers'];
While axios does automatically stringify data it apparently doesn't do that for nested arrays. I needed to add:
regData.skippers = JSON.stringify(skippers); in my js
and then in the php file
$skippers = get_object_vars(json_decode($_POST['skippers']));
Am passing data to yii2 using ajax request but i keep on getting a 500 error
This is the ajax request code:
<?php
$script = <<< JS
$('form#forward_pr').on('beforeSubmit', function(e){
var keys = $('#grid').yiiGridView('getSelectedRows');
$.post({
url: "forwardpr", // your controller action
dataType: 'json',
data: {keylist: keys},
success: function(data) {
alert('I did it! Processed checked rows.')
},
error: function(err){
console.log("server error");
}
});
return false;
} ) ;
JS;
$this->registerJS($script);
?>
When i do console.log(keys) this returns
[0, 1]
This is my controller code:
if (Yii::$app->request->post()) {
echo $post = json_encode($_POST['keys']);
if (isset($_POST['keylist'])) {
$keys = \yii\helpers\Json::decode($_POST['keylist']);
print_r($keys);
}else{
echo "1";
}
The above always executes the error part of post request, What could be wrong;
You are sending your JSON as encoded (post) data body, not key value pairs. So your approach is not working this way.
There are two options to fix this:
refactor your controller into a RESTful service
in your controller use the JSON body rather than POST parameters
While the first option is preferred in the long run, the second option is pretty simple as a quick fix.
First, make sure you configure your app to parse JSON body conten.
IN config.php add this to the components array:
'request' => [
'parsers' => [
'application/json' => 'yii\web\JsonParser',
]
]
Then in your controller use this to get the JSON parameters:
$model->load(Yii::$app->getRequest()->getBodyParams());
I'm a newbie.. But I also want use checkboxcoloumns in gridview (Kartik version).
1st thing.
Instead of writing
var keys = $('#grid').yiiGridView('getSelectedRows');
I have to write
var keys = $('#w4').yiiGridView('getSelectedRows');
2nd thing.
In the controller you can process the keylist, but don't try to decode it, simple use it int this way:
$keys = $_POST['keylist'];
and it seems it works for me!
Sorry for my english..
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.
Im working on some AJAX login function, making a request via PHP.
I am wondering how do I return data via the PHP so that I can handle it like the code mentioned below. I only worked on the javascript side and not the PHP server side so I am confused now.
I want to get a value/values stored in the response like data.name , data.sessionID , data.listOfnames
Is the data a JSON Object by itself?
Thanks!
The code below was used before and has been verified to work.
function retrieveVersion(){
var URL = RSlink + "/updates";
$.ajax({
headers : {
"Content-Type" : "application/json; charset=UTF-8",
"sessionid" : result
},
type : "GET",
url : vURL,
statusCode : {
0 : function() {
hideLoadingMsg();
showError(networkError, false);
},
200 : function(data) {
currentVersion = String(data.version);
updatesArray=data.updates;
});
}
}
});
Suppose you have a php file for handling ajax calls. It should be available by this url - vURL.
In this file you need to create an array.
Something like this:
$data = array('data' => array('version' => yourversion, 'updates' => yourupdates));
Then you need to convert this object into json string. You can do this using json_encode() function
echo json_encode($data);
One thing to keep in mind: You need to echo your data and only. If somewhere in your file you will have some other echo-es, the result string returning to your ajax-funtion might be broken.
I am finding difficulty in accessing elements in an array from php file. The array is passed through an ajax call. Please find below the ajax call.
var data = ['test1', 'test2', 'test3'];
$(document).ready(function () {
$("button").click(function () {
$.ajax({
type: "POST",
url: "getResult.php",
data: {
testData: data
},
success: function (data, status) {
alert("Data: " + data + "\nStatus: " + status);
}
});
return false;
});
});
The server side [PHP] code is
$myArray = $_POST["testData"];
echo $myArray;
However $myArray always returns last element[test3 here] in the array. How do I access first [here test1] and other elements?
Pls help.
What you need to do is convert the JavaScript array to JSON and then send over that JSON.
On the PHP side you should decode the JSON back into an array. Finally, you should re-encode the array as JSON before sending it back.
On your client side change one line:
data: {testData : JSON.stringify(data)},
On your server side do:
$myArray = json_decode($_POST["testData"]);
header('Content-Type: application/json');
echo json_encode(array('pheeds' => $pheeds, 'res' => $res));
JS:
JSON.stringify(data)
PHP:
$myArray = json_decode($_POST['data']);
For simple structures you can use jQuery Param
data : $.param({testData:data})
With this you should be able to access your data with
echo $_POST["testData"][0]...[2];
Try this when passing JS vars by ajax.
use Firebug to see on the console what is being poted to the PHP file, this will save you a lot of trouble.
you will see that array is an OBJECT , So you want to send this array as a JSON / STRING to the PHP file.
use :
var data = ['test1','test2','test3'];
data = JSON.stringfy(data);
at the PHP:
$data = var_post('test_data');
$data=json_decode($data);
$print_r($data);