Parse External JSON With JQuery $.getJSON? - javascript

I want to get a quote from iheartquotes and add it to a div when the page loads. I currently have this code but do not know why it wont work
<script type="text/javascript">
$(document).ready(function() {
$.getJSON('http://iheartquotes.com/api/v1/random?format=json&callback=?', function(data) {
$(".content").html(json.quote);
});
});
</script>
And the HTML in the body
<div class="content">
This will be replaced with a quote
</div>

The URL returns JSON, not JSON-P, so you can't read it cross domain with JS in a browser.
You could do this server side instead, or find a third party proxy that could convert it to JSON-P (perhaps YQL).

Yes i too agree with #Quentin. This is not possible in client-side as you are trying to access another domain due to Same origin policy.
So you can call a webservice / a static webmethod in an aspx page (using page- methods) from javascript and do this server side and get back the results client-side itself, where you can do this cross-domain.
The following code may help you to do this in server-side,
You could use WebClient for that matter:
using (var client = new WebClient())
{
// Define data to be posted
var values = new NameValueCollection
{
{ "key1", "value1" },
{ "key2", "value2" },
};
// Send the POST request
byte[] result = client.UploadValues("http://foo.com", values);
// This will contain the cookie being set
string cookie = client.ResponseHeaders[HttpResponseHeader.SetCookie];
}
Hope this helps...

Related

How can I sent a javascript object via href

I am building a javascript script that will go on a few websites ( clients ), get some info and return it to my home site. Since every website is a little different I need to do this in pure javascript. The way I want it to work is collect the info and store it in an object ( which I have working ) then send it to the home site with window.location.href. Without knowing what is available on each site ( for instance, they may not have JQuery ), what would be the best method of this?
The page it is sending to is a php script.
Example of object.
var obj = {
page_on:window.location.pathname,
loadtime:loadtime,
};
Then I want to send home in a function ( so i can reuse in different places )
function sendHome(obj) {
window.location.href="http://domainname.com/handleinfo/obj
}
The code above is not working, its where I am right now. I need to do something with obj. I am not real good with javascript.
Thanks
You need to serialise your object first. Then you can use XMLHttpRequest to send the data to your server.
Note that when your server is on a different domain than the websites you want to run your JavaScript from (it sounds like that), you need to enable CORS on the server, too.
Here is a sample of the script to send the data, given CORS is enabled on the server:
var obj = {
url: window.location.href,
loadTime: loadtime
};
var req = new XMLHttpRequest();
req.open('POST', 'https://yourdomain.com/track');
req.setRequestHeader("Content-Type", "application/json");
req.send(JSON.stringify(obj));

Sending and getting data via $.load jquery

I'm writing a system in HTML5 and Javascript, using a webservice to get data in database.
I have just one page, the index.html, the other pages i load in a <div>
The thing is, i have one page to edit and add new users.
When a load this page for add new user, i do this:
$("#box-content").load("views/motorista_add.html");
But, i want send a parameter or something else, to tell to 'motorista_add.html' load data from webservice to edit an user. I've tried this:
$("#box-content").load("views/motorista_add.html?id=1");
And i try to get using this:
function getUrlVar(key) {
var re = new RegExp('(?:\\?|&)' + key + '=(.*?)(?=&|$)', 'gi');
var r = [], m;
while ((m = re.exec(document.location.search)) != null)
r.push(m[1]);
return r;
}
But don't work.
Have i an way to do this without use PHP?
This won't work. Suppose your are loading the motorista_add.html in a page index.html. Then the JS code, the function getUrlVar(), will execute on the page index.html. So document.location that the function will get won't be motorista_add.html but index.html.
So Yes. To do the stuff you are intending, you need server side language, like PHP. Now, on the server side, you get the id parameter via GET variable and use it to build up your motorista_add.php.
You can pass data this way:
$("#box-content").load("views/motorista_add.html", { id : 1 });
Note: The POST method is used if data is provided as an object (like the example above); otherwise, GET is assumed. More info: https://api.jquery.com/load/

Is it possible to override window.document.location.host?

Use-case :
My server is in the domain www.mywebsite.com
In a webpage, I have a JavaScript tag call to a WebService which is in the same domaine
The JavaScript call is signed and is valid only for a limited time
The WebService use a session cookie set in the same domain to return the user name
to the browser
The risk here is that a malicious site can scrape my page to get the valid WebService call and include it to its page to display the user name on it's pages for phishing purpose
What I do
Let say that I want to prevent the hotlinking of this JavaScript :
<script type="text/javascript" src="http://webservice.mywebsite.com/username.js?ID=SERVICE_ID;ts=1386607643;sig=52f72b1a0fe9158d87d9e4ba4e26a731"/>
In username.js, I do this check :
if (document.location.host.match(/[.]mywebsite[.]com$/i) == null) {
document.location.href="http://www.mywebsite.com/error.html";
} else {
username = username_obtained_using_the_session_cookie
}
My question
Is it safe ?
Yes it is possible to redefine the window object:
var window = '123';
alert(window.location);
gives undefined in the alert.
Or even override the document object (your edit to your question):
var document = { "location" : { "host" : "www.mywebsite.com" } };
so it now passes your test:
if (document.location.host.match(/[.]mywebsite[.]com$/i) == null) { document.location.href="http://www.mywebsite.com/error.html"; } else { username = username_obtained_using_the_session_cookie }
A better solution would be if you made your web-service respond to a POST rather than a GET for your method, then due to the the Same Origin Policy it will not be possible for any remote domain to read the contents of your response containing the username.
You can either execute the POST in plain JavaScript or you can use JQuery.

On jQuery.post, I get the message: The method GET is not allowed for the requested URL

I have the following problem:
I work on a Flask application, and I want to pass some data to the server via AJAX. I am pretty new on this AJAX thing, so I can't get something right.
On my client side, when the user clicks on an icon, I want to pass some data via jQuery.post stored in the variable message:
jQuery("#icon_ID").click(function() {
var message = {
'GRAPH_TYPE': graphType
};
var _sendOnSuccess = function () {
}
var jqxhr = jQuery.post('/graph', message, _sendOnSuccess, 'json');
});
On my server side, I have the following code:
#app.route('/graph', methods = ['POST'])
#login_required
def physical_graph():
ret_data = request.form['GRAPH_TYPE']
return ""
All I want to do for now is to access the GRAPH_TYPE on the server side. However, when I click on the icon, I get the error message:
Method Not Allowed
The method GET is not allowed for the requested URL.
I really don't understand why Python tells me that I am using the GET method, when in fact I am using the POST method.
Can please someone help me with this? What should I do to solve this problem? If there's some other method I can use, feel free to give me advice of any kind. Just bear in mind that besides jQuery, I don't want to use other JavaScript library.
Thank you in advance!
It's because you are passing an object as data like
var message = {
'GRAPH_TYPE': graphType
};
In this case jQuery attempts to URL encode the object and by default sends with the data type application/x-www-form-urlencoded; charset=UTF-8 ans sends a GET request. To overcome this problem make sure that you’re passing jQuery a string for the data parameter and to do this you can use JSON.stringify like
var message = JSON.stringify({ "GRAPH_TYPE": graphType });

parsing json response

I'm calling a REST webservice and getting JSON format as a result. I'm calling rest service from another domain than mine. How can I parse this?
To answer the question you asked: There is a long list of parsers, including several for JavaScript, at the bottom of http://json.org/
If your question is actually: "How can I read JSON data from another domain with client side JavaScript in the browser?", then you can either fetch it using a proxy on the same domain as the page, or you can provide the data using JSON-P instead.
<script type="text/javascript" src="http://www.json.org/json2.js"></script>
var myObject = JSON.parse(myJSONtext);
or use jQuery
$.getJSON('http://twitter.com/users/usejquery.json?callback=?', function(json) {
alert(json.followers_count);
});
if you need only parsing jQuery also can do this:
var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );
Are you getting the json result? Most implementations have protection agains cross site scripting and will only allow a request back to the original host of a page.
Could you please post some example code for your current implementation.

Categories

Resources