Can't get $.ajax or $.get to work - ajax

I have this $.ajax (using jquery) code, it originally was the $.get that is now commented but for some reason I'm always getting the error and I can't find anything wrong with it =/, am I overlooking something?
$.fn.randomContent = function(options){
var contentArray = new Array();
var dType = "html";
var defaults = {
xmlPath: "../xml/client-quotes.xml",
nodeName: "quote"
};
var options = $.extend(defaults, options);
alert(options);
$.ajax({
type: "GET",
url: "../xml/client-quotes.xml",
dataType: "html",
success: function(){
$(defaults.nodeName).each(function(i){
contentArray.push($(this).text());
});
$(this).each(function(){
$(this).append(getRandom());
});
},
error: function(){
alert("Something Went wrong");
}
});
/*$.get(defaults.xmlPath, function(){
alert("get");
$(defaults.nodeName).each(function(i){
contentArray.push($(this).text());
});
$(this).each(function(){
$(this).append(getRandom());
});
}, type);//$.get*/
};
Here's the getRandom() function:
function getRandom() {
var num = contentArray.length
var randNum = Math.floor(Math.random()*num)
var content = "";
for(x in contentArray){
if(x==randNum){
content = contentArray[x];
}
};
alert(content);
return content;
}

It could be that the browser is caching your GET requests. In this case, either:
ensure the server is controlling your cache options (using cache-control settings of private or no-cache)
change the method of your AJAX call to POST instead of GET
differentiate your GET request by adding querystring parameters that change with each request
I prefer option #1, specifically because POST operations are intended to change something on the server, and so we should use that method when our actions do in fact modify server state. GET requests on the other hand, are requests that do nothing more than read data.
I feel a GET request is more appropriate for this task, and so in my own code I would prevent the caching of the response.

Does that url have to be absolute? I've never tried doing ajax requests with a "../" in it. Do you have FireBug installed? You could examine the response header from the sever.

Related

Monitor AJAX JSON Object download/transfer progress

I would like to know if it is possible to create a progress bar for an AJAX call where data returned is a JSON Object which represents a large database . This functions is used to synchronize between a client - server side database, and would like to show progress for users, like a normal file download...
I have tried the following without sucesss..
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.addEventListener("progress", updateProgress, false);
function updateProgress (oEvent) {
if (oEvent.lengthComputable) {
var percentComplete = oEvent.loaded / oEvent.total * 100;
console.log(percentComplete);
} else {
console.log('Unable to compute Size');
}
}
return xhr;
},
type: "POST",
url: "http:s......"
ect....//
Probably using - XMLHttpRequest
I'm trying to achieve the same so digging it here.
Does this post work for you?

Multiple AJAX calls on page load

I'm attempting to pull two separate things from outside sources to put onto an HTML page I'm creating. I have a successful AJAX function to pull the most recent video from a particular Youtube channel by parsing through the XML/RSS feed for that channel. I receive this feed through an AJAX call.
I'd also like to get the most recent blog post from a Blogger account. The code for parsing the feed to get the most recent entry shouldn't be difficult, but I'm having trouble with simultaneous AJAX calls. I read somewhere that it can only handle one at a time? I'm weary about queuing them because I don't want to the content on the page to load in steps. I'd rather it all just get fetched simultaneously. How might I go about doing this?
Here is my current script:
<script type="text/javascript" charset="utf-8">
$(function() {
$.ajax({
type: "GET",
url: "http://gdata.youtube.com/feeds/base/users/devinsupertramp/uploads?orderby=updated&alt=rss&client=ytapi-youtube-rss-redirect&v=2",
dataType: "xml",
success: parseXml
});
});
function parseXml(xml) {
$(xml).find("item:first").each(
function() {
var tmp = $(this).find("link:first").text();
tmp = tmp.replace("http://www.youtube.com/watch?v=", "");
tmp = tmp.replace("&feature=youtube_gdata", "");
var tmp2 = "http://www.youtube.com/embed/" + tmp + "?autoplay=1&controls=0&rel=0&showinfo=0&autohide=1";
var iframe = $("#ytplayer");
$(iframe).attr('src', tmp2);
}
);
}
</script>
I read somewhere that it can only handle one at a time?
Either you misunderstood what the person was trying to say or they were incorrect. Javascript doesn't run any functions concurrently so someone with poor English might reword that as "can only handle one at a time" but that doesn't mean you can't make multiple AJAX calls. jQuery is smart and will do what it needs to do to make sure both calls are executed eventually.
If you'd like all the content to be loaded simultaneously the sad fact is you can't. However you can make it appear that way to the user by declaring a flag that is set by the success method of each call. Then just keep the content hidden until both flags have been set.
EDIT:
Here's a very simplistic approach to make it appear that they are fetched simultaneously:
<script type="text/javascript" charset="utf-8">
var youtubComplete = false;
var otherComplete = false;
$(function() {
$.ajax({
type: "GET",
url: "http://gdata.youtube.com/feeds/base/users/devinsupertramp/uploads?orderby=updated&alt=rss&client=ytapi-youtube-rss-redirect&v=2",
dataType: "xml",
success: parseXml
});
$.ajax({
type: "GET",
url: "http://someotherdata.com/",
dataType: "xml",
success: function() { otherComplete = true; checkFinished(); }
});
});
function parseXml(xml) {
$(xml).find("item:first").each(
function() {
var tmp = $(this).find("link:first").text();
tmp = tmp.replace("http://www.youtube.com/watch?v=", "");
tmp = tmp.replace("&feature=youtube_gdata", "");
var tmp2 = "http://www.youtube.com/embed/" + tmp + "?autoplay=1&controls=0&rel=0&showinfo=0&autohide=1";
var iframe = $("#ytplayer");
$(iframe).attr('src', tmp2);
}
);
youtubeComplete = true;
checkFinished();
}
function checkFinished()
{
if(!youtubeComplete || !otherComplete) return;
// ... Unhide your content.
}
</script>
The browser will support multiple outbound calls but there is a cap per domain. Take a look at this related Q/A How many concurrent AJAX (XmlHttpRequest) requests are allowed in popular browsers?.
There are several good libraries for doing request scheduling including chaining and parallelizing AJAX calls. One good library is https://github.com/kriskowal/q, which provides async promises framework to enable arbitrarily complicated chaining of AJAX requests. Q minified is about 3.3KB.
// The jQuery.ajax function returns a 'then' able
Q.when($.ajax(url, {dataType: "xml"}))
.then(function (data) {
var parsedXML = parseXML(data)
...
// some other ajax call
var urls = [Q.when($.ajax(url2, {data: {user: data.userId}})),
Q.when($.ajax(url3, {data: {user: data.userId}}))];
// run in parallel
return Q.all(urls)
})
.then(function (data) {
// data retrieved from url2, url2
})

Jquery Ajax - Tumblr API v2

I'm trying to delve into the depths of the murky world of Tumblr, and can't understand how to get over the following error:
Uncaught SyntaxError: Unexpected token :
I believe it may be because I'm getting back json, but trying to use jsonp. Here's what I'm trying to send:
$(function(){
$.ajax({
type: "GET",
url : "http://api.tumblr.com/v2/blog/MyTumblrName.tumblr.com/info",
dataType: "jsonp",
data: {
api_key : "MyTumblrApi"
},
success: function(data){
console.log(data);
},
});
});
I get a 200 OK response, and the data but still the above error (which I don't understand and would like to know more about)
Tumblr also kindly points out the following, but I'm unclear on the specifics.
All requests made with HTTP GET are JSONP-enabled. To use JSONP,
append jsonp= and the name of your callback function to the request.
JSONP requests will always return an HTTP status code of 200 but will
reflect the real status code in the meta field of the JSON response.
Any help would be awesome, thanks!
Do what Tumblr is telling you to - add a callback function name to the request
myJsonpCallback = function(data)
{
console.log(data);
}
$.ajax({
type: "GET",
url : "http://api.tumblr.com/v2/blog/MyTumblrName.tumblr.com/info",
dataType: "jsonp",
data: {
api_key : "MyTumblrApi",
jsonp : "myJsonpCallback"
}
});
========================================================
EDIT: The console.log thing is a syntax error since I didn't actually test this code.
What happens to success? I don't really know. Try and find out :) It will probably be called but data parameter likely be null or something.
The issue here is that jQuery names it's callback parameter callback, where as Tumblr is expecting jsonp. Upon 200 response jQuery likely simply eval()s the response, which is why myJsonpCallback is actually called.
In case you don't want to use jQuery:
var tumblrFeed = document.createElement('script');
tumblrFeed.setAttribute("src", "http://api.tumblr.com/v2/blog/{blog.tumblr.com}/posts?api_key={your api key}&jsonp=callback");
document.getElementsByTagName("head")[0].appendChild(tumblrFeed)
function callback(data){
console.log(data);
}
I've created simple function for this purpose:
function jsonpRequest(opt){
var params = "";
var blogName = "{your blog name}";
var api_key = "{api key}";
if("selector" in opt){params = "id=" + opt.selector;}
if(("offset" in opt) && ("limit" in opt)){params = "limit=" + opt.limit + "&offset=" + opt.offset;}
if("callback" in opt){params += "&jsonp=" + opt.callback;}else{params += "&jsonp=callback";}
params += "&api_key=" + api_key;
var tumblrFeed = document.createElement('script');
tumblrFeed.setAttribute("src", "http://api.tumblr.com/v2/blog/" + blogName + "/posts?" + params);
document.getElementsByTagName("head")[0].appendChild(tumblrFeed)
}
How to use it:
jsonpRequest({offset: 50, limit: 5});
function callback(data){do stuff here ...}
Alternative usage:
jsonpRequest({offset: 50, limit: 5, callback: "nameOfMyAmazingCallbackFunction"});
function nameOfMyAmazingCallbackFunction(data){do stuff here ...}

dojo pass URL parameter into AJAX

I want to take URL parameter and pass to ajax function,
var queryParams = dojo.queryToObject(window.location.search.slice(1));
var data = dojo.toJson(queryParams, true);
console.log(data);
getCategory( data );
...
function getCategory(input){
dojo.xhrGet( {
// The following URL must match that used to test the server.
url: "http://js.localhost/dojo-release-1.5.0-src/json3.php",
handleAs: "json",
content: input,
on my URL parametetr, I pass in
?return_type=category&category_desc=Business2
when I view on firebug, the ajax request become ....
t?0=%7B&1=%0A&2=%09&3......
but data debug is correct, any idea what's wrong?
{ "return_type": "category",
"category_desc": "Business2" }
just found out that it doesn't need dojo.toJson
var queryParams = dojo.queryToObject(window.location.search.slice(1));
getCategory( queryParams );

Set ajax request in joomla using mootools

I am having a prob for ajax request in joomla using mootools.
var url = '<?php echo JURI::base();?>index.php?option=com_test&task=getselectmode&selectedid='+$('parent_question').value;
var params ={method: 'post',update:'test'};
var myAjax = new Ajax(url, params);
myAjax.request();
My prob is that, is there any to set onComplete event of the ajax request.
i have set it as below on above code but nothing happen.
onComplete: function(response) { alert('Response: ' + response); }
Can you please provide full code of how to use ajax using mootools 1.1 ??
Thanks in advance
just add the onComplete to the params object, no need to add the event seaprately. also, you can use this.response.text. it can all look a bit more compacted - depends on your preference. if you don't plan on reusing the object, just call it direct and don't assign it to a variable either:
new Ajax(url, {
method: "get",
update: $("someelement"),
onComplete: function() {
alert(this.response.text);
}
}).request();
if you do something with the response text, you may want to remove the update: bit. if you need to evaluate the response (as javascript), use evalResponse: true instead of eval(this.response.text);. also handy - evalScripts: true|false if you want to do something from the server side along with the response.
This should work:
var ajaxObj = new Ajax ('index.php?option=com_yourcomponent&view=yourview&format=raw', {
method: "get"
});
ajaxObj.addEvent('onComplete', function (data) {
// data is the response text
// use as desired
});
// this initiates the call
ajaxObj.request();
maybe:
var a = new Ajax( url, {
method: 'post',
data: { parfoto: foto },
onComplete: function( response ){
..........
}
}).request();

Resources