Get request within page - html

I've been looking around, but I'm not quite sure what to search for...
I want to have a webpage send a Get request to a python script when you first open the page, maybe with the option to refresh it with a button. Is there a way to send a request ("script.py?var=test") and display the results within the page?
What I tried to use earlier: (didn't work..)
Am I doing something stupid? I don't know anything about JavaScript
<p>Highscores:</p>
<p id='scores'>text</p>
<input type='button' onclick='changeText()' value='Change Text'/>
<script type="text/javascript">
function changeText(){
var request = new XMLHttpRequest();
request.open("GET", "../../cgi-bin/highScore.py?scoreMethod=load&game=ulama", true)
request.onreadystatechange = function(){
var done = 4, ok = 200;
if (request.readyState == done && requeset.status == ok){
document.getElementById('scores').innerHTML = request.responseText;
}
};
request.send();
}
</script>
Also, should I have the python script return a full page with the header and all? or just the relevant section?

Use a Jquery call in this case to clean up your code a little bit.
Also in this case you should use a post because of the nature of your 'beast' :)
function changeText(){
$.ajax({
method : "POST",
URL : "../../cgi-bin/highScore.py",
data : {
"scoreMethod" : "load",
"game" : "ulama"
},
success : function(data) {
$("#scores").html(data);
}
});
}
I'd also look into JSON and jquery being returned as its probaly going to be easier in the long term (Though ive never played with python.

why not using jquery for doing this?
$('#scores').load('../../cgi-bin/highScore.py?scoreMethod=load&game=ulama', function(responseText, textStatus) {
alert(textStatus);//check here whether textStatus equals 'success' or something else (maybe an error)
});

Related

Use JSON after caching through AJAX

I'm new in coding and currently creating a website that supports English and Russian languages. I want to change between them with no page reload, so I decided to use AJAX to achieve it and store information in JSON. I have a checkbox that changing my langString between EN and RU depending on checkbox state.
var langStr = "en";
$('#langsw').click(function(){
if($(this).prop("checked") == true){
console.log("Checkbox is checked.");
langStr = "ru";
}
else if($(this).prop("checked") == false){
console.log("Checkbox is unchecked.");
langStr = "en";
}
});
And this is jquery code to perform AJAX part
$.ajax({
type:'GET',
dataType:'json',
url: langStr+".json",
cache:true,
success: function(data){
$('#meet').append(data.title);
$('#meet').append(data.hr);
$('#meet').append(data.subtitle);
},
error: function(data){
console.log("there is an error")
}
});
My JSON is
{
"title":"<h1 style=\"color:white; font-size: 42pt\">Name</h1>",
"hr":"<hr style=\"width:60%\">",
"subtitle":"<h1 style=\"color:#dbdbdb; font-weight:100\">Interactive resume</h1>"
}
and the second one is the same in Russian.
Now the question: I want to cache both JSONs and then use one of them depending on the state of the checkbox, but I don't know how to do so. If you have any ideas relating to other ways of achieving this I will be very happy to read them.
P.s English is my 2 language so forgive the mistakes.
You can save the information in localstorage (altough there is a limit of how much you can save there).
You can use this formula to save raw json into localstorage
localStorage.setItem('language-ru', data);
To get what is in localstorage you would use
const ru = localstorage.getItem('language-ru')
So you can check, if user has the right language in his localstorage and if there is nothing, you can download it with that ajax call.
You can read more about localstorage here: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

Delay ajax GET function helps in this case?

I am using the following to save the html of a certain website in a string
function loadajax(dname) {
$.ajaxSetup({async: false});
$.get('https://www.example/?param=param1', function(response) {
var logfile = response;
//alert(logfile);
});
}
The problem is that in the html code there are some codes like {{sample}} which seems that there a not loaded yet when the Ajax call is getting the code. When I perform the operations manually I can clearly see HTML code instead of the " {{ }}'s ".
I have already tried {async: false}...

HTML5 offline JSON doesn't work

I have a small HTML5 (using jQuery mobile) web app that caches its files to use them offline, however some parts don't seem to work once it's offline.
The files are cached OK (I can see them in the web inspector) but when I try to visit a page that uses jQuery to load a JSON file it doesn't load.
I tried creating an empty function to load the JSON files (when the index page is loaded) to see if that would help but it doesn't seem to make a difference.
Here's the function that doesn't want to work offline.
My question is: should it work offline or am I missing something?
// events page listing start
function listEvents(data){
$.getJSON('/files/events.json', {type: "json"},function (data) {
var output = '';
for (i in data)
{
var headline = data[i].headline;
var excerpt = data[i].rawtext;
output += '<div id="eventsList">';
output += '<h3>'+headline+'</h3>';
output += '<p>'+ excerpt +'<p>';
output += '</div>';
}
$("#eventsPageList").html(output).trigger("create");
});
}
I'm not really sure, if i'm right about this. But i think an ajax request will always fail when you are offline. It won't use the locally cached file. What you should try is, to cache the data in localStorage. When the ajax request fails, fallback to localStorage.
OK here's a version which seems to work, I read the json file and place it in localstorage then use the localstorage in the listEvents function.
When the page loads I call this function to add the json to localstorage
function cacheJson(data){
$.getJSON('/files/events.json',
{type: "json", cache: true},function (data) {
localStorage['events'] = JSON.stringify(data); });
}
Then this function to output the json (from localstorage) to the page, with an if else incase the localstorage doesn't contain the json.
function listEvents(data){
if (localStorage.getItem("events") === null) {
var output = '';
output += 'Sorry we have an error';
$("#eventsPageList").html(output).trigger("create");
}
else {
data = JSON.parse(localStorage['events']);
var output = '';
for (i in data)
{
var headline = data[i].headline;
var excerpt = data[i].rawtext;
output += '<div id="eventsList">';
output += '<h3>'+headline+'</h3>';
output += '<p>'+ excerpt +'<p>';
output += '</div>';
}
$("#eventsPageList").html(output).trigger("create");
}
}
It seems to work ok but am I missing something that could cause issues?
Is there a more efficient way of doing this?

how to communicate between a options page and background page of chrome extension

I face a problem. Through message passing I transferred DOM data from content script to background page. What i would like to know is how you can establish a communication channel between Options page and background page. The API chrome.extension.getBackgroundPage() is not useful. Nor is traditional message passing through sendRequest and addlistener working . How do i transfer this data from background page to the options page? Could someone provide a tested snippet to explain?
this is what i have been trying .
In my contentscript.js
<script>
var selected_Text ="";
window.addEventListener("dblclick",function(event){
selected_Text = String(window.getSelection());
chrome.extension.sendRequest({greeting: "maprender",name:selected_Text}, function(response) {
alert("reached here")
console.log(response.farewell);
});
//i am to then load options.html on DOM like this
var Div = document.createElement("iframe");
Div.setAttribute('src', chrome.extension.getURL('options.html'));
Div.setAttribute("style","width:130px;height:80px;position:absolute;left:10px;");
Div.setAttribute("id","xyz");
document.body.appendChild(Div);
</script>
I retreive the selected_Text at background.html like this
<script>
var Addr_details={
place:null
};
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
if (request.greeting == "maprender")
{
alert("reached here sendin resp"+request.name);
Addr_details.place = request.name;
sendResponse({farewell: "goodbye"});
}
else
sendResponse({}); // snub them.
});
</script>
Now to access the value of this text at the options page options.html i tried 2 methods
One was to use chrome.extension.getBackgroundPage() like this:
<script>
function init(){
var bkg = chrome.extension.getBackgroundPage();
alert("the selected text is "+bkg.Addr_details.place);
}
</script>
init is onload of options.html .This does not give me the value . infact it just terminates at initialization of chrome.extension.backgroundPage.
Another approach i tried was to create a similar request(like the one already present at contentscript.js) from contentscript.js with a different greeting and add a listener to it at options.html .That doesnt seem to work either at the receiver side(options page) because i get the callback at the contentscript after the request.I am surely doing something wrong , amnt I ?Please help.
It makes sense for the second approach not work. Options.html is not "alive" all of the time, only when the options page is up. Hence, it cannot listen to requests from the content script.
That's exactly what "background" is for.
As for the first approach (using getBackgroundPage()), I never used this method myself, but it seems to bring back only the DOM of the background page, and therefore you cannot access the variables in the background js.
Your best shot should be to send a request from the options page to the background page, asking for this value, e.g.:
Content script:
chrome.extension.sendRequest({greeting: "retrieveAddr"}, function(response) {
// do something with response.addr...
});
Background page:
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
switch (request.greeting) {
case "maprender"):
alert("reached here sendin resp"+request.name);
Addr_details.place = request.name;
sendResponse({farewell: "goodbye"});
break;
case "retrieveAddr":
sendResponse({addr: Addr_details});
default:
sendResponse({}); // snub them.
});
});
Another, easier but hackier solution is to use localStorage to pass info between the options and background pages, as they both share the same one.

Not able to parse JSON file in JavaScript

I am using JavaScript to Parse the JSON file. But I am not able understand the error I am getting. Could anybody please help me on this topic.
**My Code:
Html file:
<title>JSON Parser</title>
<script type="text/javascript">
function webGLStart() {
var request = new XMLHttpRequest();
request.open("GET","test.json");
var my_JSON_object = JSON.parse(request.responseText);
alert (my_JSON_object.result[0]);
}
</script>
</head>
<body onload="webGLStart();">
</body>
</html>
test.json File:
{"result": [0,1,2,3,4] }
alert in above code does not show anything on the webpage.
It's straight forward with jQuery:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$.getJSON('test.json', function(data) {
$.each(data, function(key, val) {
console.log("key=" + key + " " + "val=" + val);
});
});
For more sample code look here: http://api.jquery.com/jQuery.getJSON/
Your code for making the Ajax request is not correct.
First, var request = new XMLHttpRequest(); will not work incase of IE 5, 6; i.e. you need to make cross-browser object of XMLHttp
Second, request.open("GET","test.json"); does not indicate this request to be asynchronous... i.e. you are missing the third boolean parameter (true / false)
Thirdly, you are not sending the request to the web server using:
request.send(null);
Try following link for Ajax:
http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
Try this link for Parsing JSON using Javascript:
http://json.org/js.html
Hope this helps.
Ajax is asynchronous. You are trying to read the response before it has arrived from the server. Oh, worse than that. You are opening the request but never actually sending it.
You need to use an event handler onreadystate change to run the code once the response has arrived, and you need to send the request to the server before you can get a response. There is a decent guide to using XHR here.