javascript - Getting a JSON array - javascript

So I have a stock website that I want to be able to obtain the JSON information from either Google's API or Yahoo's API website. I am currently just testing so that is why I used a replacement function for my console log to print it onto a text box for my testing atm. I can not seem to get this to work correctly, I have looked on other pure JS script, but I am currently stump, I have read past posts, but they're very similar in answers, and I have tried implementing.
It works with a fully JSON string, with just {}, where I can just access the inner elements. However, even accessing it, what I believe to be the correct way, it does not seem to work. And I tried with other API with a different method and it worked fine.... Anyone can explain? And I also tried using $.getJSON
$.get("http://d.yimg.com/aq/autoc?query=y&region=US&lang=en-US", function(data) {
var dropDownHTML;
var stock = data.ResultSet.Result;
for (var i = 0, len = stock.length ;i<len;i++){
dropDownHTML += '<option value="' + stock[i].symbol + '">' + stock[i].name + '</option>';
}
document.getElementById("options").innerHTML = dropDownHTML;
});
</script>
</div>

The problem is simply that the website you are scraping from has specifically blocked HTTP requests. You'll need to connect with HTTPS instead:
https://mysafeinfo.com/api/data?list=englishmonarchs&format=json
Also, you're returning a large array of objects from your scrape -- you'd need to loop through, and log the contents of each object individually:
for (var i = 0; i < data.length; i++) {
console.log(data);
}
I've created a Fiddle showing a working scrape here.
Hope this helps! :)

Related

Listen for new urls of ads posted to site

for (var i = 3848450; i > 3848400; i--) {
var query = {
url: 'http://classifieds.rennug.com/classifieds/viewad.cgi?adindex=' + i,
type: 'html',
selector: 'tr',
extract: 'text'
}
,
uriQuery = encodeURIComponent(JSON.stringify(query)),
request = 'http://127.0.0.1:8888//?q=' +
uriQuery + '&callback=?';
jQuery.getJSON(request, function (data) {
var datastring = data[0].results;
var datasplit = datastring.toString().split('Sign');
$('#inner-content').append(datasplit[0]);
});
}
I want to listen for new URLs of ads that are posted without writing some kind of arbitrary code that takes up a lot of memory looping through new URLs, etc. I can do that but it seems redundant and such as my code listed above. Im using noodle.js to get the info from the pages. Now I would like a way to listen for new urls instead of looping through every possible url from a to z. Since I don't know z it's a safe bet I'll be using an if statement but how would one go about incorporating this nth URL without ending up with undefined iterations. Im still learning and find this place has many helpful people. This is simply a fun project I'm doing to learn something new.
If I understand you correcly, you want an external thing to inform your javascript when there's new a URL or JSON data
Unfortunately the web is not built for servers to contact clients, with one exception to my knowleadge: WebSockets
You already seem to have a local server so you meet the requirements plus node ships with them ready for use (also available on the browser). To use noodlejs with websockets you'd have to require the package and set up the WebSocket to send data to your client
Other than pointing you towards that direction, I don't think I can do better than the internet at giving you a tutorial. Hope this helps, Have fun! Also thanks for telling me about noodle, that thing is awesome!

Codeigniter/JSON/AJAX - Can't see array data from URL

I'm trying to display JSON data using jQuery from a Codeigniter controller. I've already created a JSON URL (http://www.tgttest.jeffreyteruel.com/location/locales), and also have the same data on my WAMP server. What I'm having problems is getting the data to display. It works if I take the same JSON data and place it on a .json file, but I'm looking to get it from a Controller/MySql database.
My code is below:
$.getJSON('http://www.tgttest.jeffreyteruel.com/location/locales', function(data) {
var output="<ul>";
for (var i in data.locales) {
output+="<li>" + data.locales[i].location_id + " " + data.locales[i].location_title + "</li>";
}
output+="</ul>";
document.getElementById("placeholder").innerHTML=output;
});
It's been a while since I've dealt with AJAX so my skills are rusty. Any help to get the data from the URL is greatly appreciated.
You need to use CORS or JSONP. Please, read my answer in a similar post:
local AJAX-call to remote site works in Safari but not in other browsers

how to get the +1 count in google plus using any API

I have tried many things but I'm not able to get a proper API which will return me the +1 count in google plus.
I have already tried using :-
Getting Counts for Twitter links, Facebook likes and Google +1 with Jquery and AJAX
Getting Google+ subscription count with jQuery
How do I get the counter of a google plus +1 button?
But none of them is giving me the answer.
Any thoughts....
Thanks :)
i just found out a very useful site to solve our problem. :) Thanks to him!
http://99webtools.com/script-to-get-shared-count.php
You could write your own function using the link you and jgillich mentioned. This would be slightly simplified with jQuery.
Here's a jsfiddle I made as an example. You'll probably have to use something like PHP to fetch from the site if you want to circumvent inter-domain issues. It could look something like this though (ignoring domains):
$('#myInput').keyup(function () {
var url = 'https://plusone.google.com/_/+1/fastbutton?url=' + encodeURIComponent($(this).val());
$.get(url,
function (data) {
var aggregate = $('#aggregateCount', data).html(),
exactMatch = $('script', data).html().match('\\s*c\\s*:\\s*(\\d+)');
$('div').html(exactMatch ? exactMatch[1] + ' (' + aggregate + ')' : aggregate);
}
);
});
Currently, the API does not offer any method to retrieve the +1 count. A workaround would be to fetch it directly from the +1 button like described here (you already linked to it, but I don't think there is another way).
this works for me :
var _url = 'http://mylink.com/';
$.getJSON('http://anyorigin.com/get?callback=?&url=' + encodeURIComponent('https://plusone.google.com/_/+1/fastbutton?url=' + _url)).done(function(data,status,xhr){
console.log($(data.contents).find('#aggregateCount').html());
});
Check out the following for another way to get the Google+ count.
http://share.yandex.ru/gpp.xml?url=http://google.com

Remote json and Javascript

I'm currently developing a web application for the school where I work. We have a program called FROG on one of our dedicated servers. Unfortunately this is very locked down, and you create websites using a a gui. The most coding you can do on it is HTML and javascript.
I want to be able to retrieve information from a remote server which we also own. I cant use ajax due to the cross domain restrictions. However I have come up with a work around.
I have this function call on my remote server within a file called xrequest.js:
loadNotices({[{title: 'this is a test'},{title: 'this is another test'}]});
This is simply a function call with a json object passed as an argument (The argument will ultimately be generated from data retrieved from a database).
On my other restricted server, I have this javacript:
<script type="text/javascript">
function loadNotices(data)
{
alert(data);
}
var url = "http://somedomain.com/tests/xrequest.js";
var script = document.createElement('script');
script.setAttribute('src', url);
document.getElementsByTagName('head')[0].appendChild(script);
</script>
<div id="notices"></div>
What I want to do is loop through each of the titles in the xrequest.js file, and display them as a list.
Im unsure how to loop through the titles.
If you need any more information, please leave a comment. Any help is appriciated.
Many thanks
Phil
To loop over the titles, you first need to remove the curly braces around your array. After, loop through the titles like below:
function loadNotices(arr) {
var title, i = 0;
for (; i < arr.length; i++) {
title = arr[i].title;
}
}​
Also, look into changing:
document.getElementsByTagName('head')[0].appendChild(script);
to
document.head.appendChild(script);
Your implementation look like JSONP call. With Jquery you can make it easy
$.get('url?callback', {<data>}, function(data){
});
with ?callback at the end of url, jquery auto create a random callback function. At your server instead of return normal JSON, you can add wraper callback function around it.
example with php:
$callback = $_GET['callback'];
echo $callback.'('.json_encode(obj).');';
which will become
callback({your return data>});
and your script will receive that.
loadNotices({[{title: 'this is a test'},{title: 'this is another test'}]});
this function call is not correct, do this instead:
loadNotices([{title: 'this is a test'},{title: 'this is another test'}]);
then you can loop through your title like this
for (i = 0; i < titles.length; i++){
alert(titles[i].title);
}

Possible to load data into a javascript file?

I have a fly out javascript menu that is initialized using the onload event. All of the data inside the menu right now is hard coded but needs to be dynamic and will come from my database. Is there a way to build this javascript file with my database values? Is this possible? I'm a total noob to JS so please spell things out for me.
Maybe an example of what I'm thinking will help. This is part of my JQuery file after I have my serialized array. How do I get the array into the menu from here?
if(data.success == 0) {
// error
} else {
// my array that needs to be exported into the JS file.
}
This is the other file that I'm talking about that needs to be built with the data from the database.
function create_menu()
{
document.write(
'<table cellpadding="0" cellspaceing="0" border="0" style="width:98%"><tr>' +
'<td class="td" valign="top">' +
'<h3>Test</h3>' +
'<ul>' +
'<li>afd</li>' +
'<li>fsg</li>' +
'<li>sfg</li>' +
'<li>fsg</li>' +
'</ul>' +
'</td></tr></table>');
}
One option would be to build the JavaScript file dynamically on the server when a request comes in from the browser using one of the various server-side scripting languages. The downside to this method is that that browsers may cache the file and, therefore, may operate with stale data.
The other option is to use a static JavaScript file and use an AJAX call to get the latest menu options and then render them into the page's DOM. This would be better than the first option since you wouldn't have the caching concerns.
The third method is to dynamically generate the markup for the page and not worry about requesting a menu via JavaScript. This is the best option in my book. I wouldn't want to wait for the navigational elements of a page to be requested via JavaScript when it's something simple that should already be part of the page.
You need to use AJAX.
You can load the contents from back-end into a JavaScript array and use that. This is how dynamic data is fetched from the server without a page refresh.
Hope this helps.
JSON is a data format which can be executed using eval(). Create some JSON which represents whatever format you've hard-coded and evaluate it like in Wikipedia's example
This is only okay if you trust the source of the JSON, in this case you're generating it yourself so it should be okay.
example, json_menu.php returns the text:
create_menu( { "menus" : ["afd", "fsg", "sfg", "fsg"] } );
And you execute it like this by evaluating it:
function create_menu(JSONData)
{
var s = '<table cellpadding="0" cellspaceing="0" border="0" style="width:98%"><tr>' +
'<td class="td" valign="top">'
// loop through each one
for(var menu in JSONData.menus)
s = s + '<li>' + menu + '</li>';
s = s + '</ul></td></tr></table>';
// write it out
document.write(s);
}
// this gets called somewhere in your OnLoad
function yourOnLoader()
{
var ajaxRequest = new ajaxObject('http://your-site.com/json_menu.php');
ajaxRequest.callback = function (responseText) { eval(responseText); }
ajaxRequest.update();
}

Categories