I am currently experimenting JSONP data using native Javascript. I am trying to get the data to display. How ever i am receiving a syntax error. Unexpected token : As far as i am aware i follow the correct steps into in order gather data. Below is a snippet of my code. Link to JSfiddle
<script src="http://linkToMyJSONDetails"></script>
JS
function (data) {
var showStops = '';
for (var i = 0; i < data.markers.length; i++) {
showStops += '<div class="stops">';
showStops += '<h3>' + data.markers[i].smsCode + '</h3>';
showStops += '<h1>' + data.markers[i].name + '</h1>';
showStops += '</div>';
}
document.getElementById('bus-stops').innerHTML = showStops;
}
You need to do 2 things.
First: Add a callback: (Scroll to the right, since your link is a bit long)
http://digitaslbi-id-test.herokuapp.com/bus-stops?northEast=51.52783450,-0.04076115&southWest=51.51560467,-0.10225884&callback=someFunction
^^^^^^^^^^^^^^^^^^^^^^
Second: Define the callback:
// same function name as the callback in the jsonp url
function someFunction(data) {
var showStops = '';
for (var i = 0; i < data.markers.length; i++) {
showStops += '<div class="stops">';
showStops += '<h3>' + data.markers[i].smsCode + '</h3>';
showStops += '<h1>' + data.markers[i].name + '</h1>';
showStops += '</div>';
}
document.getElementById('bus-stops').innerHTML = showStops;
}
Fiddle: http://jsfiddle.net/29eajsjm/4/
Make sure the function is defined before calling the jsonp.
you have not mentioned the function name.
insead of
function (data) {
use
var myFn = function (data) {
};
or
function myFN(data) {
}
First of all validate the json you are getting from your function at jsonlint.
Related
I am writing a piece of code to basically call in the top money earner and the top five money earners in a given data set. While writing the code, I realized that there were a couple of spots where I was rewriting the code, basically copying and pasting it. While that works, I wanted to throw the duplicate portion of the code and call it from a function. However, that is not working and I don't exactly know why. Here is the code that is duplicated:
for (let i = 0; i < len; i++) {
html +=
'<li class="top">' +
'<h2>' +
topSalaries[i][8] +
'</h2>' +
'<h3>' +
topSalaries[i][11] +
'</h3>';
}
container.innerHTML = '<ul id = "topSalaries">' + html + '</ul>';
Here is the function I made to be called. However, when I call it, it's not working as expected, where the information shows up on the webpage. I'm using VS Code and am running this on live server so when I save, the webpage automatically updates.
function createHtmlElements(len, html) {
for (i = 0; i < len; i++) {
html +=
'<li class="top">' +
'<h2>' +
topFiveSalaries[i][8] +
'</h2>' +
'<h3>' +
topFiveSalaries[i][11] +
'</h3>' +
'</li>';
}
return html
}
function getTopSalaries(boston, container) {
const people = boston.data;
const len = 5; // only want top five
let topFiveSalaries = sortPeople(people).slice(0,len);
// create the list elements
html = createHtmlElements(len, html);
container.innerHTML = '<ul id = topSalaries">' + html + '</ul>';
}
For one thing topFiveSalaries is going to be undefined in the function createHtmlElements you've created, you must pass it to the function
Ok. So, Thanks Dave for the help. It looks like I also was missing a piece in that I needed to pass the array into the function as well. This is what I wrote and how I called it.
function getTopSalaries(boston, container) {
const people = boston.data;
const len = 5; // only want top five
var topFiveSalaries = sortPeople(people).slice(0,len);
let html = '';
// create the list elements
html = createHtmlElements(len, html, topFiveSalaries);
container.innerHTML = '<ul id = topSalaries">' + html + '</ul>';
}
function getTopEarner(boston, container){
const people = boston.data;
const len = 1;
let highEarner = sortPeople(people).slice(0,len);
var html = '';
// create the list elements
createHtmlElements(len, html, highEarner);
container.innerHTML = '<ul id = topSalaries">' + html + '</ul>';
}
// sort people by income in descending order
function sortPeople(people) {
people.sort(function(a, b) {
return b[11] - a[11];
})
return people
}
function createHtmlElements(len, html, array) {
for (i = 0; i < len; i++) {
html +=
'<li class="top">' +
'<h2>' +
array[i][8] +
'</h2>' +
'<h3>' +
array[i][11] +
'</h3>' +
'</li>';
}
return html
}
Is there a way to use callback functions in Python with requests? This is from a here API example im trying to copy using python. This is the request and the function used at the end in the parameters is defined jsoncallback=parseResponse.
If i can replace the functionality of the callback in a other way would be fine too, is it possible to just take the response and do everything thats done in parseRespone?
"https://route.api.here.com/routing/7.2/calculateroute.json?jsonAttributes=1&waypoint0=50.7799,6.08425&waypoint1=50.77988,6.08288&waypoint2=50.78144,6.07794&representation=overview&routeattributes=sc,sm,sh,bb,lg,no,shape&legattributes=li&linkattributes=sh,nl,fc&mode=fastest;car;traffic:enabled&app_id=inCUge3uprAQEtRaruyaZ8&app_code=9Vyk_MElhgPCytA7z3iuPA&jsoncallback=parseResponse"
var parseResponse = function (resp)
{
if (resp.error != undefined)
{
alert (resp.error);
feedbackTxt.innerHTML = resp.error;
return;
}
if (resp.response == undefined)
{
alert (resp.subtype + " " + resp.details);
feedbackTxt.innerHTML = resp.error;
return;
}
//add Routing Release number if not already done
if (releaseRoutingShown == false){
releaseInfoTxt.innerHTML+="<br />HLP Routing: "+resp.response.metaInfo.moduleVersion;
routerMapRelease = resp.response.metaInfo.mapVersion;
mapReleaseTxt.innerHTML = "HLP Routing Service based on "+routerMapRelease+ " map release";
releaseRoutingShown = true;
}
var strip = new H.geo.Strip(),
shape = resp.response.route[0].shape,
i,
l = shape.length;
for(i = 0; i < l; i++)
{
strip.pushLatLngAlt.apply(strip, shape[i].split(',').map(function(item) { return parseFloat(item); }));
}
polyline = new H.map.Polyline(strip,
{
style:
{
lineWidth: 5,
strokeColor: "rgba(18, 65, 145, 0.7)",
lineJoin: "round"
}
});
group.addObject(polyline);
var links = [];
for(var i = 0; i < resp.response.route[0].leg.length; i++)
links = links.concat(resp.response.route[0].leg[i].link);
pdeManager.setLinks(links);
pdeManager.setBoundingBoxContainer(group);
pdeManager.setOnTileLoadingFinished(pdeManagerFinished);
pdeManager.start();
}
function pdeManagerFinished(finishedRequests)
{
feedbackTxt.innerHTML = "Done. Requested " + finishedRequests + " PDE tiles for " + numLinksMatched + " route links. ";
var resultHTML = '<table class="pde_table" cellpadding="2" cellspacing="0" border="1" width="90%">' +
'<thead>' +
'<tr>' +
'<th width="80%">Sign</th>' +
'<th width="20%">#</th>' +
'</tr>' +
'</thead>' +
'<tbody id="maps_table_body">';
for(var sign in signs)
{
resultHTML += "<tr>" + "<td>" + sign + "</td>" + "<td>" + signs[sign] + "</td>" + "</tr>";
}
resultHTML += "</tbody>" + "</table>";
document.getElementById("resultArea").innerHTML = resultHTML;
document.getElementById("resultArea").style.display = "block";
map.addObject(group);
map.setViewBounds(group.getBounds());
}
You don't need to use any callback (since there's nothing that would execute it anyway); elide the parameter and call response.json().
The below code does raise
Unauthorized. The request is not from an authorized source.
so you may need some additional headers or such (possibly an Origin header if the credentials are matched to a site address).
import requests
resp = requests.get(
url="https://route.api.here.com/routing/7.2/calculateroute.json",
params={
"jsonAttributes": "1",
"waypoint0": "50.7799,6.08425",
"waypoint1": "50.77988,6.08288",
"waypoint2": "50.78144,6.07794",
"representation": "overview",
"routeattributes": "sc,sm,sh,bb,lg,no,shape",
"legattributes": "li",
"linkattributes": "sh,nl,fc",
"mode": "fastest;car;traffic:enabled",
"app_id": "inCUge3uprAQEtRaruyaZ8",
"app_code": "9Vyk_MElhgPCytA7z3iuPA",
},
)
# Uncomment this to see the actual error.
# print(resp.content)
resp.raise_for_status()
print(resp.json())
Currently,
when i input test,
the comment system directly show my typing, "test"
Modify to,
I would like the modify the javascript code that when i input test,
it convert to html result "test" (a hyperlink to "#").
How can i modify following code? Many thanks!
function fetchComments(leaveRequestId) {
$('#existingComments').html(lang_Loading);
params = 'leaveRequestId=' + leaveRequestId;
$.ajax({
type: 'GET',
url: getCommentsUrl,
data: params,
dataType: 'json',
success: function(data) {
var count = data.length;
var html = '';
var rows = 0;
$('#existingComments').html('');
if (count > 0) {
html = "<table class='table'><tr><th>" + lang_Date + "</th><th>" + lang_Time + "</th><th>" + lang_Author + "</th><th>" + lang_Comment + "</th></tr>";
for (var i = 0; i < count; i++) {
var css = "odd";
rows++;
if (rows % 2) {
css = "even";
}
var comment = $('<div/>').text(data[i]['comments']).html();
html = html + '<tr class="' + css + '"><td>' + data[i]['date'] + '</td><td>' + data[i]['time'] + '</td><td>' +
data[i]['author'] + '</td><td>' + comment + '</td></tr>';
}
html = html + '</table>';
} else {
}
$('#existingComments').append(html);
}
});
}
<div id="existingComments">
<span><?php echo __('Loading') . '...';?></span>
</div>
var comment = $('<div/>').text(data[i]['comments']).html();
You're explicitly escaping the data from the Ajax request so that it shows up as text and isn't treated as HTML source code.
If you don't want to do that, then just don't do it!
(Do be careful not to expose yourself to stored XSS attacks though)
$('#existingComments').html(html);
This may seem a duplicate, but in my case it's a bit different.
I have the following code:
function stateList() {
function parseStateList(response){
var stateTable= "<table><tr><td style='width: 500px; color: blue;'>Folder name (state)</td></tr>";
console.log(response);
statelist=response["States"];
console.log(statelist);
for (var i in statelist) {
a = statelist[i];
var index = Object.keys(statelist).indexOf(i)
console.log("i="+index);
console.log(statelist[i]);
stateTable+="<tr><td style='width: 500px;'><button id=\""+index+"\" onclick=\"GetSavedState("+a+",parseSavedState)\">" + a + "</button></td></tr>";
//document.getElementById(index).onclick = function(){GetSavedState(a,parseSavedState);};
}
stateTable+="</table>";
document.getElementById('state_output').innerHTML = stateTable;
}
GetStateList(parseStateList);
}
And I'm getting this error SyntaxError: missing ) after argument list
The error is not in the code you've put in your question. I made a dummy GetStateList function and the snippet works fine. This points to the error being, for example, in the structure of the response you get from GetStateList.
PD: I took the liberty of quoting the first parameter of GetSavedState because you were passing it as a variable, whereas a is a string.
function GetStateList(callback) {
callback(
{
"States":{
"CA":"California",
"FL":"Florida"
}
});
}
function GetSavedState(stateusps, callback) {
callback(stateusps);
}
function parseSavedState(savedState) {
console.log(savedState);
}
function stateList() {
function parseStateList(response) {
var stateTable = "<table><tr><td style='width: 500px; color: blue;'>Folder name (state)</td></tr>";
console.log(response);
statelist = response["States"];
console.log(statelist);
for (var i in statelist) {
a = statelist[i];
var index = Object.keys(statelist).indexOf(i)
console.log("i=" + index);
console.log(statelist[i]);
stateTable += "<tr><td style='width: 500px;'>";
stateTable += "<button id=\"" + index + "\" onclick=\"GetSavedState('" + a + "',parseSavedState)\">" + a + "</button>";
stateTable += "</td></tr>";
}
stateTable += "</table>";
document.getElementById('state_output').innerHTML = stateTable;
}
GetStateList(parseStateList);
}
stateList();
<div id="state_output"></div>
This doesn't answer your error, it's just a demonstration that it isn't where you think it is.
In my javascript app, I insert a user message using the code:
var displayMessages = function(response, onBottom) {
var user = GLOBAL_DATA.user;
var acc = '';
for(var i=0; i<response.length; i+=1) {
var obj = response[i];
var acc_temp = "";
acc_temp += '<div class="message ' + (obj['user_id']==user['id'] ? 'message-right' : 'message-left') + '">';
acc_temp += '<div>' + Autolinker.link($(obj['message']).text()) + '</div>';
if (obj['user_id']!=user['id']) {
acc_temp += '<div class="message-details">' + obj['first_name'] + ' ' + obj['last_name'] + '</div>';
}
acc_temp += '<div class="message-details">' + obj['date_sent'] + '</div>';
acc_temp += '</div>';
acc = acc_temp + acc;
}
addMessage(acc, onBottom);
};
The problem is that, if obj['message'] = "<script>alert(1);</script>"; then what gets printed on the screen is "alert(1);" because I use .text(). How can I insert the string with the script tags, so that it looks exactly like that on the page? I don't want it to get executed.
Thanks
I use these helper functions.
function htmlEncode(value){
return $('<div/>').text(value).html();
}
function htmlDecode(value){
return $('<div/>').html(value).text();
}
I would escape the other variables as well if you are not sure that they will not have any executable code.
I solved it using this:
function escapeHTML(str) {
return $("<p></p>").text(str).html();
}
I think you'll need to wrap your object in a dummy tag, then you can retrieve the full html from that.
You'll have issues though, because you're using a script tag, which will be evaluated.
obj['message'] = "<script>alert(1);</script>";
>
$(obj['message']).text();
> "alert(1);"
$(obj['message']).html();
> "alert(1);"
$(obj['message']).wrapAll('<div>').text();
// alerts with 1
> "alert(1);"
Not using a script tag will work.
obj['message'] = "<span>alert(1);</span>";
>
$(obj['message']).wrapAll('<div>').text();
> "<span>alert(1);</span>"