getJSON doesn't work on the server but does locally - javascript

I am using jQuery for a cascading check box, but the getJSON command dosen't work on the server (locally it works fine). It couldn't find the data.json file (see error debug).
Part of the script:
<script type="text/javascript" src="scripts/jquery-1.7.2.js"></script>
<script>
$(function() {
$("#json-one").change(function() {
var $dropdown = $(this);
$.getJSON("data.json?callback=?", function(data) {
var key = $dropdown.val();
var vals = [];
switch(key) {
case 'BR9':
vals = data.BR9.split(",");
break;
case 'base':
vals = ['Please choose from above'];
}
var $jsontwo = $("#json-two");
$jsontwo.empty();
$.each(vals, function(index, value) {
$jsontwo.append("<option>" + value + "</option>");
});
});
});
});
</script>
Error from firebug:
GET http://______my url site ____/data.json 404 NOT FOUND x 25ms
If I change the line
$.getJSON("data.json", function(data) ...
to
$.getJSON("data.json?callback=?", function(data) ...
it doesn't work either.
Can anyone help me?

Have you tried giving the full path to you json file?
$.getJSON("http://www.mywebsite.com/folder/data.json?callback=?", function(data) {});

Is the page you are making JSON call from and the page you are making the call to are on the same domain ? JSON doesn't support cross domain calls and you would need to use JSONP.

Related

How to access json data in console after using $.getJSON()

I'm have trouble accessing json data within the console. If for instance I wanted to type in courses[0].name or courses.length, I get the error "courses is not defined". I'm definitely missing something here but I'm unsure how to go about it. The list is generating just fine on the DOM, but I want want to access specific parts within the array.
$(document).ready(function () {
var showData = $('#show-data');
$.getJSON('../undergraduate/ug.json', function (data) {
console.log(data);
var courses = data.courses.map(function (course) {
return course.code + ': ' + course.name;
});
if (courses.length) {
var content = '<li>' + courses.join('</li><li>') + '</li>';
var list = $('<ul />').html(content);
showData.append(list);
}
});
});
<body>
Get JSON data
<div id="show-data"></div>
</body>
The json data also seems to be appearing fine initially on load within the console log:
Any help would be very appreciated. Thanks in advance!

AngularJS issue with getting external JSON

Okay so I am new to AngularJS, and am trying to get data from an external API. The end result of this is basically going to help me understand angularjs, using external data, some more as well as getting some stats for Call Of Duty Ghosts for my account or others that I search for.
I know that $http.jsonp is the way to go, but the API doesn't really support it as well as CORS... I have accounted for that. I have been able to use jquery to test to make sure I can do it, but am unable to figure it out with AngularJS.
One issue I am having using whateverorigin and anyorigin from https://stackoverflow.com/a/7910570/1888585 and https://stackoverflow.com/a/6104416/1888585 is that I am getting http error 500 (Internal server error)
Without them I am getting an error regarding the json I am getting (which is valid json, checked with json linter) -> 'Uncaught SyntaxError: Unexpected token : '
So here is what I have:
<!DOCTYPE html>
<html ng-app="myApp">
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body ng-controller="GhostsCtrl">
<div id="text">
Data from site: {{getGhostData()}}
Data from site: {{info}}
</div>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.15/angular.js"></script>
<script>
var myApp = angular.module('myApp', []);
var ucdid = "3f0feb1229202d84b125bab79f7af503ce62057d499ecc0c";
var network = "xbl";
var url = "api.codcp.com/user_stats?ucdid="+ucdid+"&network="+network;
var wrapURL = "http://anyorigin.com/get?url="+url+"&callback=?";
var wrapURL4 = 'http://whateverorigin.org/get?url='+url+"&callback=?";
//-----------
myApp.service('dataService', function($http) {
console.log("in service!!");
this.getData = function() {
console.log("http fn");
resp = "test";
// from here i get the syntax error
$http.jsonp("http://"+url+"&callback=JSON_CALLBACK")
.success(function(data) {
console.log("Data gotten");
console.log(data.contents.user);
resp = "Success";
}).error(function(data ) {
console.log("error");
resp = "error";
});
return resp;
}
});
myApp.controller('GhostsCtrl', function($scope, $http, dataService){
$scope.info = null;
$scope.info = dataService.getData();
$scope.getGhostData = function() {
// from here I get the 500 error
delete $http.defaults.headers.common['X-Requested-With'];
$http.jsonp(wrapURL4).success(function(data) {
console.log("success: "+data.contents);
$scope.info = data.contents.user;
}).error(function(data) {
console.log("error: " + data);
});
}
});
</script>
</body>
</html>
And for my jquery code that works just fine:
$.getJSON('http://anyorigin.com/dev/get?url=api.codcp.com/user_stats%3Fucdid%3D3f0feb1229202d84b125bab79f7af503ce62057d499ecc0c%26network%3Dxbl&callback=?', function(data){
$.each(data.contents.user, function(val, idx) {
$("#text span").append(val+" ");
})
console.log(data.contents.user);
});
The json that comes back is as follows:
{"user":{"profile":{"ucdid":"3f0feb1229202d84b125bab79f7af503ce62057d499ecc0c","gamertag":"xNF6xVENGE","network":"xbl","image":"http://avatar.xboxlive.com/avatar/xNF6xVENGE/avatarpic-l.png","kdr":1.109316019930545,"winr":2.7632311977715878,"kill":14694,"deaths":13246,"wins":992,"losses":359,"hoursPlayed":147.32049180327868,"currentStreak":0,"preferredWeapon":"weapon.iw6_arx160"},"squadMember":{"gamertag":"Erskine","xp":1031872,"background":20,"patchbacking":0,"patch":"patch_590","level":57,"nextLevelXp":1070000,"nextLevel":58,"prevLevel":56,"prevLevelXp":1030000,"progress":0.0468,"prestige":6},"careerHistory":{"blackops2prestige":3,"mw3prestige":6,"nextreadblackops2":1405837382,"nextreadmw3":1405841587,"playedblackops2":true,"playedmw3":true},"accounts":["xbl","ucd"],"clan":{"teamId":34018,"name":"xATFWx","memberCount":24,"tag":"ATFW","motto":"Search & destroy ","mottoBg":22,"motd":"","stats":null,"entitlements":268435448,"cxp":1991990,"kdr":1.5,"winp":74,"chat_token":"a2236f048c2a5ab71473b6765909a7f88b8716782dff8fd7b1f9df43b4b2c00ad60ba1e1a47cbea0153f590b89b698de9b91e240a8427fae4a9d8d48ea10d4fe941ab40f62acca0497e3b9c39967621abb9d6c2863ac1935d4fc193b44e2bb19","clanLevel":25,"progress":1,"nextLevelXp":1991990,"cxpNeeded":0,"nextLevel":25,"membership":0,"invited":null}}}
If there is a way I can either call jquery from angularjs easily, or avoid either error I get would be great.
I created a fiddle to figure out what your problem may be and found out that your return statement was getting fired before parsing the data in the service. I have modified the service in order to return a callback and it will work fine.
Since I cannot mock your server request here is sample fiddle and code snippet
myApp.service('dataService', function($http) {
console.log("in service!!");
return {
getData: function(callback) {
console.log("http fn");
resp = "test";
// from here i get the syntax error
var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts?callback=JSON_CALLBACK";
$http.jsonp(url)
.success(function(data){
console.log(data.found);
resp="success";
callback(resp);
});
}
}
});
Looks like there are 2 reasons the anyorigin URL is not working.
The URL parameter needs to be properly encoded.
The callback should be JSON_CALLBACK instead of ?
Try this...
var ucdid = "3f0feb1229202d84b125bab79f7af503ce62057d499ecc0c";
var network = "xbl";
var url = "api.codcp.com/user_stats?ucdid="+ucdid+"&network="+network;
var wrapURL = "http://anyorigin.com/get?url=" + encodeURIComponent(url) +"&callback=JSON_CALLBACK";
This should build this URL which properly returns a JSONP response that can be consumed by angular:
http://anyorigin.com/get/?url=api.codcp.com%2Fuser_stats%3Fucdid%3D3f0feb1229202d84b125bab79f7af503ce62057d499ecc0c%26network%3Dxbl&callback=JSON_CALLBACK
See this Fiddle: Live Demo
The jQuery's $.getJSON() is not a jsonp, so if you are able to retrieve the data by $.getJSON(), you could also do it with a normal $http.get() (of course with the use of anyorigin.com).
It seems the api.codcp.com doesn't support JSONP, it response with a normal JSON regardless of a callback=? exists in a url or not.
Fix this for starters, as it is just mixing single and double quote strings in concatenation:
var wrapURL4 = 'http://whateverorigin.org/get?url='+url+"&callback=?";
By the way watch out. He is out there to get you !
Motto:
Search & destroy
and he's armed!
If you have not figured out the jsonp callback in angularjs! here is something that helped me:
$http.jsonp("http://anywebsite.com/?json=get_recent_post&callback=JSON_CALLBACK")
I hope you find this helpful.
jv

Code is giving error, "ReferenceError: CryptoJS is not defined" , while I have included required .js references, what's the reason?

Here is my code, I have included following .js files, onpage load it is giving error "ReferenceError: CryptoJS is not defined" why does it give that error when already js references are added. I am making a sharepoint-2013 app using office 365.
<script type="text/javascript" src="../Scripts/sha1.js"></script>
<script type="text/javascript" src="../Scripts/hmac-sha1.js"></script>
'use strict';
var context = SP.ClientContext.get_current();
var user = context.get_web().get_currentUser();
(function () {
// This code runs when the DOM is ready and creates a context object which is
// needed to use the SharePoint object model
$(document).ready(function ()
{
getUserName();
$("#button1").click(function()
{
paraupdate();
});
});
// This function prepares, loads, and then executes a SharePoint query to get
// the current users information
function paraupdate()
{
var str=""+$("#textbox1").val();
alert(""+str);
var message = str+"json539ff0f815ca697c681fe01d32ba52e3";
var secret = "<my private key>";
var crypto = CryptoJS.HmacSHA1(message, secret).toString();
alert("crypto answer is " + crypto);
var siteurl="http://pnrbuddy.com/api/station_by_code/code/"+str+"/format/json/pbapikey/539ff0f815ca697c681fe01d32ba52e3/pbapisign/"+crypto;
$.ajax({
url: siteurl,
type: "GET",
dataType: 'json',
success: function (data) {
alert("IN Success");
alert(""+data.station_by_code);
},
error: function (error) {
alert("IN Error");
alert(JSON.stringify(error));
}
});
}
function getUserName()
{
context.load(user);
context.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFail);
}
// This function is executed if the above call is successful
// It replaces the contents of the 'message' element with the user name
function onGetUserNameSuccess()
{
$("#label1").html("Enter Station Code : ");
$("#button1").val("CLICK");
}
// This function is executed if the above call fails
function onGetUserNameFail(sender, args) {
alert('Failed to get user name. Error:' + args.get_message());
}
})();
include core-min.js before sha256.js
There are one of two forms for fixing this:
1: Manual Load, i have more success with this pattern:
$.getScript(scriptbase + "SP.Runtime.js",
function () {
$.getScript(scriptbase + "SP.js", execOperation);
}
);
Example:
$.getScript("~hostUrl/_layouts/15/SP.RequestExecutor.js", getListDataREST);
2: Script on Demand:
SP.SOD.executeFunc('sp.userprofiles.js', 'SP.ClientContext', loadUserData);
This SharepointExchange posting, gives the usual JSOM implementation for most AppParts: Jquery is not firing on Page load SharePoint 2013
Error solved I added online references instead,
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js"></script>
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/hmac-sha1.js"></script>
Maybe is too late, but:
var CryptoJS = require('crypto-js');
var hash = CryptoJS.HmacSHA256("Message", "secret");
var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
console.log(hashInBase64); // qnR8UCqJggD55PohusaBNviGoOJ67HC6Btry4qXLVZc=
Works fine in node.js.

Google custom search - manual load/execute from url params

Getting some odd behavior from google custom search that I can't seem to suss out. Maybe someone has a clue.
I'm putting together a Magento site, which has its own internal search engine - but is limited to product only. I want to implement google custom search results on the search results page as well. I figure I should be able to simply execute a search based on the query vars in the url (to return all the non-product content), as such:
<section style="min-height:600px">
<div style="background-color:#DFDFDF; min-height:800px; width:100%;">
<div id="cse">Loading</div>
</div>
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
$(document).ready( function(){
console.log('search initiated');
var t = window.setTimeout( function(){ customSearch(); }, 5000 );
});
function customSearch(){
var q = urlParams()['q'];
if (q != undefined && q != ""){
console.log('q : %s', q); //outputs successfully
google.load('search', '1');
google.setOnLoadCallback(function () {
var customSearchControl = new google.search.CustomSearchControl(MY CUSTOM ID KEY);
var cseDrawOptions = new google.search.DrawOptions();
cseDrawOptions.setAutoComplete(true); //unknown if this is required...
customSearchControl.draw('cse',cseDrawOptions);
customSearchControl.execute(q);
}, true);
}
}
function urlParams(){
var vars = [];
var hash;
var index = window.location.href.indexOf('?');
if( index != -1 ){
var hashes = window.location.href.slice(index + 1).split('&');
for(var i = 0; i < hashes.length; i++){
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1].replace(/\+/g, " ");
}
}
return vars;
}
//]>
</script>
</section>
I'll note that I've pulled all other content out of the logic (but its implementation in magento is identical).
So the behavior goes like this: page loads fine (I'm delaying the google search with a timeout for testing purposes ). Assuming there is a query var in the url the console traces out as expected. Then the page just gets wiped out, with no content back from google. "Wiped out"... meaning all elements on teh page disappear, or are getting overwritten by a new page that google loads. As if the search control isn't creating an iframe - its just replacing the page with a <body>-less html page.
I've ready a number of articles on the subject, and gone over the API - this code looks like it should work. But clearly isn't.
What am I missing?
Cheers -
UPDATE
Continued messing around with this has revealed that for whatever reason :
google.load('search', '1');
google.google.setOnLoadCallback( console.log('loaded') )
Was the cause of the replaced page issue. The responded page, however contained links to the search module that google is hosting. And if I manually linked those files (forgoing a google.load) then I could run a search as expected:
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script src="http://www.google.com/uds/?file=search&v=1" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
... search logic
Then I found an alternate syntax on the google developers page that seemed to work as expected:
$(document).ready( function(){
google.load("search", "1", {"callback" : customSearch});
});
function customSearch(){
var q = urlParams()['q'];
if (q != undefined && q != ""){
var cseControl = new google.search.CustomSearchControl('MY CUSTOM KEY');
var cseDrawOptions = new google.search.DrawOptions();
cseDrawOptions.enableSearchResultsOnly()
cseControl.draw('cse', cseDrawOptions);
cseControl.execute(q);
}
}
Which works as expected. Only real problem at this point is the host of
Unsafe JavaScript attempt to access frame with URL http://mydomain from frame with URL http://www.google/cse?...
That now gets thrown.
I don't know how the two different versions of load syntax changes anything... but it seemed to of. Whatever the case, I'm unclear as to how to resolve these cross domain errors.
Thoughts would be great.
Nothin huh?
Well - I've basically worked out a good solution, using an alternate method that I think will be more flexible in the long run. Using googles RESTful API and simple jquery .ajax call, I can obtain good, controllable results with no cross-domain errors:
<div id="cse">Loading</div>
<script>
//https://developers.google.com/custom-search/v1/getting_started
//https://developers.google.com/custom-search/v1/using_rest#query-params
//https://developers.google.com/custom-search/v1/cse/list
var _url = "https://www.googleapis.com/customsearch/v1";
var _key = 'AIzaSy... your api key here';
var _cx = '001809... your engine id';
var _q = urlParams()['q']; //query param
jQuery(document).ready(function() {
$j.ajax({
url : _url,
type : 'GET',
dataType : 'jsonp',
data :{
key : _key,
cx : _cx,
q :_q
},
success : function(data, textStatus, jqXHR){ responseHandler(data); },
error : function(jqXHR, textStatus, errorThrown){ console.log('error: %s'), errorThrown},
beforeSend : function(){ console.log('sending request')},
crossDomain : true
});
});
function responseHandler( response, status) {
console.log(response);
var cse = $j('#cse'); // render vars as needed...
for (var i = 0; i < response.items.length; i++) {
var item = response.items[i];
cse.append( "<br>" + item.htmlTitle);
}
}
function urlParams(){
var vars = [];
var hash;
var index = window.location.href.indexOf('?');
if( index != -1 ){
var hashes = window.location.href.slice(index + 1).split('&');
for(var i = 0; i < hashes.length; i++){
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
}
return vars;
}
</script>
And you can too;D
Cheers

Get Vimeo thumbnail for video using jQuery

I've found similar questions but none of the answers show clearly and easily how to get a thumbnail for a vimeo video using jQuery and JSON. If anyone can help that would be great, here is what I've got but it shows nothing at the moment.
var vimeoVideoID = '17631561';
var videoCallback = 'showThumb';
$.getJSON('http://www.vimeo.com/api/v2/video/' + vimeoVideoID + '.json?callback=' + videoCallback,
function(data){
$(".thumbs").attr('src',data[0].thumbnail_large);
});
Thanks in advance.
I believe you're having the "same origin policy" issue. You should consider writing a server side script using something like "file_get_contents" or "fopen", enabling you to grab the data from vimeo, translate it to json, and output to your javascript with a nice ajax call.
If you would like to avoid using a server-side script you may use the data type JSONP.
var vimeoVideoID = '17631561';
$.getJSON('https://www.vimeo.com/api/v2/video/' + vimeoVideoID + '.json?callback=?', {format: "json"}, function(data) {
$(".thumbs").attr('src', data[0].thumbnail_large);
});
Notice the URL is a bit different from how you are using it. The callback which you defined as a var is unnecessary. You're attaching the getJSON to a function directly, so you'll call the 'callback' in the url '?'. This informs the getJSON function to pass the successful data return to the supplied function.
You can test my code here. Hope it helps!
With the updated API, it would be...
$.getJSON('https://vimeo.com/api/oembed.json?url=https://vimeo.com/' + id, {format: "json"}, function(data) {
$(".thumbs").attr('src', data.thumbnail_url)
});
You can use this function which supports all types of Vimeo links & sizes:
function get_vimeo_thumbnail(url, size, callback)
{
var result;
if(result = url.match(/vimeo\.com.*[\\\/](\d+)/))
{
var video_id = result.pop();
if(size == 'small'){
var video_link = encodeURIComponent("https://vimeo.com/" + video_id + "?width=480&height=360");
$.getJSON('https://vimeo.com/api/oembed.json?url=' + video_link, function(data) {
if(data && data.thumbnail_url){
if (typeof(callback) !== 'undefined') {
callback(data.thumbnail_url);
}
}
});
}
else
{
$.getJSON('http://vimeo.com/api/v2/video/' + video_id + '.json', function(data) {
if(data){
if (typeof(callback) !== 'undefined') {
var thumbnail_src = data[0].thumbnail_large;
if(thumbnail_src){
callback(thumbnail_src);
}
}
}
});
}
}
}
To use it:
// Available sizes: large, small
get_vimeo_thumbnail('https://vimeo.com/475772381', 'large' function(url){
alert(url)
})
Please check out this page; Vimeo has a new method call oEmbed as Vimeo is now pushing it's new oEmbed technology.
The method above, will fail on IE (no thumbs will be shown).

Categories

Resources