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
Related
I'm trying to post some mailing campaign statistics in a webpage on a website I'm building with Wordpress. I need the statistics to update on their own as data changes, so instead of parsing a JSON string directly I want to use an URL so the data is continually being fetched from the Mailify (mailing service I'm using) server.
I have some Pascal programming experience but I'm new to javascript and I've been struggling a lot with this particular problem. Because I'm getting desperate, I figured I'd try asking for help.
I've figured out how to request the data from the URL (although I forgot how I did it last time and rn I'm not able to get past the pop-up that requests the credentials), and also how to post on the page using JS, which would be something basic. But I can't figure out how to fetch the data from JSON in real time. I've seen so many different examples but they're all a little different and not really similar to this situation.
Some useful data:
API Key: 8RdZ1SkxTeWGlk2T049KOw
Account ID: 5c7650c911ce626a6371c1b5
Mailing campaign ID: TZi4oEiSRDCqciu-vGV98A
JSON URL: https://mailifyapis.com/v1/reports/TZi4oEiSRDCqciu-vGV98A
JSON URL I'm using to try and include the key and ID: https://mailifyapis.com/v1/reports/TZi4oEiSRDCqciu-vGV98A&accountId=5c7650c911ce626a6371c1b5&apiKey=8RdZ1SkxTeWGlk2T049KOw (It's still giving me a pop-up)
This is the Mailify documentation page: http://developers.sarbacane.com/#statistiques (have to translate with Google, they have no translation of their own)
I've tried understanding how curl works but I have to install some stuff and I thought I could get around the problem without it.
Here's what I have tried (I've just been probing the syntax, mostly):
<script>
<p id="demo"></p>
var text = 'https://mailifyapis.com/v1/reports/TZi4oEiSRDCqciu-vGV98A&accountId=%225c7650c911ce626a6371c1b5%22&apiKey=%22w_S31uj2RIGHVENnRbD4xw%22';
var obj = JSON.parse(text);
obj.opens = eval("(" + obj.clicks + ")");
document.getElementById("demo").innerHTML = obj.opens + ", " + obj.clicks();
</script>
I realize it doesn't work like this but that was my last attempt. I can't figure out what I should be doing.
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®ion=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! :)
so i've been looking at how to record and send client-side data to a php server.
i'm not sure of the correct terminologies, but i think that using an ajax call to send a post to the php server is the most elegant way to solve this problem.
so i decided to implement this data exchange:
$("#"+activityInfo.ID).click(function(){
window.open(activityInfo.URL+"userId="+$("#userid").val()+"&activityId="+activityID+"&classId="+classID);
classid = classID;
activityid = activityID;
$("body").append("class: " + classid);
$("body").append("id: " + activityid);
$.post('http://chemcollective.org/chemvlab/php/updateProgress.php', { 'cid':classid , 'aid':activityid } );}); //i think this is the important line that sends the data
and the corresponding php file (updateProgress.php)
$class_id = $_POST['cid']; //receives the data
$activity_id = $_POST['aid'];
i'm not sure why this is the case, but class_id and activity_id variables always return an empty value.
i understand somewhat that the client-browser is on a page that is preloaded by information from a php server. but there were posts that said this is a possible way to communicate back to the php server with information from the client. i'm not really sure what is going on b/c at this point i don't really know what questions to ask.
one of the example explanations that i had been following:
Ajax passing data to php script
thanks for the help.
i've also played around with start_session() and storing/loading session variables as a way to transfer data information. this works but only for php <-> php communication. it does not for saving javascript variables, so i couldn't really use $_SESSION = ..... in my javascript code.
you need to get the cid and aid outside of the single-qouts while using $.post! try this:
$.post('http://chemcollective.org/chemvlab/php/updateProgress.php', { cid:classid , aid:activityid } );
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
I am trying to get the alexa pagerank via http://data.alexa.com/data?cli=10&data=snbamz&url= + weburl
Here is the url for getting the alexa rank of facebook.com
http://data.alexa.com/data?cli=10&data=snbamz&url=http://www.facebook.com
If you copy the link above and paste in your browser you can see that it is in xml format.
I am jusing getJSON to retrieve the alexa rank from other domain. I am also using yql api. you can see the url in the first parameter below.
var url = "http://data.alexa.com/data?cli=10&data=snbamz&url="+ inputtedURL;
OR to be specific
var url = "http://data.alexa.com/data?cli=10&data=snbamz&url=www.facebook.com";
Below is my getjsON
$.getJSON("http://query.yahooapis.com/v1/public/yql?"+
"q=select%20*%20from%20html%20where%20url%3D%22"+
encodeURIComponent(url)+
"%22&format=xml'&callback=?",
function(data){
}
);
How will I get the contents of this http://data.alexa.com/data?cli=10&data=snbamz&url=http://www.facebook.com since this is in xml format. the getJSON returns JSON objects.
Any other suggestions?? I am building an alexa page rank checker using jquery only .
I see I'm a bit late to the party, but I had to solve this today and thought somebody might find it useful: You can use Yahoo Pipes to convert XML data to JSON.
I created an example Pipe that take a 'site' parameter, passes it to Alexa's API, and returns the result. You can simply add '_render=json' to the query and get the results back in JSON. So using jquery...
var pipe = "http://pipes.yahoo.com/pipes/pipe.run?";
pipe += "_id=c43fc0ed13fc8945cf438da90bff0121";
pipe += "&site=" + encodeURIComponent(url);
pipe += "&_render=json&callback=?";
$.getJSON(pipe,
function(data){
}
);
(Feel free to clone the Pipe and do with it as you will.)
Here's an example call to get Alexa stats for StackOverflow in JSON:
http://pipes.yahoo.com/pipes/pipe.run&_id=c43fc0ed13fc8945cf438da90bff0121&_render=json&site=http://stackoverflow.com
The prettified output looks like this:
{"count":1,"value":{
"title":"AlexaData",
"description":"Pipes Output",
"link":"http:\/\/pipes.yahoo.com\/pipes\/pipe.info?_id=c43fc0ed13fc8945cf438da90bff0121",
"pubDate":"Wed, 09 Jan 2013 21:50:25 +0000",
"generator":"http:\/\/pipes.yahoo.com\/pipes\/",
"callback":"",
"items":[{
"AID":"=","HOME":"0","URL":"stackoverflow.com\/","VER":"0.9",
"DMOZ":{
"SITE":{
"BASE":"stackoverflow.com\/",
"DESC":"A language-independent collaboratively edited question and answer site for programmers. Questions and answers displayed by user votes and tags.",
"TITLE":"Stack Overflow",
"CATS":{
"CAT":[
{"CID":"377304","ID":"Top\/Computers\/Programming\/Resources\/Chats_and_Forums","TITLE":"Resources\/Chats and Forums"},
{"CID":"477752","ID":"Top\/Reference\/Ask_an_Expert\/Computers_and_Technology","TITLE":"Ask an Expert\/Computers and Technology"}
]
}
}
},
"SD":{
"POPULARITY":{"SOURCE":"panel","TEXT":"86","URL":"stackoverflow.com\/"},
"REACH":{"RANK":"81"},"RANK":{"DELTA":"-3"},
"COUNTRY":{"CODE":"IN","NAME":"India","RANK":"25"}},
"description":null,
"title":null
}
]}
}