jQuery JSON and PHP Associative arrays arrays issues - php

Hi there I was wondering if somebody could help me?
I have the following code. It retrieves JSON data from a php file. The Json is the following format :
{"Title":"rose","Price":1.25,"Number":15},{"Title":"daisy","Price":0.75,"Number":25},{"Title":"orchid","Price":1.15,"Number":7}
This JSON is created using the following php code:
$shop = array();
$shop = array( array( Title => "rose",
Price => 1.25,
Number => 15
),
array( Title => "daisy",
Price => 0.75,
Number => 25,
),
array( Title => "orchid",
Price => 1.15,
Number => 7
)
);
echo json_encode($shop);
Whenever i try and access the data using obj.Title I get an undefined message.
$.ajax({
type: "GET",
url: "data.php",
success: jsonDo
});
//JSON DATA = {"Title":"rose","Price":1.25,"Number":15},{"Title":"daisy","Price":0.75,"Number":25},{"Title":"orchid","Price":1.15,"Number":7}
function jsonDo(data) {
var obj = jQuery.parseJSON(data);
alert(obj.Title)
}
I was wondering how I can access the keys in the JSON and display the data?
Thanks a million.

var obj = jQuery.parseJSON('{"Title":"rose","Price":"1.25","Number":"15"}');
alert(obj.Title);
This work. Check difference in your code.
OK this is more correct:
var obj = [
{"Title":"rose","Price":"1.25","Number":"15"},
{"Title":"daisy","Price":"0.75","Number":"25"},
{"Title":"orchid","Price":"1.15","Number":"7"}
];
alert(obj[1].Title);

You have to specify that you are expecting a JSON object by informing the dataType: "JSON" parameter to the ajax() function, so you will not have to parse the data.

There seems to be some PHP errors in your code. This could cause php to raise a notice / warning which might break the Json output and cause javascript to raise errors when trying to parse it.
The correct jSon output should have been
[{"Title":"rose","Price":1.25,"Number":15},{"Title":"daisy","Price":0.75,"Number":25},{"Title":"orchid","Price":1.15,"Number":7}]
Since it is in an array, the JS should be:
$.ajax({
type: "GET",
url: "data.php",
success: jsonDo
});
function jsonDo(data) {
var obj = jQuery.parseJSON(data);
alert(obj[0].Title)
}

You should just use jQuery's $.getJSON method:
$.getJSON('data.php',function(data) {
alert(obj.Title);
});

try obj[0]["Title"] or obj[0].Title
dont forget that you have nested a lot of arrays and that yoyu need to access them that way again.

Related

How to store and retrieve materializecss chips?

I have a form where I'm putting the chipsData into a hidden input field called #hiddenTags I'm doing this because I don't want you use an AJAX call because I have a pre-exist form. Below is how I'm putting the chip data into the hidden input.
$("form").on("submit", function() {
var tags = M.Chips.getInstance($('.chips')).chipsData;
var sendTags = JSON.stringify(tags);
$('#hiddenTags').val( sendTags );
});
I'm sending it to the database like this: (PHP)
$this->tags = json_encode( $data['tags'] );
However, saving data like this is raising all sorts of issues. I'm using Twig to display the data.
Below is how I'm trying to display it, however with this I get an error unexpected token & in json
$('.chips').chips();
$('.chips-initial').chips({
data: {{ json }}
});
I have also tried putting the json into a hidden input and then putting it into jquery:
<input id="raw_json" type="hidden" hidden value="{{ user.tags }}">
var json = $('#raw_json').val();
$('.chips').chips();
$('.chips-initial').chips({
data: json
});
However, with this I get and error of Cannot read property 'length' of undefined
Apologies if I'm doing something stupid and/or completely wrong, any help is much appreciated.
So the answer to your problems lies in setting the values when initializing the chips object, along with parsing the JSON data.
From there just keep the text box updated on add or delete of a chip.
var chipsData = JSON.parse($("#Tags").val());
$('.chips-placeholder').chips({
placeholder: 'Enter a tag',
secondaryPlaceholder: '+Tag',
data: chipsData,
onChipAdd: (event, chip) => {
var chipsData = M.Chips.getInstance($('.chips')).chipsData;
var chipsDataJson = JSON.stringify(chipsData);
$("#Tags").val(chipsDataJson);
},
onChipSelect: () => {
},
onChipDelete: () => {
var chipsData = M.Chips.getInstance($('.chips')).chipsData;
var chipsDataJson = JSON.stringify(chipsData);
$("#Tags").val(chipsDataJson);
}
});

laravel handle json child array

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().

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);
}

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