I am writing a JS where I want to make some Ajax calls to get a JSON file from my DB in CouchDB. My code is based on examples I found online, but my lack of experience and knowledge is making it difficult to fix it completely.
My code:
function myFunction(){
var request = $.ajax({
url:'http://admin:pass#localhost:5984/db/_design/view/_view/view',
type:'get',
dataType:'json'
});
request.done (function (data)){
var result;
for (var i in data){
if( data[i] == key){
result.push(data[i]);
}
}
console.log(result);
};}
Problem: It seems like it is not even doing the requested call since when I try to print my array it isn`t doing anything.
The way see it, in the first part where I defined request it should get the JSON file from CouchDB. And, if correct, in the second part where the request is done request.done I give the function how I want the JSON file to be taken care of. To make it clear, my idea is to iterate through the data and to save the values of the "key" in every row in my result-array.
Related
I'm trying to fetch a JS array created by a PHP file and re-use the JS array in a JS script in the page. I have tried many different solutions found on this site but none seems to work but I don't know what the issue is with my script.
I have a PHP file that echoes the following:
[["content11", "content12", "content13", "content14","content15"],
["content21", "content22", "content23", "content24","content25"]]
I'm using a simple Ajax get to retrieve the data:
$.ajax({
type: "GET",
url: myUrlToPhpFile,
dataType: "html",
success : function(data)
{
result = data;
alert (result);
}
});
The alert displays the expected output from the PHP file but if I now try to access the array like result[0], it outputs "[" which is the first character. It looks like JS sees the output as a string rather than an array.
Is there something I should do to make JS understand it's a JS array?
I have seen many solution with JSON arrays but before going into this direction, I'd like to check if there are simple solutions with JS arrays (this would prevent me from rewriting too much code)
Thanks
Laurent
In you php file you need check that your arrays echos with json_encode.
echo json_encode($arr);
And in your javascript file:
$.ajax({
type: "GET",
url: myUrlToPhpFile,
dataType: "html", // json
success : function(data)
{
var res = JSON.parse(html);
alert(html); // show raw data
alert(res); // show parsed JSON
}
});
You can use JSON.parse to format the string back into an array.
JSON.parse(result)[0]
or
var result = JSON.parse(result);
result[0];
#Rho's answer should work fine, but it appears that you're using jQuery for your AJAX call, which gives you a shortcut; you can use $.getJSON instead of $.ajax, and it will read the data as JSON and provide you with the array immediately.
$.getJSON(myUrlToPhpFile, function(result) { ... });
This is really just a short way of writing what you already have, but with a dataType of json instead of html, so you could even do it that way if you prefer. This is all assuming that you're using jQuery of course, but your code was following their API so it seems a good bet that you're either using jQuery or something compatible.
I want to be able to pull data from a google spreadsheet doc every 24hrs and use the values in my html page.
I have managed to get the JSON url for the cell I want to track, but I do not know how to get this JSON object into a javascript variable using the url.
I have searched around and tried using Jquery $.get() and $.getJSON() but I cant seem to get anything to work.
The url for the google spreadsheet data cell JSON is
https://spreadsheets.google.com/feeds/cells/1r56MJc7DVUVSkQ-cYdonqdSGXh5x8nRum4dIGMN89j0/1/public/values/R29C4?alt=json-in-script&callback=importGSS
I know this is probably simple but I am very new to working with JSON/ Javascript and have been struggling to work this out.
Thanks for any help :)
The data being returned is jsonp so you need to specify that in your Ajax request.
function getData() {
return $.ajax({
url: 'https://spreadsheets.google.com/feeds/cells/1r56MJc7DVUVSkQ-cYdonqdSGXh5x8nRum4dIGMN89j0/1/public/values/R29C4?alt=json-in-script&callback=importGSS',
dataType: 'jsonp',
jsonpCallback: 'importGSS'
})
}
And while you can assign the data to, say, a global variable this will only get you so far - the Ajax process is asynchronous and you won't be able to access the data until the process has finished:
var obj;
getData().done(function (data) {
obj = data;
});
// console.log(obj) here will return undefined as the process
// has not yet finished
Much better to grab the data and do something with it:
function doSomethingWithData(data) {
console.log(data);
}
getData().done(function (data) {
doSomethingWithData(data);
});
Or even simpler:
getData().done(doSomethingWithData);
I'm using sailsjs to insert data from GET parameter of the URL (mydomain.com/prod_master/addsupp).
The page is /prod_master/addsupp which is accepting GET parameters to insert in database.
In javascript I need to do loop and insert more than one record
following is the javascript code i'm using:
<script>
for(var i=2;i<(rCount);i++)
{
supplier=tbl.rows[i].cells[3].children[0].value;
del_lead_time=tbl.rows[i].cells[4].children[0].value;
min_qty=tbl.rows[i].cells[5].children[0].value;
window.location="/prod_master/addsupp?supplier="+supplier+"&del_lead_time="+del_lead_time+"&min_qua="+min_qty;
}
</script>
However I can confirm that using my url mydomain.com/prod_master/addsupp?supplier=val&del_lead_time=val2&min_qua=val3 its adding records to database perfectly
but in loop if i use window.location=url then its not working.
Any solution?
Note: if is there any jQuery solution then also let me know.
In loop you can't use window.location=url to call any url and do some task. Because javascript execution will be faster than you think. Once it has replaced URL in window.location, in next loop it will replace same and it will conflict with previous call.
Better approach would be calling that URL using ajax call.
I'm giving you psudo code using jQuery to do GET request.
<script>
for(var i=2;i<(rCount);i++)
{
supplier=tbl.rows[i].cells[3].children[0].value;
del_lead_time=tbl.rows[i].cells[4].children[0].value;
min_qty=tbl.rows[i].cells[5].children[0].value;
urlToCall="/prod_master/addsupp?supplier="+supplier+"&del_lead_time="+del_lead_time+"&min_qua="+min_qty;
$.get(urlToCall, function(response){
console.log(response); //you might want to see returned response
});
}
</script>
I'm new in the scripting and web world and have been trying to work through an issue I've been having. I am reading data from a local JSON file, and have been able to use jQuery.getJSON and jQuery.parseJSON successfully, but I am trying to use the data outside of the getJSON callback function and am having issues. I think it comes down to me not fully understanding the correct way to do this, and that's where I'm looking for your help. Here's my code:
var names = new Array();
$.getJSON('ferries.json', function(data) {
var jsondata = $.parseJSON(JSON.stringify(data));
var length = jsondata.nodes.length;
for (var i = 0; i < length; i++) {
names[i] = String(jsondata.nodes[i].name);
}
});
console.log('Names: ' + names[0]);
The final line returns undefined. If I were to write that line right after the for loop, it would return the desired value. Here's how the JSON file is structured:
{
"nodes":[
{
"name":"John"
},
...
{
"name":"Joe"
}
]
}
Any help would be appreciated - thanks!
Edit: One last thing, it seems that the final line (console.log(...)) executes before the $.getJSON bit, which confuses me as well.
$.getJSON runs asynchronously. The function that you pass to it is a "callback", which means that it gets called when getJSON comes back from doing its thing.
If you want to do something with the JSON data that you get back, you must wait for the callback to execute.
Also, on a side note, $.parseJSON(JSON.stringify(data)) is redundant. The data object is already a perfectly usable object with your data in it, but you're turning that object back into a JSON string and then immediately back into an object. Just use data as is. For more information, check out the jQuery API docs for getJSON.
There are some similar posts on SO about this topic but they are all dealing with search and I am trying to do something different. I have tried to apply some of the logic in answers to other questions here but w/o success. Essentially I just want users to be able to enter a status update ID into a text field, hit a button then display all meta data associated with that tweet. If I leave the callback=? part off of the URL string I get a response back but it's empty, which is obviously due to the security restrictions put in place by the Twitter API.
Here is what I am working with currently:
$.getJSON("http://www.twitter.com/statuses/show/73051651728084992.json?callback=?",
function(Data)
{
if(Data.length)
{
var Content = "";
$.each(Data, function(i, Row)
{
alert("We Have Data");
Content += Row;
});
$("#Result").append(Row);
}
else
alert("No Result for that ID!");
})
Which comes back w/ no data, yet the request does come back w/ a 200 HTTP response. Obviously I am missing something as far as the callback goes, I am just not sure what. Just as a crude proof of concept I was going to output all of the data to the Result div and pretty it up later. Obviously first things first I need to actually have some data to work with!
What am I missing?
Remove the ?callback=? from the url and try again. You are asking Twitter's api to wrap the response in a callback ? which would result in invalid JSON. Also, whenever in doubt, load the url manually in your browser to examine whether the response is correctly formatted.
Also, change to this, since $.getJSON() returns an Object, not a string:
if (Data) {
var Content = "";
..
}