I want to request JSON inside of a WordPress page - javascript

For the last few hours I've been trying to set up this http://code.google.com/apis/books/docs/dynamic-links.html on a WordPress blog. Google's API sends back a JSON response (which is supposed to be "put" into _GBSBookInfo variable). However, that variable never is assigned so my javascript callback function explodes saying the variable doesn't exist. So far, all of my javascript is in the WordPress header.
I tried this outside of WordPress and it works fine.
This is the static page:
<script src="http://books.google.com/books?bibkeys=0307346609&jscmd=viewapi&callback=response_handler">
This is the handler:
function response_handler(data) {
var bookInfo = _GBSBookInfo["0307346609"]; // the var that doesn't exist
document.getElementById("test123").innerHTML = bookInfo.thumbnail_url;
}
Thanks for any help in advance, WordPress has been extremely frustrating by limiting so much! If I'm doing anything stupid please say so, I'm a new javascript programmer.
EDIT:
I've used firebug so far to identify the problem to be: the _GBSBookInfo variable never gets "created" or "exists". I'm not sure how javascript works at this level. Hopefully this helps.
ERRORS:
Error: _GBSBookInfo is not defined
Line: 79

Try replacing _GSBookInfo with data, like so:
function response_handler (data) {
var bookInfo = data["0307346609"];
document.getElementById("test123").innerHTML = bookInfo.thumbnail_url;
}
Based on your post, google returns this:
response_handler({
"0307346609": {
"bib_key":"0307346609",
....
"thumbnail_url":"http://bks2.books.google.com/books?somethumbnailstuff"
}
});
... so the above code should work for you.

Related

Understanding Ajax requests to update page content when SQL Query Response changes

I am writing a page update which works with PHP to read a SQL database the page echo's the contents in a div section 'track_data'. yet it doesn't do this update idk
I have JavaScript script which I dont really fully understand and hopeful someone could explain its principally the check response section I think is failing ? :
in my PHP page :
<script type="text/javascript">
function InitReload() {
new Ajax.PeriodicalUpdater('track_data', 'fetch_sql.php', {
method: 'get', frequency: 60, decay: 1});
}
</script>
Thanks for looking and hopefully someone undersstands this and can put a smile on my face for the second time today :)
Steps to fix
Thanks for the suggestions of syntax errors. I haven't really got very far with this here are the changes you suggested which I have changed but I still think there is something wrong with last function as it doesn't update div section.
Code in JS file
// Start Clock refresh
// uses new new Ajax.PeriodicalUpdater(
// in main fetch file to trigger the auto update of the page.
// Written by Denise Rose
var gUpdateDiv;
var gContentURL;
var gcheckInterval;
var gcheckURL = "";
var gCurrentCheck ="";
_fetchUpdater('track_data','/fetch_sql.php','/fetch_sql.php',8000);
function _fetchUpdater(updateDiv,contentURL,checkURL,checkInterval)
{
gUpdateDiv = updateDiv;
gContentURL = contentURL;
gcheckInterval = checkInterval;
gcheckURL = checkURL;
setTimeout('check();',gCheckInterval);
}
//Called by _fetchUpdater every (n) seconds determins if content should be updated.
function check()
{
new Ajax.Request(gContentUrl,{method:'get', onSuccess:'checkResponse'});
setTimeout('check();',gCheckInterval);
}
// looks for the response and determines if the div should be updated.
function checkResponse(transport)
{
var content = transport.response.Text;
if(gCurrentCheck != content) {
gCurrentCheck = content;
new Ajax.Request(gContentUrl, {method: 'get',onSuccess:function t() {
$(gUpdateDiv).innerHTML = t.responseText; /*t.response.json()*/}
});
}
}
This is the bit I dont understand
function checkResponse(transport)
{
var content = transport.response.Text;
if(gCurrentCheck != content) {
gCurrentCheck = content;
new Ajax.Request(gContentUrl, {method: 'get',onSuccess:function t() {
$(gUpdateDiv).innerHTML = t.response.json();/*t.responseText;*/}
});
}
}
Method and Issues
What is transport here and what is t? if it stores the contents of the body text from the second in gCurrentCheck and compares to transport version content then why doesn't it update if its different please which it is if the SQL has created a different page?
I did find this https://api.jquery.com/jquery.ajaxtransport/
First Answer not using Ajax
I was given a neat and JS version as an answer, which is not really what I was looking for. I was hopeful to get the one working with one with Ajax but I appreciate your efforts is very kind. I just really wanted to send a refresh to the div area so that the PHP rebuilt the page from the SQL.
I might have been missing the MIT javascript http://www.prototypejs.org/ lol but I dont think it was.
Just to help:
AJAX stands for Asynchronous JavaScript And XML. In a nutshell, it is the use of the XMLHttpRequest object to communicate with servers. It can send and receive information in various formats, including JSON, XML, HTML, and text files. ... Make requests to the server without reloading the page.
Researching
I found this Update div with the result of an Ajax-call but it did not really explain as the OP was using PHP like me not HTML. The answer was given:
$.ajax({
url: 'http://dowmian.com/xs1/getcam.php',
type: 'GET',
data: {id: <?php echo $cam_id; ?>},
success: function(responseText){
$('#update-div').html(responseText);
},
error: function(responseText){
}
});
I dont think above it answered posters question or mine as ajax is a server based push how is this relevant? as if its PHP driven the needs a refresh at server to refresh the contents not to provide new html. It is this refresh I am not interested in to re-copy PHP code elsewhere in JS as its already in my PHP. Does that make more sense?
Update
I did find a bracket missing and a set of single quotes inserted by editor. Which I have updated above but there was no significant change.
Cheers Nicolas . I am still hopeful that someone knows about Ajax as it sits underneath these technologies. I have a server side PHP file that I was hoping to use AJAX to pull just the PHP from the section it was pointing to an gUpdateDiv . As its derived from the server and created on the fly from SQL. I dont see how your answer would help push this data back in to the from the server . The $(gUpdateDiv).innerHTML was supposed to be acted upon not the whole page . What I am unsure of is how a trigger from this can update timer just this $(gUpdateDiv).innerHTML . I am also not aware if a server based refresh would do this or if the transport id provided from the file would be able to deliver just that . I think I am missing something a vital part that I dont have or have grasped yet. The reason there is two timers is effectively it checks the same file at a different point in time as its created by PHP it might be different from the first if it is i.e. the SQL data has changed, I want this to update this $(gUpdateDiv).innerHTML with the data which it compared it to the second 'Get' in the second request. It sounds, simple in practice but have got stuck comparing two versions and insuring second version gets used .
Further update placing an alert in the Javascript file did not pop up like it does here https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_alert however the same alert in the initiating PHP worked fine and created the alert. called the same function from the main PHP nd the alert occurred so the JavaScript is running next visit F12 on the page to see if there is any warnings or errors. Ok after adding JQuery which I thought I had added this started working however It is not doing what i Expected it to do. As the contained both text and graphics created by PHP I expected this all to be updated The graphics are not the text is any ideas? .
Further to the image problems I placed an extra line to update the image however I used this too in PHP
<script type="text/javascript">
//initpage() ;
function updateArtworkDisplay() {
document.querySelector('#np_track_artwork').src = 'images/nowplaying_artwork_2.png?' + new Date().getTime();
}
</Script>
But it didnt work to update the image in php?
<div id='outer_img'><img id='#np_track_artwork' src='/images/nowplaying_artwork_2.png' alt='Playing track artwork' width='200' height='200'></div>
in js change
/ looks for the response and determines if the div should be updated.
function checkResponse(transport)
{
var content = transport.response.Text;
if(gCurrentCheck != content) {
gCurrentCheck = content;
new Ajax.Request(gContentUrl, {method: 'get',onSuccess:function t() {
$(gUpdateDiv).innerHTML = t.responseText; /*t.response.json()*/}
});
updateArtworkDisplay(); // fire up the redraw in php file.
}
}
Nearly there it does almost what it needs to apart from the redraw which is not happening
// Start Clock refresh
// uses new new Ajax.PeriodicalUpdater(
// in main fetch file to trigger the auto update of the page.
// Written by Denise Rose
var gUpdateDiv="";
var gContentURL="";
var gcheckInterval=0;
var gcheckURL = "";
var gCurrentCheck ="";
_fetchUpdater('track_data','/fetch_sql.php','/fetch_sql.php',8000);
function _fetchUpdater(updateDiv,contentURL,checkURL,checkInterval)
{
gUpdateDiv = updateDiv;
gContentURL = contentURL;
gcheckInterval = checkInterval;
gCheckURL = checkURL;
setTimeout('check();',gcheckInterval);
}
//Called by _fetchUpdater every (n) seconds determins if content should be updated.
function check()
{
new Ajax.Request(gCheckURL,{method:'get', onSuccess:'CheckResponse()'});
setTimeout('check();',gcheckInterval);
}
// looks for the response and determines if the div should be updated.
function checkResponse(transport)
{
var content = transport.response.Text;
if(gCurrentCheck != content) {
gCurrentCheck = content;
new Ajax.Request(gContentUrl, {method: 'get',onSuccess:function t() {
$(gUpdateDiv).innerHTML = t.responseText; /*t.response.json()*/}
});
$time = new Date().getTime();
new Ajax.Request('outer_img', {method: 'get',onSuccess:function s() {
$('outer_img').innerHTML = "<img id='#np_track_artwork' src='/images/nowplaying_artwork_2.png?t='"+$time+" alt='Playing track artwork' width='200' height='200'>"}
});
}
}
GIVEN UP WITH THIS PLEASE DELETE MY PERSONAL INFORMATION AND POSTSript-fetch-async-await/

Update a variable dynamically in flask

I m working with flask and need to make a python variable appear on a HTML page & update it in real time without the need to refresh . i have searched but couldn't do it. To find a solution the simple way i have created in the python script a time variable that should be updated in the page dynamically.Here is my code:
<script>
$SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
(function(){
$.getJSON(
$SCRIPT_ROOT+"/get_data",
function(data) {
$("#testt").text(data.time);
}
setInterval(arguments.callee, 1000);
);
});
</script>
<span id="testt">?</span>
import datetime
from flask.app import Flask
from flask.json import jsonify
app=Flask(__name__)
#app.route('/get_data', methods=['GET'])
def get_data():
return jsonify(time=str(datetime.datetime.now().time()))
if __name__=="__main__":
app.run(debug = True, host='0.0.0.0')
EDIT: In my solution the time only updates when i refresh the page . want it to update in real time.
You don't specify what's your problem exactly ("doesn't work" doesn't really help) so this can be a wild-guess answer at best.
First point, you define an anonymous function but never call it, so the chances it ever gets executed are strictly equal to zero. If you want that function to be executed when your dom's ready (which is the sane thing to do since it references an element of the dom that is defined after the function, you can use $(document).ready(yourfunc), ie:
$(document).ready(function(){
$.getJSON(
$SCRIPT_ROOT+"/get_data",
function(data) {
$("#testt").text(data.time);
}
setInterval(arguments.callee, 1000);
);
});
Also you certainly don't want to call window.setInterval() from the function that itself (which would then be called again an again each time the function is called), so it should rather be something like:
$(document).ready(function(){
function _update_time() {
$.getJSON(
$SCRIPT_ROOT+"/get_data",
function(data) {
$("#testt").text(data.time);
});
}
// do a first call at load time
_update_time();
// then repeat it every second
window.setInterval(_update_time, 1000);
);
});
Also, I'm not a Jinja2 expert (since it's Flask and from the look of it I assume Jinja2 templating), but this:
$SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
seems uncorrect to me.
First, you want $SCRIPT_ROOT to be a string, so you have to quote it:
$SCRIPT_ROOT = "{{ request.script_root|tojson|safe }}";
Then I don't see the point of the tojson and safe filters here - safe tells the template engine to not html-escape your variable but an url seldom contains html markup, and jsonifying a simple string doesn't make sense to me.
Once again it's wild-guess at best and possibly completely wrong. If you want better answers you will have to do your homework and post some more informations, including:
the rendered html (well the relevant part that is)
any error message in your browser's inspector window / debug toolbar / however it's called in your browser.
You can update your page dinamically using a websocket.
There is a project named Socket.Io which is implemented by Flask to work with websockets.
You can read the documentation here : https://flask-socketio.readthedocs.io/en/latest/ and watch a quick example to understand the concepts here : https://www.youtube.com/watch?v=RdSrkkrj3l4

How to define an undefined return value from C# code behind, JS / JQuery

This is a follow up using the code from my previous question:
Why wont js read text box values
My code behind methods are already displayed in that post.
My script works fine with the code behind but when I am trying to retrieve the return value I am getting a return value of "undefined".
The JS code is simple:
var answer = PageMethods.saveCat(CategoryName, ParentID, CategoryID, CatChk);
window.alert(answer);
I have also tried:
windows.alert(String(answer));
but I keep getting an undefined value. I have searched around but have only been able to find solutions using a drawn out $.ajax syntax and was wondering is there a simple way to grab the string value returned by my web method similar to the code I am trying to get to work instead of writing 10 - 15 lines of code?
Thanks for the help.
Thanks to Karthik Ganesan's comment I was able to get on the right track using this link: mindfiresolutions.com/Using-PageMethods-in-ASPNET-2467.php
My resulting code was:
PageMethods.saveCat(CategoryName, ParentID, CategoryID, CatChk, onSuccess, onFailure);
function onSuccess(result)
{
alert(result);
}
function onFailure(result)
{
alert("There was an error saving the category.");
}
I am posting this hoping it helps out other newbies to JS.

post request returns ok but no data and function not working

Ok, I've been putting together a website for the las couple of weeks.
I got everything working before moving on to next phase. Made a lot of changes but none to the functions that I'm talking about.
basically I have a code:
var grabbedItems = [];
function grab(){
$.post(questions.php, {"grab":"grab"}, function(data){
grabbedItems = data;
console.log(grabbeditems);
}, "json");
}
The function gets called on page load. The problem is that network tab says 200 ok for questions.php, but console.log() doesn't even log anything. I can't think what i've done wrong. i haven't even changed the page that the function is on. What could be the problem, apache says no errors network says 200 ok. But functions are not working. I don't think there is anything wrong with my JQuery file, that returns 200 ok aswell.
Any help would be appreciated.
The problem was with the data in one of the mysql fields. I used a £ sign. for some reason the JSOn didn't like it. Maybe I should look into the coding of the database entries.

Execute javascript inside the target of an Ajax Call Drag and Drop Shopping Cart without Server language

Well i wanna create an Ajax Drag and Drop Shopping cart using only javascript and ajax. Currently i'm using the example in this page as a stepping stone. Right now it's only with local jquery and it works fine but i want to make the cart work with ajax calls. Note that i do not want to use a server side language( like php, rubby, asp etc), only html and javascript.
My initial thought was that at the $(".basket").droppable i should add an ajax call to another html page containing the "server logic" in javascript, execute in that file all the necessary steps( like reading the get variables (product name, product id and quantity), set a cookie and then return an ok response back. When the server got the "ok" response it should "reload" the cart div with the updated info stored inside the cookie.
If this was with php i would know how to do it. The problem is that as far as i know, you can execute javascript once it reaches the DOM, but how can you execute that js from inside the page that isbeing called upon ? ( thanks to Amadan for the correction)
I've thought about loading the script using $.getScript( "ajax/test.js", function( data, textStatus, jqxhr ).. but the problem with that is that the url GET variables i want to pass to the "server script" do not exist in that page.
I havent implemented all the functionality yet as i am stuck in how to first achieve javascript execution inside an ajax target page.
Below is a very basic form of my logic so far
// read GET variables
var product = getQueryVariable("product");
var id = getQueryVariable("id");
var quantity= getQueryVariable("quantity");
//To DO
//--- here eill go all the logic regarding cookie handling
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
alert('Query Variable ' + variable + ' not found');
}
Any help regarding this matter will be appreciated.
Note: Logic in simple words:
1)have an html page with products+cart
2)Have an "addtocart.html" with the "Cart Server Logic"( being the target of the ajax call when an item is dropped into the product.)
If you have some other idea on this, please enlighten me :)
thanks in advance
Foot Note-1:
if i try loading the scipt using
$("#response").load("ajax/addtocart.html?"+ $.param({
product: product,
id: id,
quantity:quantity
})
);
i get the alert about not being able to find the url parameters( something that i thing is normal as because the content is being loaded into the initial page, from which the request is started, there are no get parameters in the url in the first place)
The problem is that as far as i know, you cannot execute javascript contained in the target of an ajax call, as that page never reaches the browser interpreter.
This is either incorrect or misleading. The browser will execute any JavaScript that enters DOM. Thus, you can use $.load to load content and execute code at the same time. Alternately, you can use hacked JSONP to both execute code and also provide content as a JSON document.
EDIT: Yes, you can't get to the AJAX parameters from JavaScript. Why do you want to? Do you have a good reason for it, or is it an XY problem?
The way I'd do it is this:
$('#response').load(url, data, function() {
onAddedToCart(product, id, quantity);
});
and wrap your JS code in your HTML into the onAddedToCart function.
Depending on what exactly you're doing, it could be simplified even further, but this should be enough to cover your use case.

Categories

Resources