Ajax in javascript not working - ajax

$(document).ready(function() {
$('#content').html('');
$.ajax({
url:'data.json',
dataType: "json",
success: function(data) {
$('#content').append('<p>'+data.rank+'</p>');
}
});});
In this code (it works) data.json contains the JSON data in this format:
{
"user_id":"3190399",
"user_name":"Anand_Dasgupta",
"followers_current":"86",
"date_updated":"2009-06-04",
"url":"",
"avatar":"205659924\/DSC09920_normal.JPG",
"follow_days":"0","started_followers":"86",
"growth_since":0,
"average_growth":"0",
"tomorrow":"86",
"next_month":"86",
"followers_yesterday":"86",
"rank":176184,
"followers_2w_ago":null,
"growth_since_2w":86,
"average_growth_2w":"6",
"tomorrow_2w":"92",
"next_month_2w":"266",
"followersperdate":[]
}
This data comes from the URL:
http://twittercounter.com/api/?username=Anand_Dasgupta&output=json&results=3
(Click the URL to get the data)
But when I replace data.json in the $.ajax function with the URL which contains the same data, this code below doesn't seem to work...
$(document).ready(function() {
$('#content').html('');
$.ajax({
url:'http://twittercounter.com/api/username=Anand_Dasgupta&output=json&results=3',
dataType: "json",
success: function(data) {
$('#content').append('<p>'+data.rank+'</p>');
}
});});
Any help with the problem will be highly appreciated.
Thanks in anticipation,
Anand

The thing is that you are trying to access an url on a different domain (unless you actually are on twittercounter.com of cause). Anyways, if you want to do cross-site AJAXcalls which browsers don't permit due to safety, you have to use the JSONP "trick". You can use JSONP with jQuery, which it seems like you are using. Last I checked though, jQuery required some server side configuration, so unless you can alter the data you get, you would have to do the AJAX request manually, in which case you would be able to get it, using the JSONP method.

Basically you are trying to access a cross-domain AJAX request. This is not allowed because it tends to compromise browser security. Here is a way that you can get around it:
http://code.google.com/p/cross-domain-ajax/
Noah
Edit: Mon Jun 29 10:24:51 CDT 2009 googletorp FTW!

Related

How to send and retrieve cross-domain ajax data in userscript

I use this code to store and retrieve ajax data via http://openkeyval.org/
$.ajax({ /* send data */
url: "http://api.openkeyval.org/store/",
data: "test-key-data=" + JSON.stringify([123,456]),
dataType: "jsonp",
success: function(data){
console.log(data);
}
});
$.ajax({ /* retrieve data */
url: "http://api.openkeyval.org/test-key-data",
dataType: "jsonp",
success: function(data){
console.log(data);
}
});
everything work fine in Chrome javascript console but in userscript I get error like this
Uncaught ReferenceError: jQuery110208458673823624849_1375932537303 is
not defined
I try to use GM_xmlhttpRequest to retrieve data like this
GM_xmlhttpRequest({
method: "GET",
url: "http://api.openkeyval.org/test-key-data",
onload: function(response) {
console.log(response.responseText);
}
});
but it seem like openkeyval doesn't accept data via POST/GET method and log result was like when you access it directly from url of browser like this
{"error":"not_found","documentation_url":"http://openkeyval.org/"}
I include jQuery and it work fine with this code
// #require http://code.jquery.com/jquery-latest.min.js
I try to use Greasemonkey/jQuery XHR bridge with out change other code by like this
// #require http://courses.ischool.berkeley.edu/i290-4/f09/resources/gm_jq_xhr.js
and try use openkeyval official javascript library with code like this
// #require http://cdn.openkeyval.org/statics/openkeyval.packed.js
and retrieve data with code like this
var ourCallback = function(value, key) {
console('The value of ' + key ' + is ' + value);
};
window.remoteStorage.getItem('test-key-data', ourCallback);
still got error ERROR: Unexpected string
Please help, I mess with it more than 10 hours. Thank you so much.
It look like $.ajax always trigger error event function
but GM_xmlhttpRequest can retrieve mistype data, so I try looking for dataType: "jsonp" in GM_xmlhttpRequest and I got that jsonp header content-type is "application/javascript" OR "application/json" and the first one work well.
my new code for retrieve data look like this
GM_xmlhttpRequest({
method: "GET",
url: "http://api.openkeyval.org/test-key-data?nocache=" + new Date(),
headers: {
"Content-Type": "application/javascript"
},
onload: function(response) {
console.log(response.responseText);
}
});
and retrieve data using $.ajax even it always trigger error event function but it still send data.
I try both content-type on GM_xmlhttpRequest and still not work.
my code to store data look like this
$.ajax({ /* send data */
url: "http://api.openkeyval.org/store/",
data: "test-key-data=" + JSON.stringify(myVarObject),
dataType: "jsonp"
});
Add this into $.ajax({...})
crossDomain: true;
It is because by default cross domain ability is disabled. See http://api.jquery.com/jQuery.ajax/
EDIT:
Sometimes there will be a issue with different charset between local script and remote script. Try using:
scriptCharset: "utf-8";
Also look at JQuery AJAX is not sending UTF-8 to my server, only in IE
Elaborating my comment
The reference is to the callback function generated by jquery.
It Sounds to me the way you invoke your userscript unloads the jquery functions before the callback is executed.
Perhaps you use a link and forgot the preventDefault?
If you ajax and have
$("#linkid").on("click"
or
$("#formid").on("submit"
it is MANDATORY to continue like this:
,function(e) {
e.preventDefault();
Otherwise the link is followed or the form is submitted which may not have any visible effect, but the asynchronous scripts have been (partially) unloaded unless the form and link has a target other than the current window

Cross domain Ajax call from HTML page (can't use any proxy)

I was trying to get some information from another server using ajax post call as .
$.ajax({
type: 'POST',
url: testURL,
data: data,
//dataType: 'jsonp',
dataType: "script",
success: function (data) {
alert("Successfully posted (Test) : " + data);
},
error: function (ts) {
alert("Inside Error : " + ts.responseText);
}
});
Here testURL is the URL where i am posting the data (Cross domain requests are only possible if datatype is either jsonp or script), and it suppose to return text/html data back (what fiddler says will be the return type for the data).
I am not sure if i can use any proxy as pages are normal HTML pages.
Isn't there any way to get the [data] as text (as for now success expecting JASONP data and alert("Successfully posted (Test) : " + data); only showing data as undefined). I can't make any changes to API or whatever it is on the remote Server.
Thanks for the help in advance.
Regards
Without a proxy you cannot do it. If that is in a windows box, you can create a COM object to make the call to that server and from your JavaScript you call that COM.
UPDATE:
Well it seems you can with JSONP
jsonp with jquery

Converting AJAX call to avoid cross-domain problems

I m trying to convert the following code to another AJAX call, in order to not have cross-domain problems!
This is my original code:
<script>
$(document).ready(function() {
$("#os").load('http://www.a.gr/os #livesos');
var refreshId = setInterval(function() {
$("#os").load('http://www.a.gr/os #livesos');
}, 60000);
$.ajaxSetup({ cache: false });
});
</script>
And here is a sample code for what i want to do, but i dont know how...
$.ajax({
type: "GET",
cache: false,
url: 'http://www.a.gr/os',
dataType: "???",
.
.
.
.
});
Can someone help me please?
Your best bet to avoid cross-domain issues is to have the phone call your server, and the server can call the other servers to get the data needed.
There are a couple of benefits to this, one being that you can cache recent calls, if it doesn't change often, and more quickly send it back to the client.
Also, if you want to later change the url or make additional calls to return richer data, you can do that without affecting the client.

calling delete rest api by jquery

I had called the GET REST API by following code :
$.getJSON('http://myapisite.com/user/1?callback=?', function(msg){
console.log(msg);
});
But for calling DELETE REST API through jquery
what i had tried is :
$.ajax({
url: 'http://mysite.com/user/1?callback=?',
type: 'DELETE',
dataType: 'json',
data: '',
success: function(response) { console.log('PUT completed'+response); }
});.
and this api is not being called , I want to know how should i call the DELETE REST API .
Thanks
You are trying to do a cross-domain request. This means that you cannot use XMLHttpRequest (the basis of AJAX) because of the same-origin policy. You are using a workaround called JSONP, which works by inserting <script> tags into your document.
Script tags will always fetch content via GET, so you can't do a DELETE, POST, PUT or suchlike with them.
The best workaround would be to have a script on your own server that proxies the DELETE request for you.

Ajax with JQuery: 200 ok, but not "success"

I'm trying to use AJAX to send a query to Google Books and display the results on my website. I'm using JQuery to send the request and handling the response, like so:
var query = [formatted input from a form];
var URL = "http://books.google.com/books/feeds/volumes?q="+query+"&start-index=1&max-results=5";
$.ajax({
type: "GET",
url: URL,
dataType: "xml",
success: function(data, status){
alert(status);
}
});
Currently, I just have the script alerting "success" if a response is received. If I use my script to send that query to a local page for testing, this works just fine. But when I set the URL to the Google one listed above, as instructed on the Developer API page, I never see the alert. According to Firebug, I am receiving a response and a status of 200 ok as I should, but it's not getting to that "success" path. Does anyone know why?
Edit: I should add that if I follow the URL directly, to http://books.google.com etc. with some random q, it displays the feed XML with no problems, so the query is not the issue.
You can't make cross-domain requests using XMLHttpRequest under the standard browser security settings. One possible solution is to write a local proxy function (assuming you can create server-side code) that forwards the query to the external site, and then returns the response.
Edit: It looks like Google provides a JavaScript API as well. I would assume that they've crafted in such a way to avoid the cross-domain XHR issue.
http://code.google.com/apis/books/docs/js/devguide.html#execute
Edit: The JavaScript API for books was deprecated. While it's no longer practically useful, you can see the original referenced documentation text via the Wayback Machine archive: http://web.archive.org/web/20120414070427/http://code.google.com/apis/books/docs/js/devguide.html#execute
It's a cross-domain problem with ajax calls because browsers have a security model based on a domain policy.
if you don't wan to include the whole Google Books API, you can also use Google Ajax API with jsonp for cross-domain ajax calls.
Docs here:
http://code.google.com/apis/books/docs/js/jsondevguide.html#basic_query
jQuery example
var query = 'jquery';
var URL = 'https://ajax.googleapis.com/ajax/services/search/books?v=1.0&q=' + query;
$.ajax({
type: 'GET',
url: URL,
dataType: 'jsonp',
success: function( data, status ){
alert( data.responseData.results.length + ' results found!' );
},
error: function() {
alert( 'Something goes wrong!' );
}
});
Ciao!

Resources