AngularJS $resource can't deserialized array into an object - php

I'm working with php Tonic and AngularJS. So I have angular that call a rest resource. The code of the rest is like this:
/**
* #method GET
*/
public function getData(){
$response = new Response();
$response->code = Response::OK;
$response->body = array("one","two");
return $response;
}
On backend, code return a Response object with an array in the body.
From angular I use $resource service to call backend:
return {
getBackData : function(){
var call = $resource('/table_animation_back/comunication');
call.get(function(data){
console.log(data);
});
}
}
The result of console.log is this:
Resource {0: "A", 1: "r", 2: "r", 3: "a", 4: "y", $promise: d, $resolved: true}0: "A"1: "r"2: "r"3: "a"4: "y"$promise: d$resolved: true__proto__: Resource
I tried to use:
call.query(function(){...})
but Response in php is an object and not an array, so in this way I got a javascript error.
I can't access to the array.
Where wrong?

You need to serialize your array to JSON before sending to client:
public function getData(){
$response = new Response();
$response->code = Response::OK;
// Encode the response:
$response->body = json_encode(array("one","two"));
return $response;
}

I think that you forgot encode data before return it to client. In the server-side, it should be:
$response->body = json_encode(array("one","two"));
return $response;
In client, I think that we should use $q.defer in this case. For example:
angular.module('YourApp').factory('Comunication', function($http, $q) {
return {
get: function(token){
var deferred = $q.defer();
var url = '/table_animation_back/comunication';
$http({
method: 'GET',
url: url
}).success(function(data) {
deferred.resolve(data);
}).error(deferred.reject);
return deferred.promise;
}
};
});

Related

How do I return JSON data from CodeIgniter to Google Apps Script?

so we've been making a chatbot in Google Apps Script and one of its functions is to display information from a database (hosted online). The script sends a POST request to a controller function in our CodeIgniter program:
function do_post(name, status, duration) {
// Make a POST request with a JSON payload.
var data = {
'name': name,
'status': status,
'key' : api_key,
'duration' : duration
};
var options = {
'method' : 'post',
'contentType': 'application/json',
'muteHttpExceptions' : true,
// Convert the JavaScript object to a JSON string.
'payload' : JSON.stringify(data)
};
var response = UrlFetchApp.fetch('https://www.domainname.com/bot/index.php/bot/process/', options);
Logger.log(response);
return response;
}
The function above successfully inserts a record into the database using our process() controller in CI, but the problem is in our response variable. It's of HttpResponse type and we don't know how to return that type from our controller. We want our controller to return something like {"Response": "success"} to our chatbot but we don't know how. We've tried returning a JSON-encoded array:
public function process()
{
$_POST = array_replace($_POST, json_decode(file_get_contents('php://input'), true) ?? []);
$name = $_POST["name"];
$status = $_POST["status"];
$api = $_POST["key"];
$duration = $_POST["duration"];
if ($api == api_key){
$result = $this->bot_model->add_log();
}
$res_array = array("response" => $result);
// encode array to json
$json = json_encode($res_array);
return ($json);
}
}
And we try accessing var response in our app script using response.getContentText(), but we get something like "string(39)" and then the value of our api_key. How do we access the json data from the response?
You need to set the mime-type of your page so you can serve JSON data by using the set_content_type() method from the Output class.
Check the code
public function process()
{
$_POST = array_replace($_POST, json_decode(file_get_contents('php://input'), true) ?? []);
$name = $_POST["name"];
$status = $_POST["status"];
$api = $_POST["key"];
$duration = $_POST["duration"];
if ($api == api_key){
$result = $this->bot_model->add_log();
}
// JSON OUTPUT
$this->output
->set_content_type('application/json')
->set_output(json_encode( array("response" => $result)));
}
I noticed that when a function in CodeIgniter is called via post, the return of that function is whatever is printed out by the function in any way, be it echo, print_r, or var_dump. So to return your JSON file to App Script simply do echo $json;.

How to retrieve a parameter from ajax to laravel API Controller

I have an API that requires a string parameter. I want to take the query parameter to the controller and process there. I tried $ajax_data = Input::get('query'); but it didnt work. Searched the same question but cant find a decent answer. Current error is $ajax_data is empty.
My ajax request:
const sendAPIRequest = function (csrf, f) {
$.ajax({
async: false,
url: 'api/apitest',
method: 'get',
data:{
query:"select?facet=on&q=*:*&rows=1&json.facet={Categories:{type:terms,field:price,limit:3}}"
},
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Bearer ' + tkid);
xhr.setRequestHeader('Accept', 'application/json');
xhr.setRequestHeader('X-CSRF-TOKEN', csrf.trim());
},
success: function (data) {
f(data);
},
error: function(xhr) {
//Do Something to handle error
}
});
};
My Controller API part:
public function apitest(){
$ajax_data = Input::get('query');
$user_type = UserAuthorizationHelper::user_authorization();
if ($user_type == Authorities::EDIT_ORGANISATIONS) {}
$query = new GuzzleHttp\Client();
try {
$response = $query->request('GET',SolrController::$url.$ajax_data);
} catch (GuzzleHttp\Exception\GuzzleException $e) {}
$data = $response->getBody()->getContents();
return response()->json(json_decode($data));
}
You are having a problem in this line:
$ajax_data = Input::get('query');
When you are making a request, Request object is sent with the data.
So, instead of Input replace it with Request's object, and you will get the desired output.
Something like this:
// Don't forget to import the Request's namespace
public function apitest(Request $request)
{
$ajax_data = $request->get('query');
// ... Rest of your code
}

API callback response

I'm using an API to send sms in my codeigniter project. After sending, it will return a response array in the form of json to a callback url in my project. And i need to update this response in my database. Here is my code :
the response array will be similar as follows :
{"req_id":"809ff62f-74a9-45a5-9cb5-5e60763289af","status":"0" ,"comment":"OK"}
my callback url redirects to following function in my controller
public function templateCallback() {
$json = file_get_contents('php://input');
$json = urldecode($json);
$obj = json_decode($json, TRUE);
$reqID = $obj->req_id;
$status = $obj->status;
print_r($obj);
$this->db->where('TemplateRequestID', $reqID);
$this->db->set('TemplateApproved', $status);
$this->db->update('templatemaster_tbl');
}
But its never get updated. What is wrong in my code ? I'm not good in json. So i'm not sure is this the correct way to fetch and decode json array in php. Someone please help me.
To test this i have created a view in my project and send this same array through an ajax function like :
var base_url = '<?php echo base_url()?>';
$('#test').click(function() {
var val = $('#testvalue').text();
$.ajax({
type: 'post',
url: base_url + 'API/templateCallback',
data: {
val
},
success: function (response) { console.log(response);
}
});
});
and try to print both $json and $obj in controller function.
$json displays a string like : val=%7B%22req_id%22%3A%228b3eef97-330a-4271-8450-0676fbac8885%22%2C%22status%22%3A%220%22%2C%22comment%22%3A%22OK%22%7D
and $obj displays nothing
If your $json contains encoded value (%7B%22req_id%22%3A%228b3eef97-330a-4271-8450-0676fbac8885%22%2C%22status%22%3A%220%22%2C%22comment%22%3A%22OK%22%7D) you should decode it first with urldecode.
So proper code would be:
...
$jsonEncoded = file_get_contents('php://input');
$json = urldecode($jsonEncoded);
$obj = json_decode($json, TRUE);
...

Angularjs $http.post, passing array to PHP

I am using a service to update a DB table.
myApp.factory('createGal', function ($http, $q)
{
return {
createGal: function ()
{
var deferred = $q.defer();
var newGalleryArray = {};
newGalleryArray.galleryName = 'New Image Gallery';
newGalleryArray.client = 245;
$http.post('/beta/images/create', {newGalleryArray: newGalleryArray}).success(function(data)
{
console.log(data);
deferred.resolve(data);
});
return deferred.promise;
}
};
});
PHP
public function create()
{
print_r($_POST);
}
The array is returning empty. Am i passing the array incorrectly?
Chrome Dev
Thanks
It's been a while since I've used PHP, but doesn't $_POST just contain request paramaters? $http.post sends data through a JSON payload, not request parameters. So, you'll need to use something like json_decode

send datas to php with ajax - Internal Server Error(500)

i try to send my datas to php with ajax but there's strange mistake.
this is my ajax script,
function deleteData2()
{
var artistIds = new Array();
$(".p16 input:checked").each(function(){
artistIds.push($(this).attr('id'));
});
$.post('/json/crewonly/deleteDataAjax2',
{ json: JSON.stringify({'artistIds': artistIds}) },
function(response){
alert(response);
});
}
i think this works correctly but in php side, i face 500 internal server error(500).
public function deleteDataAjax2() {
$json = $_POST['json'];
$data = json_decode($json);
$artistIds = $data['artistIds'];
$this->sendJSONResponse($artistIds);
}
Above code is my php. For example, when i try to send $data to ajax,
i print my ids in json mode:
However, when i try to send $artistIds to ajax side, i gives 500 error why?
Selam :)
Right should be:
public function deleteDataAjax2() {
$json = $_POST['json'];
$data = json_decode($json, true);
$artistIds = $data['artistIds'];
$this->sendJSONResponse($artistIds);
}
look at json_decode(). If you wanna use this as an array, you have to set the second parameter to true, otherwise use $data->{'artistIds'}; :)
try something like this and see if you get a response.
$.getJSON('/json/crewonly/deleteDataAjax2',
{ 'artistIds' : artistIds },
function(response){
alert(response);
});
public function deleteDataAjax2() {
$json = $_REQUEST['artistIds'];
$data = json_decode($json);
var_dump($data);die(null);
}

Categories