Retrieving cross-domain JSON data, Javascript/JSON - javascript

I did some research on retrieving cross domain JSON data, but when I implemented it, the code didn't work. Doing some more research, I found that browsers don't let websites retrieve data from a different host due to security reasons. I found an answer that said I should use JSONP, but it still wasn't working? This was my code.
function getWeather(location){
$.getJSON("http://api.openweathermap.org/data/2.5/weather?q=" + location + "&appid=/*my usual app id is here*/&callback=?", function(result){
//response data are now in the result variable
alert(result.weather[0].description);
var changeW = document.getElementById("theweathertext");
changeW.innerHTML = "The current weather at your destination: " + result.weather[0].description +".";
});
}
When I test the code, the browser isn't letting me retrieve the data? How would I fix this? Thanks in advance.
UPDATE: This code was working when I was testing it locally, but when I did a live launch preview, it didn't work. Could this be some other problem?

I think this code will work if you provide a valid apikey:
$.getJSON(
'http://api.openweathermap.org/data/2.5/weather?q=lisbon&callback=?',
function(data){
console.log(data);
}
);
EDIT: It currently gives me 401 code which means i have no rights to access this endpoint. That is why i'm suggesting to use a valid api key.

Related

Accessing JSON data through API with js

WHY! Why is this not working. I am using the weatherbit api, and trying to simply get the uv index. Mind you, in a browser the proper link displays all the information but I can not get it to work through js, putting it through to a div.
I replaced the actual request data with (nameOfData) for privacy, I assure you that there is no problem with the parameters specific.
$getJSON('https://api.weatherbit.io/v2.0/current?lat=(Lat)&lon=(Lon)&key=(Key)', function(data) {
// JSON result in `data` variable
$(".UV").html(data.data[1].uv);
});
Please help.
It is failing because you need an API key. Using the URL in the address bar of a browser does not have that restriction.
Sometimes a workaround in this case is to use a proxy on a server. Your code queries the server, and the server mimics a browser. It depends on the web service how you will fare.
I got it working with async, somehow.
async function getData(){
let response = await fetch(weatherbitApi);
let data = await response.json()
return data;
}
getData().then (data =>
console.log(data.data[0]));

Issues accessing Facebook profile image

This is the kind of question that I am sure has a simple answer, but I been with this for days now without finding it.
The issue comes when I try to access the picture via the graph API.
According to the graph API the following URL should return a JSON with is_silhouette and url
https://graph.facebook.com/xxx/picture
When I try that in the Graph Explorer it works fine, but when I test the same URL in the browser I get automatically redirected to the URL attribute of the response instead of getting a JSON.
My problem is that I need to access the contents of that JSON to get the URL attribute in order to display the user profile.
My code looks something like this
var fbimage = "https://graph.facebook.com/" + e.uid + "/picture/";
var xhrFbImage = Ti.Network.createHTTPClient({
onload : function() {
jsonData = '';
jsonData = this.responseText;
Ti.API.info("inside FB response...");
Ti.API.info(jsonData);
}
});
xhrFbImage.open("GET", getFbImage);
xhrFbImage.send();
The response is always null
Any tip in the right direction will be really appreciated.
Found the answer.
By adding ?redirect=false I get the actual JSON without the redirect.
So the correct URL to query is
https://graph.facebook.com/xxx/picture?redirect=false
The answer was more visible than I thought. You can refer to it here
https://developers.facebook.com/docs/graph-api/reference/user/picture/

how to query the sharepoint List from outside website by Javascript

I'm totally new on JavaScript and SharePoint.
What I am trying to do is to build a website that be able to connect SharePoint 2010 and query data from it using JavaScript. The website I am building is outside the SharePoint.
I searched a lot of questions and examples about this topic. But all of these confused me, a very very new programer. So please forgive me if you think I am asking silly questions, but those things really confuse new programer like me. I wish my question could also help others who is as fresh as I am.
Here comes my questions:
1) what method should I use
I found a lot of samples teaching how to query the List of SharePoint, e.g. using Client Object Model. Does it is applied to my case? I think that is for the SharePoint website programming, am I right? Because based on the sample I see, there is no any URL that link to the SharePoint Server I want to query.
Or using xmlhttp.open("POST", "http://[my SharePoint Sever]/_vti_bin/search.asmx", true) ...
2) what is right URL of the SharePoint Server and its List
According to my understanding, in my codes, I should first link to the right SharePoint ( or the specific List). so there should be a URL of the SP. I don't think opening the SharePoint List and do copy paste the Address is the right. how to get the right URL and how to alter it (like adding _vti_bin/search.asmx at the end of URL)
3) what is the right query format
when I try to right my own query. too many different format of query examples confused me a lot.
soapEnvelope = "<?xml version=\"1.0\"?> \
<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" \
...
and some looks like this,
var soapEnv =
'<?xml version="1.0" encoding="utf-8"?>' +
'<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"' +
...
4) any reference should I quote to make my codes work
should I use Qjuery, XML, or Ajax? What's the connection and how to use them? (sorry about this unclear question, not sure what to ask specifically )
I'm sorta embraced about my un-mature questions. I really need to figure it out somehow....
I will appreciate it a lot if you could give me a full example including and . So I could have a better idea of where is the right place to put my coding.
Thank you so so so much!!!!
There is an open source library created for Sharepoint 2010, code name Camelot. You can find more information here:
http://camelotjson.codeplex.com/
This is a code sample from the link above:
Javscript:
// Build the command
var command = {
Type: "SELECT",
List: "Tasks"
}
var result;
// Send the command using JQUERY
$.ajax({
type: "GET",
contentType: "application/json",
data: { command: JSON.stringify(command)},
url: "/_vti_bin/Camelot.JSONAPI/jsonapi.svc/Items",
success: function (data) {
// Decode and store the result in a variable
result = $.parseJSON(data.d);
console.log("Successfully executed the command, please check the 'result' variable.");
},
error: function (xhr, textStatus, errorThrown) {
console.log(errorThrown);
}
});
You probably want to look at SPService or at the library I created: SharepointPlus.
I think SharepointPlus is really easy to use. For example if you want to query a list to get the data you'll do something like:
$SP().list("Name of your list").get({fields:"First_x0020_Field,OtherField", where:"OtherField = 'something'"}, function(data) {
for (var i=data.length; i--;) console.log(data[i].getAttribute("First_x0020_Field"))
})
Check the SharepointPlus website, it's full of examples. I think it's what you're looking for :-)

Javascript obfuscate AJAX code

First of all sorry if the name of the topic isn't the most correct.
Imagine the following code which connects to a PHP file by AJAX.
function get_locales(){
var the_locale = $('#page-add-text').val();
var url = "classes/load_info.php?type=locale&value=" + the_locale;
var all = "";
$.getJSON(url, function(data){
$.each(data, function(index, item){
all += "<li data-name='" + item.value + "'></li>";
});
$("#page-add-listview").html(all);
$("#page-add-listview").trigger("change");
$("#page-add-listview").listview("refresh");
});
}
If people download the page, they will see classes/load_info.php?type=locale&value= + the_locale;
With this they automatically assume that the url is: www.stackoverflow.com/classes/load_info.php?type=locale&value=TESTING;
So, they can view/retrieve what the function prints, plus, they might try to get some bugs.
I'm asking for help in know-how of best ways (if there is any..) to avoid this.
Thank you.
No matter how much you obfuscate your code, the Network panel of Developer Tools will always show the exact request clear as day.
Why not try just fixing bugs and not leaving security holes in your code?
The person will only be able to see client side code and not the code that is executed on your sever (PHP, etc). There is no way to hide what the server sends to the browser.
Security of your application should never rest on the client-side, for reasons just like this one. If you are passing anything to the client that they shouldn't see, then the way you fix that is to just not pass sensitive data to the client. The data that you pass to the client is data that you want them to see. Errors and bugs happen, but the fact that they are taking the time to inspect your AJAX returns probably means that they won't mind much.

Recursion issue when fetching external pages with jQuery Ajax

I have a Google Chrome extension for exporting entries from a website. I can't get all entries by one query and I'm using a parameter for paging, i.e. '...&p=' + pageNumber++. I do this with connecting to my web server and this is not a problem with PHP. But I found that I can generate pdf files directly using jsPDF and I decided to get rid of the server side help.
Now I want to fetch the entries with jQuery Ajax. The problem is that I don't know in advance how many pages I have to fetch.
My current solution is:
function runRecursionTest(url, pageNumber){
var currentUrl = url + '?p=' + pageNumber;
$.getJSON("http://query.yahooapis.com/v1/public/yql?"+
"q=select%20*%20from%20html%20where%20url%3D%22"+
encodeURIComponent(currentUrl)+
"%22&format=json'&callback=?"
).done(function(data) {
if(data.results[0]){
data = filterData(data.results[0]);
$('#export-target-list').append($(data).find('#entry-list').html());
runRecursionTest(url, pageNumber++);
} else {
alert('Stop! Last page: '+(pageNumber-1));
}
});
}
It seems logical, huh? But suprisingly it fails. Too much requests are sent even when I have 1 page only. Can't stop it.
Any ideas?

Categories

Resources