Help with passing multidimensional JSON array to jQuery autocomplete via AJAX - javascript

I'm trying to implement a live search on my photos site using jQuery and the autocomplete plugin. Everything works when I specifiy the data locally:
var data = [ {text:'Link A', url:'/page1'}, {text:'Link B', url: '/page2'} ];
However when I move this to PHP, jQuery is unable to parse the results properly. I'm really not sure what's going on here. My current code is below:
<script>
$(document).ready(function(){
var data = '/livesearch';
$("#aut_field").autocomplete(data, {
formatItem: function(item) {
return item.text;
}
}).result(function(event, item) {
location.href = item.url;
});
});
</script>
And my PHP script prints a multidimensional array in the following format:
{"1":{"text":"Google Website","url":"http:\/\/www.google.com"},
"2":{"text":"Yahoo Website","url":"http:\/\/yahoo.com"},}
However when I do alert(item.text) the variable says undefined.
If I do alert(item) I see the entire string as outputted by PHP.
I tried playing around with eval() but I'm not sure where to put it or how to get JS to actually interpret the data. Thanks for your help. Sample code specific to my implementation is appreciated.

The issue is with the php code.
Your job is to mimic the strcuture of the working javascript array. See php's json_encode()

try in your php this pattern:
[
{"text":"Google Website","url":"http:\/\/www.google.com"},
{"text":"Yahoo Website","url":"http:\/\/yahoo.com"}
]

And your PHP script return a multidimensional array/object mix.
If you insist (you blow up your var with several "text:" amd "url;") it shou1ld be:
[[{"text":"Google Website","url":"http:\/\/www.google.com"}],[{"text":"Yahoo Website","url":"http:\/\/yahoo.com"}]]
Better:
var x=[["Google Website","http:\/\/www.google.com"],["Yahoo Website","http:\/\/yahoo.com"]];
If you want to jump to Yahoo Website: var url=x[1][1];
Or:
var x={"Google_Website":"http:\/\/www.google.com","Yahoo_Website":"http:\/\/yahoo.com"};
If you want to jump to Google_Website: var url=x["Google_Website"];
My tip: visit enter link description here

Related

Converting JSON Data to String

Edit: This first paragraph got cut off somehow during posting
I am a retired farmer not a coder. I do dabble with html/js but am very far from competent at either. What I am working on is modifying the html interface for my weather station. It is for my own in house use only. The JSON I am trying to use is hosted by the weather station software on an Raspberry pi on the URL listed a couple paragraphs down.
I will just post what I'm trying to do rather than anything about what I have tried. The following code produces what I want - being able to add a temperature to an html page using the tag "extratemp". It also truncates the sample temp from 69.0 to 69.
The sample data is actually contained in a JSON on the host computer (../api/extra/temp.json). Again, my html page displays the desired "69" using the code below, I just cannot seem to replace the sample data (var str = line) with the live data from the JSON.
$(document).ready(function() {
var str = '{"data":[["Sensor 1","69.0","°F"],["Sensor 2","0.0","°F"],["Sensor 3","0.0","°F"],["Sensor 4","0.0","°F"],["Sensor 5","0.0","°F"],["Sensor 6","0.0","°F"],["Sensor 7","0.0","°F"],["Sensor 8","0.0","°F"],["Sensor 9","0.0","°F"],["Sensor 10","0.0","°F"]]}'
var jsonData = JSON.parse(str);
document.getElementById("extratemp").textContent = Math.floor(jsonData.data[0][1]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="extratemp"></div>
Any help will be greately appreciated.
Thanks
You can use jQuery's getJSON function to download the JSON file & handle it by means a callback function:
$.getJSON( "../api/extra/temp.json", function( data ) { ... });
According with your data, the JSON object is an array of arrays, each item of the main array containig 3 values:
[ ["Sensor 1", "69.0", "°F"], [...], ...]
Once again using jQuery library you can use the $each function to iterate thorugh each item of the main array, then accessing any particular subitem by index (0,1,2).
$.each(data, function( index, item ) {
console.log("Item =>", {item[0], item[1], item[2]} );
});
See: https://api.jquery.com/jquery.getjson/, http://api.jquery.com/jquery.each/

Adding to localStorage with JavaScript and Jade

Having issues with Jade and the way the data is passed to it when it is rendered.
I am trying to save the data which is in [{key1: "val1", key2: "val2"}, ...}];
format but having issues as it shows up as the result below.
Result
key: xyz value:[{"artist":"Lady Gaga",...
This is the code I am working with on the server-side Node.js which is passing it fine ...
res.render('musics', {
title: 'site',
result: JSON.stringify(result)
});
This is the code I am having issues with because of the way I have to call result in jade...
script
function local (arr) {
var i;
i = "#{result}";
localStorage.setItem('xyz', i);
}
console.log('stored');
local();
The quotes around result are messing it up but without them I get an error for unexpected identifier...
Any suggestions or if it might be better to go an ajax route through Backbone(which is what I am using with the client-side) I am willing to, just to put some pointers out - the data is being scraped and through selections of a form post - so the data comes back after the post and is a on time transfer, so if I did an ajax call it would have to include the post and the get, otherwise i am not sure of how to receive it... maybe res.json(result) on the server side, but then the page needs to render somehow... Open to suggestions. Thanks! Ultimately I want it to go into localStorage without the " around everything.
your jade snippet should look like this then:
script!= "(function() {localStorage.setItem('xyz',JSON.stringify(" +result + ");})();"
by using != you tell jade to not escape the following content, and on the clientside you have to stringify again before puting your data to local storage.
As an improvement to #greelgork's answer:
This is for JSON array
script!= "(function() {var items = []; items = JSON.parse(localStorage.getItem('Stored_items')); console.log(JSON.stringify(items)); items.push(" + JSON.stringify(product) + "); localStorage.setItem('Stored_items', JSON.stringify(items)); })();"
Anyways, pushing an item into localStorage needs to be stringified before inserted into localStorage hence, #greelgorke's answer should be modified so:
single item
script!= "(function() {localStorage.setItem('xyz',JSON.stringify(result)); })();"
So the JSON.stringify is outside the string just like all the other javascript code is,
This is what I use in my project and it worx
Credit Push JSON Objects to array in localStorage
if usersList.length
script.
const userList = !{JSON.stringify(usersList)}
localStorage.setItem('xyz',JSON.stringify(userList))
const loader = document.querySelector(".loader");
loader.className +=" hidden";

Codeigniter - sending json to script file

I query the db i my model like so
function graphRate($userid, $courseid){
$query = $this->db->get('tblGraph');
return $query->result();
}
My controller gets data back from my model and I json encode it like so
if($query = $this->rate_model->graphRate($userid, $courseid)){
$data['graph_json'] = json_encode($query);
}
$this->load->view('graph', $data);
And thats returns me a json object like so
[
{"id":"1","title":"myTitle","score":"16","date":"2013-08-02"},
{"id":"2","title":"myTitle2","score":"17","date":"2013-09-02"},
{"id":"3","title":"myTitle3","score":"18","date":"2013-10-02"}
]
In my view graph I'm loading an js file
<script type="text/javascript" src="script.js"></script>
Now I want to use $data that is being sent from my controller to my view, to my external script.js to use as labels and data to feed my chart. But How do I get that Json data to my external script.js so I can use it?
1 more thing about the json data, isn't it possible to get the output of the json data as
{
"obj1":{"id":"1","title":"myTitle","score":"16","date":"2013-08-02"},
"obj2":{"id":"2","title":"myTitle2","score":"17","date":"2013-09-02"},
"obj3":{"id":"3","title":"myTitle3","score":"18","date":"2013-10-02"}
}
The problem isn't a Codeigniter problem, it's a javascript scope/file inclusion/where-do-i-get-my-data-from problem.
I run into this all the time and have used these solutions:
naming my php files with .php extensions and loading them as if they're views.
Just putting the script that needs data from a view IN the view file where it's used
Using an ajax request in my included js file to hit a controller and get json data.
I use #2 most frequently (for things like datatables where I WANT the js code right there next to the table it's referencing.
I use #1 occasionally, but try NOT to do that because it means some .js files are in my webroot/js dir and some are in teh application/views directory, making it confusing for me or anyone else who wants to support this project.
#3 is sometimes necessary...but I like to avoid that approach to minimize the number of requests being made and to try to eliminate totally superfluous requests (which that is).
You need to print the result of the output json string to the html generated file.
But you need to parse the string with some script. I would recommend you: http://api.jquery.com/jQuery.parseJSON/
For the second question. It is possible by doing:
$returnValue = json_encode(
array (
"obj1" => array("id"=>"1","title"=>"myTitle","score"=>"16","date"=>"2013-08-02"),
"obj2" => array("id"=>"2","title"=>"myTitle2","score"=>"17","date"=>"2013-09-02"),
"obj3" => array("id"=>"3","title"=>"myTitle3","score"=>"18","date"=>"2013-10-02"),
)
);
Print the output using PHP like:
echo json_encode($query);
Then from the client-side (where JavaScript resides) load that JSON that you printed using PHP. This can be done easily using JQuery.
Like this:
$.get("test.php", function(data) {
alert("Data Loaded: " + data);
});
You can find more information about this here: http://api.jquery.com/jQuery.get/
Now you'll need to parse this data so that JavaScript can understand what you got as text from the server. For that you can use the JSON.parse method on the "data" object in the aforementioned example. Once parsed, you can use the object like any other object in JavaScript. You can find more information about JSON.parse here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
I hope that helps.

How to get JSON from PHP to JS?

I have really been searching for almost 2 hours and have yet to find a good example on how to pass JSON data from PHP to JS. I have a JSON encoding script in PHP that echoes out a JSON script that looks more or less like this (pseudocode).
{
"1": [
{"id":"2","type":"1","description":"Foo","options:[
{"opt_id":"1","opt_desc":"Bar"},
{"opt_id":"2","opt_desc":"Lorem"}],
{"id":"3","type":"3","description":"Ipsum","options:[
...
"6":
{"id":"14","type":"1","description":"Test","options:[
...
etc
Problem is, how can I get this data with JavaScript? My goal is to make a .js script that generates a poll based on these JSON datas, but I honest to god can't find any examples on how to do this. Guessing it is some something like:
Obj jsonData = new Object();
jsonData = $.getJson('url',data,function()){
enter code here
}
Any links to any good examples or similar would be highly appreciated. And I thought that encoding the data in PHP was the tricky part...
EDIT:
I got this code snippet to work, so I can review my whole JSON data in JS. But now I can't seem to figure out how to get to the inner data. It does print out the stage number (1-6) but I can't figure out how to get the question data, and then again the options data within each question. Do I have to experiment with nested each loops?
$(document).ready(function()
{
$('#show-results').click(function()
{
$.post('JSAAN.php', function(data)
{
var pushedData = jQuery.parseJSON(data);
$.each(pushedData, function(i, serverData)
{
alert(i);
})
})
})
});
The idea here is to get into the question information in the middle level and print out the qusetion description, then based on the question type - loop through the options (if any) to create checkbox/radiobutton-groups before going on to the next question. The first number represents which stage of the multi stage poll I am currently working on. My plan is to divide it into 6 stages by hiding/showing various divs until the last page where the form is submitted through Ajax.
Not sure but I think, you can use
$.getJSON('url', data, function(jsonData) {
// operate on return data (jsonData)
});
now you can access and operate on the PHP json data,
if you're going to use it outside the getJson call you can assign it to a variable
var neededData;
$.getJSON('url', data, function(jsonData) {
neededData = jsonData;
});
Try the jQuery documentation: http://api.jquery.com/jQuery.getJSON/
This example should get you started:
$.getJSON('ajax/test.json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});
This example is based on the JSON structure being;
{
"one": "Singular sensation",
"two": "Beady little eyes",
"three": "Little birds pitch by my doorstep"
}
Do not use echo in PHP. It will print string not JSON.
Use json_encode to pass JSON to javascript.
Use can use each to get the values in JSON at javascript end.
Example
http://www.darian-brown.com/pass-a-php-array-to-javascript-as-json-using-ajax-and-json_encode/
If you are using JQuery there is a really simple solution to your approach as you can see here: http://api.jquery.com/jQuery.getJSON/.
Otherwise I just want you to explain that there is no way to access your JSON directly in JavaScript as you tried in your code above. The main point is, that JavaScript runs on your browser while your PHP script runs on your server. So there must definitely be a communication between them. So you have to request the data from the server over http I would suggest.
HTH

How do implement jQuery autocomplete in Google App Engine with Python?

I found several sources discussing this problem, (this one seems the simplest but it is for PHP). I will be using an existing search form and I created AutocompleteResponse handler to handle the request. I don't understand from the documentation if it is required that the data sent will be in json format or an array of string is ok. I am not sure about what information to send either. I created a new model with search history
class Search(db.Model):
owner = db.UserProperty()
date= db.DateTimeProperty(auto_now_add=True)
query = db.StringListProperty()
and I want to send the relevant query suggestions to autocomplete. Any help to examples whether in documentation or otherwise is welcome. Thanks.
Update
I put this just before the closing </body>
<script>
$('#search_form').autocomplete({
source: "http://ting-1.appspot.com/autocomp",
minLength: 2});
</script>
in my Autocomp handler I put
data = json.dumps("abc, def")
I naively think that data will be passed to jquery autocomplete plug in. But nothing is happenning. What am I doing wrong?
Just tried this and it worked:
data = ['cat','dog','bird', 'wolf']
data = json.dumps(data)
self.response.out.write(data)

Categories