having issue to make an ajax call to google finance api - javascript

If you copy and past the following url to your browser:
http://finance.google.com/finance/info?client=ig&q=MUTF_CA%3ATDB900
it will output an string no problem. (that is what i wanted to retrieve from the following ajax call)
But if i do the following:
this.getQuote = function() {
$.get('http://finance.google.com/finance/info?client=ig&q=MUTF_CA%3ATDB900', callback);
}
var callback = function(data){
alert(data);
}
It gave me an "500 Internal Server Error". I checked using firebug console.
Did i do something wrong in the ajax call?
Thanks.

As Shadow_boi already guessed, the problem is due to the same origin policiy, which always applies to ajax requests. You need to use JSONP to fix the problem.
See this fiddle for solution: http://jsfiddle.net/cb9c3/

Related

send a javascript request to another domain and get the response - not in jsonp

i am really banging my head here for more then a day, i am trying to send a request and get the response from another site. i'm doing it with jsonp (from the obvious reason). but the response is not a JavaScript function definition, so it keeps failing.
can anyone in this planet help me get the response the right way.
i attached the code i wrote, again: because the response is not in json it's not working. (try to run it yourself and you'll see).
any suggestions?
<script>
function test()
{
$.ajax({
dataType: 'jsonp',
jsonp: 'jsonp_callback',
url: 'https://www.facebook.com/ajax/typeahead/first_degree.php?viewer=1000009843914&token=1-1&filter[0]=user&options[0]=pending_request&lazy=1&token=v7&stale_ok=1&__a=1&__user=1000009843914& viewer=1000009843914',
});
}
function jsonp_callback(data)
{
var val=JSON.stringify(data);
myString = val.slice( 11 );
$('#container').html(myString);
/*for (;;);*/
}
test();
</script>
The server must be programmed to include the JSONP callback within its script file. If it only knows to return JSON, it will have no effect when the dynamic script tag is inserted into the page since JSON can at most provide an object--but it won't go anywhere unless the same file calls the function. In this way, it is different from Ajax, since a dynamically inserted script tag can only interact with your own code if it knows to call one of your functions. Just as an example, it might return:
jsonp_callback({facebooKData:[...]});
You should investigate how the Facebook API supports JSONP (not just JSON) for whatever you are trying to do. Typically APIs will accept a "callback" variable to determine which callback function it should use (which jQuery handles for you).

JQuery .post() not returning data

I am trying to pass parameters to the TinyPaste API. I have the following JQuery script in an HTML file,
$.post("http://tinypaste.com/api/create.json",
{
"paste": "This is test paste",
"title": "Test",
"is_code": 0,
"is_private": 1
},
function(data) {
console.log(data);
}
);
As seen in the Firefox's Web Console, I can see that the request is made and is successful (The content length of the response is as expected). But the callback function is not printing anything in the console window.
What am I doing wrong here?
Looks like you are making a request to another domain from your website and this violates the SAME ORIGIN POLICY of browers, you need to use JSONP to work around this..
you should write like this
$.post("http://tinypaste.com/api/create.json",
{
'paste': "This is test paste",
'title': "Test",
'is_code': 0,
'is_private': 1
},
function(data) {
console.log(data);
},
'jsonp'
);
You must send also a data type to server, means jsonp.
EDIT: POST does not work for cross domain USE $.getJSON instead
$.getJSON("http://tinypaste.com/api/create.json",
{
"paste": "This is test paste",
"title": "Test",
"is_code": 0,
"is_private": 1
},
function(data) {
console.log(data);
}
);
It is entirely possible the API does not serve JSONP, in which case you will need to resort to alternate methods
The major (and only) problem with the script posted in the question is that it is making a cross domain HTTP/POST request while on a normal webpage. I previously believed you were working on some browser extension, which if configured properly will allow you to have cross-domain requests. HTTP/POST will just not work in your case. Although there are hacks to get HTTP/GET working, like using the script tag, and JSONP.
In your case, what I suggest is let your server (which serves out your page) carry out the request for you.
The process will be:
You submit a request to the server with the parameters for tinypaste.
The server side script will do the HTTP/POST to tinypaste, and fetch the response. This response is sent across to the browser.
Browser gets the response. (and may be redirects or something)
Or as #charlietfl suggests, you could use YQL and Jquery

$.post function, return is empty

I have a problem wit a $.post request. No errors, but the return is empty. Before I start bugging the server admin, of who the service is, with this problem. I want to make sure I did not make any mistake myself.
Below the code I'm using:
var post_data = JSON.stringify({'str_action':'log_element', 'int_id':'TEST', 'str_value':'EMPTY'});
$.post('http://url/', post_data, debug_return_data);
function debug_return_data(data)
{
alert(data);
}
Problem is that the returned data in the alert is empty. Did I make any mistake in my code?
Thanks in advance.
The Ajax call looks correct, check the response in firebug or chrome dev tools to make sure the server is actually returning data.
If you are making the AJAX call to anther server other than the one in the address bar it will be blocked as a cross-domain call. Use JSONP if you want to do this:
http://devlog.info/2010/03/10/cross-domain-ajax/
$.post('http://url/', post_data, function(data)
{
alert(data);
});
this is in the jquery documentation

JQuery external Ajax call not working in IE

I have an ajax script that sends some data to an external URL. The external URL is hosted on the same server, however the domain is different than the source of the ajax call.
This is working perfectly in Firefox and Chrome. However in IE The ajax call does not go through, and the Return False function does not either work (once the ajax call fails).
Below is my code:
$.get('http://myexternaldomian.com/feedback/save.php', {
answer: $('#answer').val(),
page_url: pathname
});
// Keeps the user on the page
return false;
When I try removing the http:// from the ajax url, the return false does work.
Any help on this would be greatly appreciated. Thank You
From jQuery documentation
Due to browser security restrictions,
most "Ajax" requests are subject to
the same origin policy; the request
can not successfully retrieve data
from a different domain, subdomain, or
protocol.
and Same Origin Policy on Wiki
I'm surprised any of them are working. Browsers generally don't allow ajax calls to a domain other than the one the current page came from.
The main exception to this rule is if you make an ajax call using jsonp (json with padding). You can do this with jQuery, here's how. Look under the dataType option.
(this is copypaste from my another similar answer). You could try enabling "jQuery.support.cors=true" flag and see how it goes. I use jQuery v1.7.2.
I had to load webpage from local disk "file:///C:/test/htmlpage.html", call "http://localhost/getxml.php" url, and do this in IE8+ and Firefox12+ browsers, use jQuery v1.7.2 lib to minimize boilerplate code. After reading dozens of articles finally figured it out. Here is my summary.
server script (.php, .jsp, ...) must return http response header Access-Control-Allow-Origin: *
before using jQuery ajax set this flag in javascript: jQuery.support.cors = true;
you may set flag once or everytime before using jQuery ajax function
now I can read .xml document in IE and Firefox. Other browsers I did not test.
response document can be plain/text, xml, json or anything else
Here is an example jQuery ajax call with some debug sysouts.
jQuery.support.cors = true;
$.ajax({
url: "http://localhost/getxml.php",
data: { "id":"doc1", "rows":"100" },
type: "GET",
timeout: 30000,
dataType: "text", // "xml", "json"
success: function(data) {
// show text reply as-is (debug)
alert(data);
// show xml field values (debug)
//alert( $(data).find("title").text() );
// loop JSON array (debug)
//var str="";
//$.each(data.items, function(i,item) {
// str += item.title + "\n";
//});
//alert(str);
},
error: function(jqXHR, textStatus, ex) {
alert(textStatus + "," + ex + "," + jqXHR.responseText);
}
});
http://en.wikipedia.org/wiki/Same_origin_policy
I dont think it should work on Chrome or Firefox, unless you testing on localhost or something like that, this would be against the crossdomain policy.
What you need is to proxy it inside the same domain, use php to connect to the destination you need and call the url from the same domain.
save_cross_domain.php -> connect through server to the desired url
then ajax calls save_cross_domain.php
you should add a
callback=?
to your url and handle this on the server side.
I did this once for a java servlet, and when the callback param was included I added an extra pair of parenteses around the json response..
hope it helps!
A couple of things:
The answers/conversation for this question has gone a bit out of context. Actually from the question it was more implied how to make ajax calls in IE. [Atleast modify the question title, else the question is very localized]
A couple of solutions to this cross-domain issue:
CORS[compatible after IE7]
JSONP [ here actually the browser takes in the input thinking it is a script]
server side encoding

jQuery Ajax POST not working with MailChimp

I have the following code I am using to send data to a MailChimp Newsletter List (API v3). Everytime I remove the type: POST from the function it attempts to post the data via GET and it sends the data properly (ok response in MailChimp API dashboard). When testing this in the browser (FF) I get a .part file with "true" response.
$(function(){
$("a#test").click(function(e){
e.preventDefault()
data = {
"apikey" : "667378947",
"id" : "90298590285",
"email_address" : "test#getmoxied.net",
"output" : "json"
}
$.ajax({
type: "POST",
url: 'http://us2.api.mailchimp.com/1.3/?method=listSubscribe',
data: data,
success: function(data){
alert(data);
},
error: function(){
alert("err");
}
})
});
});
Im pulling my hair out on this one, any insight is greatly appreciated.
Thanks in advance,
JN
There is an undocumented endpoint that uses JSONP to do cross-domain ajax requests.
Just change 'post?' to 'post-json?' and add '&c=?' to the end of the standard url to get the JSONP endpoint. This doesn't requires the API key to be exposed on the client-side, or the creation of a server-side view.
I wrote a jQuery plugin that uses this method, if that's useful at all
https://github.com/scdoshi/jquery-ajaxchimp
The main issue is what jc commented on your original post - this simply won't work due to Same Origin Policy issues. Firebug is not as vocal about why the GET call fails, but that's why it returns no data. If you watch that with the POST, you'll see Firefox doesn't even make the call. Chrome's js console on the other hand straight explains the Same Origin policy to you.
All in all, this is a very good thing if for no other reason than it prevents you from publicly publishing your account's API Key, which is a very bad thing to do. If the reason why doesn't immediately sink in, go read through the large number of methods available in the API and then realize that all you need to access them is that API Key.
The correct way to do this is to POST data back to your server, then make the request from there. There are several fully built PHP examples (one using jquery, even), here.
e.preventDefault();
data = {
"apikey" : "667378947",
"id" : "90298590285",
"email_address" : "test#getmoxied.net",
"output" : "json"
};
Could be? Semicolon is important. Hehe

Categories

Resources