JSON and passing a URL value as a parameter - Chrome Extension - json

Ok, this is my final tango with this. Below I've listed the code. I'm able to get the value of the url and display it on screen for the current (active tab) in Google Chrome. Now all I have to do is pass that value as a parameter in the URL via JSON. My processing file resides on a our remote server - in php. Everything I've done with respect to this has worked to perfection. However, any attempts to pass the current url or any url as one of the parameters - e.g. ?format=json&url=http://something.com&callback=? - results in nothing. I'm not sure if what I'm doing is wrong or if it is even possible. The important thing to note is that all we are looking to do is pass the url to a remote server for storage, processing etc and send back results. I have everything working but I just can't seem to get the url to pass as a parameter.
<html>
<head>
<title>API JSON Test</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script>
window.addEventListener("load", windowLoaded, false);
function windowLoaded() {
chrome.tabs.getSelected(null, function(tab) {
document.getElementById('currentLink').innerHTML = tab.url;
});
}
</script>
<script type="text/javascript">
$(document).ready(function(){
var timeService =
"http://api.ulore.com/api2.php?key=abce&url="+tab.url+"&format=json&callback=?";
$.getJSON(timeService, function(data) {
$('#showdata').html("<p>url_results="+data.post.url+"</p>");
});
});
</script>
<div id="showdata"></div>
</head>
<body>
</body>
</html>
Again, all the JSON works fine when I'm testing other code. Even if I put in a NON-URL value as a parameter for url=..... it throws the appropriate error. However, it will not accept a URL for some reason.
Any feedback will be greatly appreciated.
Thanks,
Ethan-Anthony

Try encoding and decoding the url.
http://www.w3schools.com/tags/ref_urlencode.asp
http://php.net/manual/en/function.rawurlencode.php
http://phpjs.org/functions/rawurlencode:501

Related

Updating automatically an HTML content when the imported *.json values are changed

I have an HTML code that imports a LOCAL but UPDATABLE *.json content, and it must be updated automatically when the *.json file is updated.
This is the *.HTML code:
<html>
<head>
<script type="text/javascript" src="sample.json"></script>
<script type="text/javascript" >
function load() {
setInterval(function () {
var mydata = JSON.parse(data);
var div = document.getElementById('data');
div.innerHTML = mydata[0].location.altitude;
}, 100);}
</script>
</head>
<body onload="load()">
<div id="data">
</div>
</body>
</html>
and the adapted sample.json file is:
data = '[{"location": {"altitude": 40}}]';
I just wanna see the altitude is changing in the browser(HTML) whenever the sample.json file is updated.
Now the HTML works but only ONCE, I wanna make it dynamic.
What should I do to make the function setInterval work correctly? or maybe this function works only for local changes, not external ones.
Thnks, Sadeq
If you want the browser to get data from a URL even interval, then you need to write code which gets data from a URL in the interval. e.g. with the Fetch API. (At which point you should make it JSON instead of JS).
However HTTP is not fast. You do not want to be polling over HTTP every 100ms. Consider using Websockets to push the data from the server when it changes instead of polling.

Why is object key pair with null value not passed from server to client anymore?

I have a Google application script web application where I use google.script.run.withSuccessHandler. Server side function returns an object where all the values are null. MaterializeCSS autocomplete requires nulls
My customer today reported that the GAS web stopped working. It was 10000000% working before. I found out that the reason is a null as a value.
Working sample applicatin is here
https://script.google.com/macros/s/AKfycbzbg4YLndZ0zORBzgDc3ETLUdJeToUS1nKjORUa5fNxQt9syXmLlX1gDHzgS4w8iCBM9A/exec
https://script.google.com/d/1Uba73PIetb9fmrO44nwsmAd_epZTHy4lwz5bG3bURK3jqpd161JT0pf5/edit?usp=sharing
HTML code
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
Test
<script type="text/javascript">
console.log("test")
document.addEventListener("DOMContentLoaded", function(event) {
google.script.run.withSuccessHandler(afterDataReceived)
.returnObject()
});
function afterDataReceived(receivedData){
console.log(receivedData)
}
</script>
</body>
</html>
GS code
function doGet(e) {
var htmlTemplate = HtmlService.createTemplateFromFile("index").evaluate()
return htmlTemplate
}
function returnObject(){
var object = {}
object.a = "123"
object.b = null
object.c = 123
console.log(object)
return object
}
Is someone experiencing the same error? How to fix this?
Issue:
If null is a value for a key in a object, the key-value pair is lost when the object is passed from server to client, though null is a legal parameter.I can confirm the issue.
Solution:
The issue is reported here. Add a star to the issue, if anyone else has the same issue.
As a typical workaround for illegal parameters, Use JSON.stringify() on the server side, pass the string to the client and JSON.parse() it client side to get nulls inside a object.
Server:
function returnObject(){
return JSON.stringify({a:1,b:null,c:3});
}
Client:
document.addEventListener("DOMContentLoaded",
function(event) {
google.script.run
.withSuccessHandler(afterDataReceived)
.returnObject()
});
function afterDataReceived(receivedData){
console.log(JSON.parse(receivedData));
}

How to send json string from backing bean to external javascript file?

i have external javascript file for drawing google charts
and in this js file i want to access backing bean to get json string.
js file:
window.onload = function(){
if(typeof(google)!= undefined){
google.load('visualization', '1.0', {'packages':['corechart'],callback: drawChart});
}
};
function drawChart() {
var jsonStr=#{myBean.jsonStr} // i want to be able to do something like that
var data_recSent = new google.visualization.DataTable(jsonStr);
//
//
}
if there's no possible solution/workaround for this case, please advise about other solutions.
best solution i have found so far, is to store the json string in hidden input, and then get the value of this hidden input in the js file.
If the result of #{myBean.jsonStr} is big, I would suggest you to make it cached by browser as follows:
Use a separated js file to keep this json:
myjson.js
var jsonStrGobal=JSON_PLACEHOLDER;
In the html header
<script language="javascript" type="text/javascript" src="myjson.js?version=#{myBean.jsonVersion}" />
myjson.js is not stored physically, but loaded by a servlet or a backing bean, JSON_PLACEHOLDER is replaced by your json, this servlet of backing bean will set the Cache-control on http response header to make browser cache it. Servlet can be registered in web.xml, backing bean can be declared in pages.xml as a page action.
Increase myBean.jsonVersion whenever the content of json changes so that browser gets notified.

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.

Scanning URL All the time - Chrome Extension

I need to develop extension, where everytime i write url and in chrome and press enter. My url is first scanned, if it matches some pattern say like if the url patter has youtube in it, redirect it to facebook
This should be done automatically - not everytime i have press the icon of (chrome extension), meaning this script or piece of code will not be running on-click event, rather once installed it will always scan the url entered and do the require change and reload the tab.
Please help me out. I reach this far
<html>
<script>
function getname()
{
chrome.tabs.getSelected( null , function(tab) {
var rawurl="http://www.youtube.com/watch?";
var newurl= "http://www.youtube.com/watch?feature=player_leanback&"
if (0 === tab.url.indexOf(rawurl))
chrome.tabs.update(tab.id, {url: tab.url.replace(rawurl,newurl)});
});
}
</script>
<body onload="getname();">
</body>
</html>
I achieve this but you onload event in J-Script - is there anyway I can do this all the time without using onload() as onload require explicit click all the time.
Rewriting the code
<html>
<script>
function getname()
{
chrome.tabs.getSelected( null , function(tab) {
var rawurl="http://www.youtube.com/watch?";
var newurl= "http://www.youtube.com/watch?feature=player_leanback&"
if (0 === tab.url.indexOf(rawurl))
chrome.tabs.update(tab.id, {url: tab.url.replace(rawurl,newurl)});
});
}
</script>
<body onload="getname();">
</body>
</html>
You should consider APIs such like chrome.webRequest or chrome.webNavigation.
Besides, I believe this extension has implemented everything you mentioned.