So I am busy with a private coding project right now, but can't seem to get my code to work properly.
I want to in essence, get data from my API and display it on to my HTML page, the data type is set to "jsonp" because of CORS errors( this was the only way I could debug it ), anyone have an idea of how I can get this to return usable data for my project?
function fetch(){
"use strict";var url = "https://api.pandascore.co/lol/champions?token=*my_unique_token*";
$.ajax({
url: url,
type: "GET",
crossDomain: true,
dataType: 'jsonp',
contentType: "application/json; charset=utf-8",
beforeSend: function(xhr){
xhr.setRequestHeader('Access-Control-Allow-Origin','*');
},
success: function(data){
console.log(data);
},
done: function(data){
console.log(data);
},
error: function(error){
console.log(error);
}
});
}
Edit:
This is a parsing problem, I cant get the code to log the success, I can see a response but its for my error log, but it doesn't show the success log, so the data is unusable.
Why not try the vanilla fetch method?
const url = 'https://api.pandascore.co/lol/champions?token=my_unique_token';
fetch(url)
.then(response => response.json())
.then(data => console.log(data))
This code should handle parsing JSON data you receive from pandascore. Fetch is not available in IE11, but there should be some polyfills lying around on the web.
Related
My requirement is to grab the response from FBapi('/me',) and do a ajax post to a view to update the info to database. With the code below although I get a 200 on Ajax Post I am unable to retrieve the response using request.POST['name'],
request.POST['birthday'] etc .
If I simply give a:-
def GetFBData(request):
print(request)
I get: "WSGIRequest: POST '/login/facebook/" and an AJAX error message of Unexpected token at JSON position 1.
Below is my script :-
FB.api('/me', {
fields: 'birthday,cover,devices,email,first_name,gender,id,last_name,link,location,name,name_format,timezone,verified,website,locale'},
function(response) {
response = JSON.stringify(response);
$.ajax({
url: '/login/facebook/',
type: 'POST',
data:{fb:response , window:window.ui},
dataType: 'json',
success: function (data) {
console.log(data);
},
error: function (xhr, ajaxOptions, thrownError){
alert(thrownError);
}
});
});
How to correctly retrieve this response data on the view?
I'm sending a simple data back from the server to the client.
app.post('/user', function (req, res) {
var userName = "John";
res.end(JSON.stringify({"error":"", "user": userName}));
});
$.ajax({
type: "POST",
...
contentType : 'application/json',
dataType: "json"
})
.done(function(data) {
// send join message
var resData = JSON.parse(data);
alert("hello"); // this doesn't show up
});
});
});
But in the browser console, I get this error - "Uncaught SyntaxError: Unexpected token o".
If I do JSON.stringify and JSON.parse on the content, it works fine.
alert(JSON.parse (JSON.stringify({"error":"", "user": userName})).user);
And also, .done works fine without a data payload from the server i.e. the alert("hello") works.
So, I'm guessing something fishy is happening while sending data within res.end(). Please help.
While at it, it would be nice if you can also tell me how to do the same using res.json() and which one is preferable.
The problem here is that you set dataType: 'json' in your jQuery request. This causes the response from the server to be automatically parsed as JSON, so it will return the object rather than the raw server response.
I have followed a tutorial on how to locally store a json feed for offline use (see link below).
http://samcroft.co.uk/2013/using-localstorage-to-store-json/
I implemented the code but unfortunately it didn't work. The json feed is stored but there seems to be a problem retrieving it. I don't have any errors, the feed just doesn't appear.
$.ajax({
url: 'path/to/json',
dataType: 'jsonp',
jsonp: 'jsoncallback',
cache: true,
timeout: 5000,
success: function(data, status){
var localData = JSON.parse(window.localStorage.getItem('events'));
$.each(function(key, value){
//do the do
});
var localData = JSON.stringify(data);
window.localStorage.setItem('events', localData);
},
error: function(){
app.showAlert('Something has gone wrong. Please report this issue or check back later.', 'Error');
},
complete: function(){
$('.scroll').removeClass('loading');
}
});
Does anyone have any ideas why this might be happening?
Thanks
Hayush!
Been trying to transfer my Chrome extension to manifest 2. Everything is working except for one script which calls an ajax. I have a variable that contains a JSON content which needs to be transferred to the server.
function sendlist(list){
jsontext = JSON.stringify(list);
$.ajax({
url: amfurl + "user/listbookmarks/",
dataType: 'text json',
async: true,
type: 'POST',
processData: false,
data: {'folders': jsontext},
success: function(data){
$('#importing').css('display','none');
$('#importdone').css('display','block');
console.log(data);
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
}
For some reason the ajax part is not executed at all. No error message was triggered, nor in the server error log.
All of the inline scripts and scripts in general were included in the popup.js. So it's probably not the issue.
Any thoughts?
Thanks!
The following code works perfectly on previous manifest
function importbookmarks(){
$('#formadd').css('display','none');
$('#importing').css('display','block');
_gaq.push(['_trackEvent', 'chromextension','importbookmarks', username]);
chrome.bookmarks.getTree(function(bookmarks) {
sendlist(bookmarks);
});
}
function sendlist(list){
jsontext = JSON.stringify(list);
$.ajax({
url: amfurl + "user/listbookmarks/",
dataType: 'text json',
async: true,
type: 'POST',
// processData: false,
data: {'folders': jsontext},
success: function(data){
$('#importing').css('display','none');
$('#importdone').css('display','block');
console.log(data);
}
});
}
The problem wasn't with the function. The button execution wasn't calling it correctly.
Here is the code I used to get the function to work in manifest 2
document.addEventListener("DOMContentLoaded", function () {
document.getElementById("import-bookmarks").addEventListener("click", function () {
importbook();return;
});
JSON data not parsing in node.js displays undefined in console..
Here is HTML code:
var jsonObjects = [{id:1, name:"amit"}];
jQuery.ajax({
url: 'http://localhost:8081',
type: "POST",
data: {"id":"1", "name":"amit"},
dataType: "json",
success: function(result) {
alert("done")
}
});
Here is Nodejs code:
http.createServer(function (request, response)
{
response.writeHead(200, {"Content-Type":"text/plain"});
var urlObj = JSON.stringify(response.data, true);
console.log(urlObj)
response.end();
}).listen(8081);
Try using GET method Instead of Post. Try this
var jsonObjects = [{id:1, name:"amit"}];
$.ajax({
type: 'GET',
url: 'http://localhost:8081',
data: {
jsonData: JSON.stringify(jsonObjects)
},
dataType: 'json',
complete: function(validationResponse) {
}
});
The data will be held in the request, not the response as it has come from the client request.
If you are using express to create your http server you will also need to tell it to use the bodyParser middle wear.