I am attempting to access Google Books in order to an ISBN Code to get details of a book, I have a number of problem, which are:
A) I am trying to assemble a script request e.g. with the ISBN code concatenated into the URL. I have not managed to do this successfully - and I don't know why.
B) I then want to update a div in the DOM with this generated script dynamically, such that it will then execute.
C) I am finding it a bit of a puzzle as to the format of the returned data and the argument name of the function call contained in the Google response.
Has anyone else encountered the same problem and can offer guidance re A thru C above.
I enclose JavaScript code below.
$(document).ready(function() {
$('#viewbook-button').live('click', function() {
isbnCode = this.text;
alert("ISBN is : " + isbnCode + " " + this.text + " as well");
alert("Getting JSONP Google Books data");
isbnCode = "0451526538";
JSONPstr = '<' + 'script ' + 'src="' + 'https://www.googleapis.com/books/v1/volumes?q=ISBN' + isbnCode;
JSONPstr = JSONPstr + '&callback=handleJSONPResponse">' + '</script>';
alert("un-Escaped JSONP string" + JSONPstr);
escJSONPstr = escape( escJSONPstr );
alert("Escaped JSONP string");
//divstr = "";
//divstr = divstr + escape(<script src=");
//divstr = divstr + encodeURIComponent(https://www.googleapis.com/books/v1/volumes?q=ISBN);
//divstr = divstr + escape(isbnCode);
//divstr = divstr + encodeURIComponent(&callback=handleJSONPResponse);
//divstr = divstr + escape("></);
//divstr = divstr + escape(script);
//divstr = divstr + escape(>);
$('#jsonp-call').html(escJSONPstr);
// This will cause the handleJSONPResponse function to execute when the script is dynamically loadedinto div.
// The data wrapped in a function call will be returned from the Google Books server.
// This will cause the handleJSONPResponse function to execute below.
}); // end viewbook-button
}); // end document.ready
function handleJSONPResponse(response) {
var tmp = response;
alert(tmp);
};
</script>
</head>
<body>
<h2>Show Details of Books Ordered by a Customer</h2>
Get Customer Details
<br/><br/>
<div id="tablist">Tables will be Listed Here</div>
<br/><br/>
<div id="Google-call">The JSONP generated src= statement will go here and execute</div>
</body>
</html>
EDIT:
Problem solved - thanks everyone.
You're reinventing the wheel: jQuery has built-in JSONP support, so you don't need to faff about implementing it yourself. Use the $.ajax method:
$.ajax({
url: 'https://www.googleapis.com/books/v1/volumes?q=ISBN' + isbnCode,
dataType: 'jsonp',
success: function(response) {
console.log(response); // log the response object to the console
}
});
That should be all you need to do.
Related
I use jQuery ajax to read context on my page dynamicly. But part of DOM is load in javaScript function call by getScript in ajax .done. But just after I load new content I need to get elements by class and use it in next function. Unfortunatly I can't find elements, that I create in javaScript function, and script with that function I call using jQuery getScript.
ok, my code:
$(document).ready(function() {
$('.link').click(function(){
var subpage = $(this).attr('data-subpage');
var src = 'subpages/'+ subpage + '/' + subpage +'.php';
var script = 'subpages/'+ subpage + '/js/' + subpage +'.js';
$.ajax({
url: src,
context: document.body,
dataType: 'html',
success: function(responseText){
$('#text').html(responseText); // responseText has only container <div id="insideText"></div> that I use in one function and load there by html() several divs. One of this div has class 'translate'. I need it in function Translator
}
})
.done(function(){
$.getScript(script); // here I call script where I load several divs to #insideText
Translator($('.active').attr('data-lang')).getTranslation() // part of function have to find all div.translate, but can't find it if they're load in script call in getScript. And this is a problem.
})
})
})
I hope, I explaine my problem quite clear. If not, plaese ask, I'll try again.
There's some way to do that?
//update//
After this script, call by getScript I still have problem with second 'done':
const Presenter = function(){
var presented, show, fullDesc, cont;
presented = [
{
url: 'demo/colorsGame/',
name: 'Graj w kolorki!',
desc: 'Graj w kolorki! Wybierz taki sam kolor, w jakim napisana jest nazwa wylosowanego koloru. Spiesz się, czas ucieka coraz szybciej i szybciej. Uważaj, bo mózg może cię oszukać i uznać za ważniejsze to, co jest napisane, a nie to co widzisz. Zobacz ile punktów jesteś w stanie zdobyć zanim popełnisz trzy błędy. Ćwicz swoją koncentrację.'
},
{
url: 'demo/sampleUserProfile/',
name: 'Sample User Profil',
desc: 'Mała próbka możliwości reactJS. Wkonany z użyciem biblioteki reactJS, menadzera pakietów webpack oraz na środowisku nodeJS przykładowy profil użytkownika. Like-uj i obserwuj do woli, a jeśli chcesz, wypowiedz się pod profilem.'
}
];
show = function(url, desc, name) {
fullDesc =
"<a href ='" + url + "'>" +
"<h1 class='translate'>" + name + "</h1>" +
"</a>" +
"<div>" +
"<p class='translate'>" + desc + "</p>" +
"</div>";
cont =
"<div id='webmin' class='clearfix'>" +
"<div>" +
fullDesc +
"</div>" +
"<div>" +
"<iframe src='" + url + "' scrolling='no'>" +
"ups, twoja przeglądarka nie obsługuje ramek" +
"</iframe>" +
"</div>"+
"</div>";
return cont;
};
return {
show: show,
presented: presented
}
};
display = function(){
var len, url, name, desc;
len = Presenter().presented.length;
for(let i = 0; i <= len; i++){
url = Presenter().presented[i].url;
name = Presenter().presented[i].name;
desc = Presenter().presented[i].desc;
$('#insidetext.apps').append(Presenter().show(url, desc, name));
}
};
display();
Hmm, I'm wondering, if iframe is not a problem here? And don't let script to be done to end?
getScript is just another ajax call and returns an xhr object which exposes done and fail methods. Use those methods to ensure your dom is properly loaded before trying to access it.
$(document).ready(function() {
$('.link').click(function(){
var subpage = $(this).attr('data-subpage');
var src = 'subpages/'+ subpage + '/' + subpage +'.php';
var script = 'subpages/'+ subpage + '/js/' + subpage +'.js';
$.ajax({
url: src,
context: document.body,
dataType: 'html'
})
.done(function(responseText){
$('#text').html(responseText);
$.getScript(script).done(function() {
Translator($('.active').attr('data-lang')).getTranslation() ;
}
})
})
})
Also, you should implement the .fail methods, in case your ajax requests fail.
I am trying to incorporate financial data in my website (just a beginner)
I followed a youtube documentary that used some java script to to the query from a local machine not a server.
the script was supposed to return price daily changes to 4 different shares and display them.
It seemed to work at first, but now i see that it only returns some of the prices (or occasionally none) and when I refresh it may show a different change but never all 4 at the same time?
here is the HTML and Javascript
<script type="text/javascript">
var Base_URL = 'https://query.yahooapis.com/v1/public/yql?q=';
var yql_query = 'select * from yahoo.finance.quote where symbol in ("YHOO","AAPL","GOOG","MSFT")';
var yql_query_str = encodeURI(Base_URL+yql_query);
var query_str_final = yql_query_str + '&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys';
$.getJSON(query_str_final, function(data){ console.log(data);
var changeValue = data.query.results.quote[0].Change;
console.log(changeValue);
document.getElementById("change").innerHTML = " Yahoo = " + changeValue; });
$.getJSON(query_str_final, function(data){ console.log(data);
var changeValue = data.query.results.quote[1].Change;
console.log(changeValue);
document.getElementById("change1").innerHTML = " Apple = " + changeValue; });
$.getJSON(query_str_final, function(data){ console.log(data);
var changeValue = data.query.results.quote[2].Change;
console.log(changeValue);
document.getElementById("change2").innerHTML = " Google = " + changeValue; });
$.getJSON(query_str_final, function(data){ console.log(data);
var changeValue = data.query.results.quote[3].Change;
console.log(changeValue);
document.getElementById("change3").innerHTML = " Microsoft = " + changeValue; });
</script>
any thoughts?
Try something like this where the changeValue ie 1,2,3 etc for each has a slightly different variable name plus the html change is done when the process is complete.
$.getJSON(query_str_final, function(data){ console.log(data);
changeValue1 = data.query.results.quote[1].Change;
console.log(changeValue);
}).done(function(){
document.getElementById("change1").innerHTML = " Apple = " +
changeValue1;});
Note: This makes the changValue1 variable global, which isn't the best but for testing.
I'm trying to get all facebook comments with profile pictures of commentators through fb.api() call. Currently all comments gets outputed i just can't get profile pictures to append to appropriate comment.
In for loop which loops through all comments is another FB.api call which gets the profile pic of user who commented on video and than append them into single comment block. With this code i get profile pictures of all users who commented in every single comment.
What am i doing wrong?? Thank you in advance!
var komentarji_length = response.comments.data.length;
for (var i = 0; i < komentarji_length; i++) {
var user_id = response.comments.data[i].from.id;
FB.api("/" + user_id + "/picture", {
access_token: access_token
}, function (response) {
var profile_pic_link = response.data.url;
$(".comments_profile_pic" + i).append("<img src=" + comments_profile_pic_link + ">");
});
var ime = response.comments.data[i].from.name;
var message = response.comments.data[i].message;
$(".fb_comments").append('<div class="single_comment"><div class="comments_profile_pic' + i + '"></div><div class="name">' + name + '  says:</div><div class="single_message">' + message + '</div></div>');
}
Issue 1: comments_profile_pic_link is not defined, the variable is: profile_pic_link.
But then also the problem will not be solved. When you call "/" + user_id + "/picture" it is redirected to the image url automatically. So you can directly use the image url as: https://graph.facebook.com/{user-id}/picture. No need to make the API call unnecessarily.
Example
Still if you wish to get the proper image url (not required though), use redirect=0 with your call-
FB.api("/" + user_id + "/picture?redirect=0", {
access_token: access_token
}, function (response) {
var profile_pic_link = response.data.url;
$(".comments_profile_pic" + i).append("<img src=" + comments_profile_pic_link + ">");
});
What I am trying to do:
Get location based off of IP (Done)
Use the City and Country code to use openweather's API (Done)
Read the XML into my webpage so that I can display the "Temperature" field.
This is my first venture into using XML in webpages, and I've tried for 3 days now with no success. I have searched google and stackoverflow, and have tried many things so far, including SimpleXMLElement, with no luck.
What I currently have on my page is just a generated link to the XML sheet for your location.
<script language="JavaScript" src="http://j.maxmind.com/app/geoip.js"></script>
<script language="JavaScript">
var country = geoip_country_code();
var city = geoip_city();
document.write('Link text');
</script>
How am I able to display the text from the required field on my page?
Thanks in advance! :)
It might be easier to change the API call to return JSON, in which case you could then use this code, the temps are stored in temp, temp_min and temp_max.
var country = geoip_country_code();
var city = geoip_city();
$.getJSON('http://api.openweathermap.org/data/2.5/weather?q=' + city + ',' + country + '&mode=json&units=metric', function( json ) {
var temp = json.main.temp;
var temp_min = json.main.temp_min;
var temp_max = json.main.temp_max;
document.write( 'Temp: ' + temp + '<br>');
document.write( 'Temp Min: ' + temp_min + '<br>');
document.write( 'Temp Max: ' + temp_max + '<br>');
});
You could use javascript library to convert the xml into a javascript object - one such library is called xml2json, it works as a jQuery plugin: http://www.fyneworks.com/jquery/xml-to-json/
Then you can simply do:
var xmlObject;
$.ajax({
url: url_of_xml,
success: function(data) {
xmlObject = $.xml2json(data);
}
});
Then you just need to place the data on your page. The object in my example is faked, but it gives you the idea:
// put this line in the success callback of your ajax call
// after you create the xmlObject
$('#temp').html(xmlObject.weather.temp);
To display the temperature you get the XML, and read one of the three temperature attributes from the XML returned:
$.get("http://api.openweathermap.org/data/2.5/weather?q=' + city + ',' + country + '&mode=xml&units=metric", function(xml) {
avg = $(xml).find("temperature").attr("value"));
max = $(xml).find("temperature").attr("max"));
min = $(xml).find("temperature").attr("min"));
(using JQuery)
I'm posting ckeditor content via Ajax to php. But getting 4-5 sentence of posted material in my db table. I wonder, Is there any size limitation for ajax post? is there any way to post big text contents via ajax?
My js looks like that
function postViaAjax(autosaveMode) {
var name = $("#name").val();
var title = $("#title").val();
var menu = $("#menu").val();
var parentcheck = $(".parentcheck:checked").val();
var id = $("#id").val();
if (parentcheck == 0) {
var parent = parentcheck;
} else {
var parent = $("#parent").val();
}
var content = CKEDITOR.instances['content'].getData();
var dataString = 'name=' + name + '&title=' + title + '&menu=' + menu + '&parentcheck=' + parentcheck + '&id=' + id + '&parent=' + parent + '&content=' + content;
$.ajax({
type: "POST",
url: "processor/dbadd.php",
data: dataString,
dataType: "json",
success: function (result, status, xResponse) {
var message = result.msg;
var err = result.err;
var now = new Date();
if (message != null) {
if (autosaveMode) {
$('#submit_btn').attr({
'value': 'Yadda saxlanıldı ' + now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds()
});
} else {
$.notifyBar({
cls: "success",
html: message + ' ' + now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds()
});
}
}
if (err != null) {
$.notifyBar({
cls: "error",
html: err
});
}
}
});
};
The HTTP specification doesn't impose a specific size limit for posts. They will usually be limited by either the web server or the programming technology used to process the form submission.
What kind of server do you use?
There isn't any size limitation for POSTs in HTTP.
Maybe you have an & in your content variable. Then everything after that would be stripped after that.
Other than that what type do you use for your data column in the database? Is it, by any chance, something like varchar(1000)? Then anything bigger would also get stripped.
Check what you actually receive on the server end, so you know if you've got a problem with the code or the database.
You have a limitation on the Apache server. Look for LimitRequestBody directive.
This may be helpful:
http://gallery.menalto.com/node/14870
In theory the limits on AJAX requests are the same on all the other requests, so it depends on your web server/app setup. See also Max length of send() data param on XMLHttpRequest Post