laravel handle json child array - php

For my project I try to create an ajax call and handle the data.
My Ajax call:
$.ajax({
type: 'GET',
dataType: "json",
url: ****,
data: {****},
success: function(data){
console.log(data.rooms);
$('.pagination').html(data.paginate);
},
error: function(){
alert('failure');
}
});
On the server with laravel I create a response with:
return response()->json(['rooms' => $rooms->toJson() , 'paginate' => $bathrooms->render()]);
In my ajax call the json response looks like (Edit this is the original json):
{"rooms": "{\"total\":3,\"per_page\":9,\"current_page\":1,\"last_page\":1,\"next_page_url\":null,\"prev_page_url\":null,\"from\":1,\"to\":3,\"data\":[{\"id\":237,\"name\":\"Modern met allure\",\"description\":\"Badkamer blablabla\",\"collection_id\":187,\"style_id\":7,\"created_at\":\"-0001-11-30 00:00:00\",\"updated_at\":\"-0001-11-30 00:00:00\"},{\"id\":243,\"name\":\"TIjdloze charme\",\"description\":\"Tijdloze charme\",\"collection_id\":187,\"style_id\":2,\"created_at\":\"-0001-11-30 00:00:00\",\"updated_at\":\"-0001-11-30 00:00:00\"},{\"id\":245,\"name\":\"Staande badkraan Bollicine\",\"description\":\"blablabla\n\",\"collection_id\":199,\"style_id\":7,\"created_at\":\"-0001-11-30 00:00:00\",\"updated_at\":\"-0001-11-30 00:00:00\"}]}","paginate": ""}
Now I want to loop all the object in data so First I tried:
console.log(data.rooms);
this gave me the first part i wanted (only the rooms not the something_else, next I tried to get only the data part by
console.log(data.rooms.data);
But then the result is
undefined
How should I access/loop through the data (subpart of rooms).

I think the problem that you have two data here. One is variable name and second is key name.
Try to use either:
console.log(data.rooms["data"]);
Or choose another name for success argument:
success: function(roomsdata){
console.log(roomsdata.rooms);
$('.pagination').html(roomsdata.paginate);
},
UPDATE: on seeing how you generate json on server:
return response()
->json([
'rooms' => $rooms->toJson() ,
'paginate' => $bathrooms->render()
]);
You're doing double json encoding: first encoding $rooms to json with toJson() and then encoding json-string to json again with json(). Remove toJson() call, leave only json().

Related

CakePHP 3 : Cannot get JSON data from controller

I'm trying to return a query made in a controller to the view file so I can use that data in my form. But I am unable to successfully return the data without errors. I know the function is working because it returns the right data but has an error.
Here is my CustomersController fill function which is running the sql query.
public function fill(){
$layout = 'ajax';
$this->autoRender = false;
if ($this->request->is('post')) {
$id = $this->request->data['id'];
$query = $this->Customers->find()
->where([
'id' => $id
])->first();
echo json_encode($query);
}
}
and here is my blah.ctp which is the view file.
<?php use Cake\Routing\Router; ?>
<?= $this->Form->create(Null, ['type' => 'POST']) ?>
<?php
echo $this->Form->input('customer_id', ['options' => $customers, 'empty' => true,'id'=>'customers']);
?>
<?= $this->Form->end() ?>
<script>
document.getElementById('customers').addEventListener('change',function(){
var id = this.value;
var csrfToken = $('[name=_csrfToken]').val();
$.ajax({
type: "POST",
url: '<?php echo Router::url(array("controller" => "Customers", "action" => "fill")); ?>',
data: {'id' : id},
beforeSend: function(xhr){
xhr.setRequestHeader('X-CSRF-Token', csrfToken);
},
success: function(data){
alert(data);
}
});
});
</script>
Currently this is what happens when I select a customer in my drop down box which triggers the script in the view.
As you can see it returns the array of data I need but also has the error cannot emit headers. I have tried solving this error following other questions on stack overflow but can't solve it.
I've tried using $this->set instead of echo json_encode but it always returns nothing. I'm not sure what other way to do this.
First of all, If you're selecting a single record by a unique ID, you can call
->get($id) on the table object directly, instead of building a query chain with ->find().
CakePHP 3.x should automatically handle converting your view to JSON by using the RequestHandlerComponent. Typically, you must enable it if your scaffolding or installation didn't.
1) Enable request handler component. (If not already enabled) https://book.cakephp.org/3.0/en/controllers/components/request-handling.html
2) Remove the echo json_encode($query) line; you should not echo anything as this will break the request/response cycle. This is the cause of your error.
Instead, you should serialize your data to the view. Assuming you have the fetched data in $data: $this->set(compact('data')). Then, make sure you add $this->set('_serialize', ['data']) (again, assuming the data is stored in variable name 'data').
3) Reference this doc for information on how you can request the json. You can use a file extension (.json, .xml).
Also, make sure you add the 'Accept: application/json' header to your request.(https://book.cakephp.org/3.0/en/development/routing.html#Cake\Routing\Router::extensions).
I apologize for the fuzzy response. There are many ways to achieve this with CakePHP3. Please see this doc page for more information: https://book.cakephp.org/3.0/en/views/json-and-xml-views.html

Send JSON Object to PHP on AJAX Success

In my Controller I've have an array $data whose var dump is as follows:
array
'urls' =>
array
0 =>
array
'link_id' => string '1' (length=1)
'link_name' => string 'http://www.nytimes.com' (length=22)
'words' =>
array
0 =>
array
'keyword_id' => string '1' (length=1)
'keyword' => string 'republican' (length=10)
Array Structure:
$ data will have urls and words only but they can have multiple values. Both will not have the same cardinality.
Then I encode it as echo json_encode($data); in displayData and send this to ajax. displayData needs no POST data. The ajax request made in the View is as follows:
$.ajax({
url:"http://localhost/codeigniter/SiteController3/displayData",
success: function(response){
alert(response);
$("#user_data").html(response);
},
dataType:"json"
})
I want to access the response in my 'View' so that I can
perform json_decode($response, true) and get the associative array.
There is a chunk of code which renders this data in tabular format by
looping on the array. And before this code I want to get the
associative array.
I tried using $.getJSON instead of $.ajax but no solution. Also
tried $.each function, but on alert only getting undefined. Did
JSON.stringify which on alert displayed the JSON but not able to
send it to PHP code.
EDIT:
#fragmentedreality's answer
The content-type inconsistency is solved using the answer. But how can I access the response received on success of AJAX in html body of my View which has a chunk of PHP code for displaying data in tabular format ?
Solution:
Check my answer below.
Add
header('content-type: application/json');
to your controller (before the echo) to set the correct mime-type for you application's response.
Finally I dropped the JSON approach. I added the following line in displayData method of the Controller:
$this->load->view('data_processing', $data);
The data_processing.php is a new View that generates the HTML table I wanted to display. The response of this View is loaded in my original View by the following AJAX request:
$.ajax
({
url: "http://localhost/codeigniter/SiteController3/displayData",
}).done(function(data)
{
console.log(data);
$('#user_data').html(data);
}

$this->data empty after performing an ajax call

I am implementing a function populatig a select box using data from another select box.
//views/users/ajax.ctp
$.ajax({
url: url,
type: "GET",
dataType: "html",
data:"arr=" + result,
success: function(data){
document.getElementById(child).innerHTML = data;
}
});
As you can see from the code above the data passed by the call should be accessible in the getSectors() function under the data variable:
//controllers/users_controller.php
function getSectors() {
$this->set('data', $this->data);
$this->render('/users/ajax_data');
}
In the corresponding view I try to see the content of the data passed:
//views/users/ajax_data.ctp
<?php var_dump($data); ?>
The $data is null.
Debugging that in Firebug shows that the call is invoked properly (status 200 ok) and that the XMLHttpRequest contains parameters and values.
Do you have any suggestions what could be possibly wrong?
In order for Cake to populate the $this->data variable, the data being send needs to follow the format data[Model][field], or at least be part of the data[..] array. If it's plainly named arr, Cake won't put it in the $this->data variable.

Sending an array to a function in codeigniter

I have the following codes which sends an array to the function /chat in codeigniter
$(document).ready(function () {
$('#submit').live('click', function (eve) {
eve.preventDefault();
$.ajax({
url: "http://localhost/fq/index.php/splash/chat/",
type: 'JSON',
data: a,
success: function (html) {
alert(html);
}
});
});
Let us assume that array a contains names of people only. ( John, James, Smith)
I want to be able to retrieve the all the values from the array in the function chat.
How can it be done?
Edit:
I need to retrieve the values from the JSON encoded array in this function (codeigniter)
public function chat()
{
//code to retrieve values
$this->load->view('chat');
}
data: a,
should
data: $('form').serialize(), // 'form' may need to replace by your form selector
But if you want to send only an array like ['John', 'James', 'Smith']... then yours is just fine.
And use dataType: 'json' as configuration if you're expecting Object as response or dataType: 'html' for Html response.
Setting dataType will release you from extra parsing effort.
You should do it via JSON, by changing
type: POST
into
type: JSON
Take a look at: http://api.jquery.com/jQuery.getJSON/
Also I agree with thecodeparadox above, it's simply better practice

MYSQL data + PHP to FLOTgraphing

im quite new to mysql and flot graphing, but i get the general idea.
This is my scenario:
I receive data from a device, in which i put into mysql database.
am i wrong in saying that the new data will replace the existing data in the database?
i then need to plot that on a graph, how do i get(store) the old values so i can put in the data in this line?
$(function () {
var d4 = [[36,37],[50,51],null,[23,24],[18,17]];
$.plot($("#placeholder"), [d4]);
});
if not, i'll only be getting the current data... and that doesnt give me a line.. it'll give me datapoints haha
Thanks for your help!
First, you'll want to set the stage for a graph that you can recreate dynamically. To do so, grab your container then fire off an ajax call to the script that wraps up your data. Within the ajax success call, catch the script's results within a function and send it off to a method such as resetGraph that will reset the graph according to the new information found within the database.
var dataview = $("#placeholder");
$.ajax({
url: "index.php",
data: "stuff&junk&things",
method: 'GET',
dataType: 'json',
success: function(msg){
resetGraph(msg);
}
});
function resetGraph( data ){
plot = $.plot(dataview, data.data, {
points: { show: true, radius: 5 },
xaxis: { ticks: data.ticks, tickSize: 7 },
yaxis: {labelHeight: 2}
});
}
Your script should be populating arrays with the necessary information then json_encoding it before sending it back to Jquery. For example,
echo json_encode(
array(
"data" => array(
array("data" => array(1,2,3))
),
"ticks" => array(2, "two")
)
);

Categories