Showing posts with label jQuery Ajax. Show all posts
Showing posts with label jQuery Ajax. Show all posts

Tuesday, May 28, 2013

jQuery : Execute/Run multiple Ajax request simultaneously

Yesterday for one of my requirement, I needed to execute/run multiple ajax request simultaneously or in parallel. Instead of waiting for first ajax request to complete and then issue the second request is time consuming. The better approach to speed up things would be to execute multiple ajax request simultaneously.


Related Post:

To do this, we can use jQuery .when(). The $.when() provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events.

To show how it works, will send multiple ajax request to Flickr API to fetch some photos. The first request will fetch photos which are tagged with "moon" and the second request will fetch photos tagged with "bird". And then we display the results in a div of both the requests.

The basic syntax is,
$.when(request1, request2, request3.....)
So here is 2 ajax request to flickr API. To iterate through the response, there is a callback function attached to it. This callback function gets executed once both the ajax request are finished.

In the case where multiple Deferred objects are passed to $.when(), it takes the response returned by both calls, and constructs a new promise object. The res1 and res2 arguments of the callback are arrays, where res1 has response of first request and res2 has response from second request.
$(document).ready(function () {
   $.when($.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?", {
        tags: "moon",
        tagmode: "any",
        format: "json"
   }),
   $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?", {
        tags: "bird",
        tagmode: "any",
        format: "json"
   })).then(function (res1, res2) {
       $.each(res1[0].items, function (i, item) {
          var img = $("<img/>");
          img.attr('width', '200px');
          img.attr('height', '150px');
          img.attr("src", item.media.m).appendTo("#dvImages");
          if (i == 3) return false;
      })
      $.each(res2[0].items, function (i, item) {
          var img = $("<img/>");
          img.attr('width', '200px');
          img.attr('height', '150px');
          img.attr("src", item.media.m).appendTo("#dvImages");
          if (i == 3) return false;
      })
  });
});
See Complete Code
You can also declare what to do in case of success and failure of ajax request. Below jQuery code execute the function myFunc when both ajax requests are successful, or myFailure if either one has an error.
$.when($.ajax("/page1.php"), $.ajax("/page2.php"))
  .then(myFunc, myFailure);
Read more about $.when.

Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Tuesday, July 10, 2012

Get JSON with jQuery using Ajax

JSON (JavaScript Object Notation) is an data exchange format and which is human-readable data. JSON has became very popular since that web pages have became interactive using AJAX. JSON format is easy to create from the server and easy to parse at client. In this post I will show you how to get JSON file from different server/ same server using jquery and Ajax and display it on webpage.

jQuery provides a method called "getJSON" to load JSON-encoded data from the server using a GET HTTP request.
jQuery.getJSON( url [, data] [, success(data, textStatus, jqXHR)] )
url: A string containing the URL to which the request is sent.
data: A map or string that is sent to the server with the request.
success(data, textStatus, jqXHR): A callback function that is executed if the request succeeds.

The "getJSON" method is shorthand Ajax function. To show you how getJSON method works, we will be using Flickr public gallery images. Flickr provides JSON format file for its public gallery images. You can select photos with particular tag from http://www.flickr.com/photos/tags/.
$(document).ready(function() {
    $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?", {
        tags: "sunset",
        tagmode: "any",
        format: "json"
    }, function(data) {
        $.each(data.items, function(i, item) {
            var img = $("<img />");
            img.attr('width', '200px');
            img.attr('height', '150px');
            img.attr("src", item.media.m).appendTo("#dvImages");
            if (i == 3) return false;
        });
    });
});​
As you can see from above code, using getJSON method load the JSON file and once it is loaded, now loop through the file and show the images on the page. For demo purpose, I am showing only 4 images.

See result below.


See Complete Code
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Monday, April 16, 2012

Read and Process XML using jQuery Ajax

While working on my current project, for one of my requirement I need to read and process the XML file using jQuery and Ajax. The actual XML file was very huge and I can't share. So in this post, I will show you how to process XML file with jQuery and Ajax.

Related Post:
Below is the sample XML file that we will be using for the demo.The XML file is having list of books with Title and Publisher as 2 XML node with every book.
//Code Starts
<?xml version="1.0" encoding="utf-8" ?>
<BookList>
  <Book>
     <Title>jQuery: Novice to Ninja</Title>
     <Publisher>Site point</Publisher>
  </Book>
  <Book>
     <Title>Learning jQuery</Title>
     <Publisher>PACKT</Publisher>
  </Book>
  <Book>
     <Title>Head First jQuery</Title>
     <Publisher>O'Reilly</Publisher>
  </Book>
  <Book>
     <Title>jQuery UI 1.8</Title>
     <Publisher>PACKT</Publisher>
  </Book>
</BookList>
//Code Ends
Now, to process the XML using jQuery, below is the idea to how to do it..
  • Declare a div which will be used to show the XML content.
  • As the display will be in the list so append the UL to the div element.
  • Call the ajax method to process the xml file.
  • Set HTTP request type to "GET" and also provide the name of XML file in url.
  • Set the datatype to "xml".
  • We also need to define a callback functions, which gets called when request is successful or if some error occurred.
  • So when success callback is called then loop through the xml content.
  • Get the node value for "Title" and "Publisher" and append it to the div.
  • Define error callback to handle the error.
So here is the complete jQuery code.
//Code Starts
$(document).ready(function(){
  $("#dvContent").append("<ul></ul>");
  $.ajax({
    type: "GET",
    url: "BookList.xml",
    dataType: "xml",
    success: function(xml){
    $(xml).find('Book').each(function(){
      var sTitle = $(this).find('Title').text();
      var sPublisher = $(this).find('Publisher').text();
      $("<li></li>").html(sTitle + ", " + sPublisher).appendTo("#dvContent ul");
    });
  },
  error: function() {
    alert("An error occurred while processing XML file.");
  }
  });
});
//Code Ends
And below is the output:
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Wednesday, April 4, 2012

Use jQuery.getScript to load external js files

jQuery provides a function called "getScript", which allows to load external Javascript or js file on the fly. The advantage of using $.getScript is that it loads the content on run time, which is far better than including <script> tag in your head section. jQuery getScript load a JavaScript file from the server using a GET HTTP request, then execute it. The syntax of $.getScript is,
//Code Starts
$.getScript('url', callback function(){
 //call the function here....
});
//Code Ends
  • url : A string containing the URL to which the request is sent. It will be URL of your js file.
  • callback function : A callback function that is executed if the request succeeds.
For example,
//Code Starts
$.getScript('js/jsPlugin.js',function(){
   Demo(); //This function is placed in jsPlugin.js
});
//Code Ends
This is a shorthand Ajax function, which is equivalent to
//Code Starts
$.ajax({
  url: url,
  dataType: "script",
  success: success
});
//Code Ends
But do you know what happens internally? When loading external js file using .getScript method, what it does it that it appends a timestamp with every request. So the request may look like,
<script src="/js/jsPlugin.js?_=ts2499874935">
instead of,
<script src="/js/jsPlugin.js">
So what it does by appending timestamp is, it tells the browser to get a fresh copy of js file every time. In other words, it disables the cache or it doesn't allow browser to cache the js file. Which can be great sometimes but not always.

What if you want to cache the script, so that it doesn't download every time from the server.

Well, there are 2 ways. First is, before making call to $.getScript method, you can set the cache true for ajax request and set it to false once script is loaded.
//Code Starts

//Set Cache to true.
$.ajaxSetup({ cache: true });
$.getScript(urlhere, function(){
  //call the function here....
  //Set cache to false.
  $.ajaxSetup({ cache: false });
});
//Code Ends

Second solution is to modify the default implementation of $.getScript to allow cache. The default implementation of $.getScript is,
//Code Starts
$.getScript = function(url, callback){
  $.ajax({
    type: "GET",
    url: url,
    success: callback,
    dataType: "script"
  });
};
//Code Ends
All you need to do is to add a boolean parameter, which will set the cache attribute to true or false. That's the beauty of jQuery that you can redefine things the way you need.
//Code Starts
$.getScript = function(url, callback, cache){
  $.ajax({
    type: "GET",
    url: url,
    success: callback,
    dataType: "script",
    cache: cache
  });
};
//Code Ends
So,now you call the $.getScript like, (notice the 3rd argument)
//Code Starts
$.getScript('js/jsPlugin.js',function(){
   Demo(); //This function is placed in jsPlugin.js
}, true);
//Code Ends
Don't worry, it will not break your existing code as if jQuery doesn't find the 3rd parameter then it will assign undefined or no to this attribute.

Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Monday, March 26, 2012

jQuery and Ajax

jQuery and Ajax is a great combination to build responsive and user friendly websites. Initially Ajax was on top but later on when jQuery came into the market, the integration of jQuery and Ajax become quite handy and useful. In this post, I have put together list of some of my already posted articles for jQuery and Ajax so that you can find them all in one place.



Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Wednesday, November 30, 2011

Avoid jQuery.Post(), use jQuery.ajax()

Well, as you are aware that there are many ways to make an ajax call. If you don't know then do read "How to Make jQuery AJAX calls". Okay, hope you have gone through the article. So 2 very common ways are jQuery.Post() and jQuery.get().jQuery post() is for to make a post request and jQuery get() is to make a get request. That's the only difference between jQuery Post() and jQuery get().

Related Post:

These methods are very popular for ajax call because they are simple to write and easy to remember the syntax as well. But you are making a mistake over here. By using jQuery post()/ jQuery get(), you always trust the response from the server and you believe it is going to be successful all the time. Well, it is certainly not a good idea to trust the response. As there can be n number of reason which may lead to failure of response. Okay, why do I say this? Let's take a look at the signature of jQuery post().
$.post({
  url: url,
  data: data,
  success: success,
  dataType: dataType
});

The parameters are,
url (String): The URL of the page to load.
data (Map): Key/value pairs that will be sent to the server.
success (Function): A callback function that is executed if the request succeeds.
dataType: The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html).

Looking at above parameters, there only a single callback function that will be executed when the request is complete (and only if the response has a successful response code). What if your request fails? There is no error handling. oh... So what should be done?

Well, jQuery provides another method to perform an ajax call which is jQuery.ajax(). This is jQuery's low-level AJAX implementation. See $.get, $.post etc. for higher-level abstractions that are often easier to understand and use, but don't offer as much functionality (such as error callbacks).
jQuery.ajax(url [, settings] )
There are various settings options available for this method. For complete list visit http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings

This method provides callback for success, error and complete. So which means that we can handle error, success and also perform any operation when the ajax request is complete.
$.ajax({
  type: 'POST',
  url: url,
  data: data,
  success: success,
  error : error,
  complete : complete,
  dataType: dataType
});
I strongly recommned that it is always better to use jQuery.ajax() over $.post() and $.get(). Having said that, does not mean that $.post() and $.get() are outdatted. If you are using jQuery 1.5 or above, you can still handle the error with $.post() and $.get().

From jQuery official documentation

The Promise interface in jQuery 1.5 also allows jQuery's Ajax methods, including $.post(), to chain multiple .success(), .complete(), and .error() callbacks on a single request, and even to assign these callbacks after the request may have completed. If the request is already complete, the callback is fired immediately.
// Assign handlers immediately after making the request,
    // and remember the jqxhr object for this request
    var jqxhr = $.post("example.php", function() {
      alert("success");
    })
    .success(function() { alert("second success"); })
    .error(function() { alert("error"); })
    .complete(function() { alert("complete"); });

    // perform other work here ...

    // Set another completion function for the request above
    jqxhr.complete(function(){ alert("second complete"); });
So that means that we can still handle the errors using $.post() as well.

But I still recommened $.ajax() method as it gives these options straight away where on the other side, using $.post() one is handling using deferred object.

Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Wednesday, September 29, 2010

Use jQuery and Ajax together with ASP.NET Master pages

I had previously posted about "jQuery does not work properly after ajax partial postback" and the best possible solution was to put all your jQuery code in pageLoad() function instead of document.ready(). This works great. But this will not work when you are using ASP.NET master page feature and you have jQuery code in master page as well as in content page. You can't use pageLoad function at both the places.

The reason is when you run the page, Master page and content page gets combined and we have single DOM. In single DOM, we can't have more than one pageLoad function.

The solution to this problem is to register another function in pageLoad() function of master page. And the registered function you can use in content page. See code.

<script type="text/javascript">
  function pageLoad() {
    // Master pageLoad() code.
 
    //Content Page Load function
    if(typeof contentPageLoad == 'function')
      contentPageLoad();
}
The contentPageLoad function will be executed on content page if you wish to include in your content page. If you don't include then it will not throw any error as we have checked in if condition.

Credit

Feel free to contact me for any help related to jQuery. I will gladly help you.
Read more...

Sunday, September 12, 2010

How to Make jQuery AJAX Calls

I had already posted about "jQuery does not work properly after ajax partial postback". But there are couple of ways via which you can make ajax call from jQuery. In this post, we will see five different ways to make jQuery ajax calls. Below is list of five different ways to make ajax calls.


I found 2 great articles which provides an in-depth overview of Ajax calls with jQuery. Worth to read and learn.
  1. A Working Example of Five Different Ways to Make jQuery AJAX Calls
  2. 5 Ways to Make Ajax Calls with jQuery
Feel free to contact me for any help related to jQuery. I will gladly help you.
Read more...

Thursday, August 12, 2010

Call jQuery from ASP.NET server side

In this post, I will explain you that how can you call jQuery from server side in ASP.Net. Lets place a button on the page and on click of button, server side click event of button will get executed.
<asp:Button ID="btnCall" runat="server" Text="Call jQuery From Server"
OnClick="btnCall_Click" />
Server side click event of button.
protected void btnCall_Click(object sender, EventArgs e)
{
   StringBuilder strScript = new StringBuilder();
   strScript.Append("$(document).ready(function(){");
   strScript.Append("alert('I am called from server.');");
   strScript.Append("});");
   Page.ClientScript.RegisterStartupScript(this.GetType(), "Script",
strScript.ToString(), true);
}
As you can see, I have registered the jQuery script using RegisterStartupScript method. So now when button click code is finished, you will see an alert on the page.

However, if you are working with ajax and your button is placed with in an updatepanel, above code will not work. Well, you can try yourself.

Call jQuery from ASP.NET server side, If Ajax is used.

Lets place a button within update panel.
<asp:ScriptManager ID="sm1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="updPnl" runat="server">
   <ContentTemplate>
       <asp:Button ID="btnCallAjax" runat="server" 
                Text="Call jQuery From Server Within Ajax"
onclick="btnCallAjax_Click"/>
     </ContentTemplate>
</asp:UpdatePanel>
Server side click event of button.
protected void btnCallAjax_Click(object sender, EventArgs e)
{
    StringBuilder strScript = new StringBuilder();
    strScript.Append("$(document).ready(function(){");
    strScript.Append("alert('I am called from server within Ajax.');");
    strScript.Append("});");
    ScriptManager.RegisterStartupScript(updPnl, updPnl.GetType(),"Script",
strScript.ToString(), true);
}
You need to use ScriptManager.RegisterStartupScript method to register your jQuery script, if your postback is asynchronous.

Feel free to contact me in case of any query. I will gladly help you.
Read more...

Monday, August 9, 2010

jQuery Datepicker does not work after Ajax Partial Postback

I had already posted number of post related to jQuery UI Datepicker.

1. Implement jQueryUI DatePicker with ASP.NET
2. Show Hand/Pointer cursor on image button with jQueryUI datepicker control
3. Disable Weekends in jQuery UI DatePicker
4. Enable weekends in jQuery UI Datepicker
5. Disable specific days in jQuery Datepicker

"jQuery UI Datepicker does not work after ajax partial postback". How true is it? Let's find out.

Place a script manager and an update panel on the page.
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="upd1" runat="server">
 <ContentTemplate>
 </ContentTemplate>
</asp:UpdatePanel>
Now place a text box and a button inside the updatepanel control.
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="upd1" runat="server">
 <ContentTemplate>
     <div style="font-family: Arial; font-size: small;">
        Select Date :
        <asp:TextBox ID="txtDate" runat="server"Font- Names="Arial"></asp:TextBox>
     </div>
     <asp:Button ID="btnAjax" runat="server" Text="Ajax PostBack" OnClick="btnAjax_Click" />
  </ContentTemplate>
</asp:UpdatePanel>
Now bind the datepicker control with the text box.
<script type="text/javascript" language="javascript">
$(document).ready(function(){      
    $("#<%=txtDate.ClientID %>").datepicker(
    {   changeMonth:true, 
        changeYear:true,
        showOn: 'button',
        buttonText:'Show Date',
        showAnim: 'fadeIn',
        showButtonPanel: true,
        dateFormat: 'DD, MM d, yy',
        buttonImage: 'Images/imgCalendar.png',
        buttonImageOnly: true
     }
   );
             
   $(".ui-datepicker-trigger").mouseover(function() {
        $(this).css('cursor', 'pointer');
   });
});  
<script>
Now create a server side click for the button which will cause an ajax partial postback.
protected void btnAjax_Click(object sender, EventArgs e)
{
   System.Threading.Thread.Sleep(1000);
}
Just run the page. You will see something like this.



Click on datepicker. The datepicker gets opened and selected date becomes value of the text box.
Now click on button. The server side button click gets called and now you will see something like this.


oops!!! The datepicker button is gone. So the statement is correct that "jQuery UI Datepicker does not work after ajax partial postback". So what do we do now to make it working within ajax. Well, nothing special. See below code.
<script type="text/javascript" language="javascript">
function pageLoad(sender, args)
{
  $(document).ready(function(){      
    $("#<%=txtDate.ClientID %>").datepicker(
    {   changeMonth:true, 
        changeYear:true,
        showOn: 'button',
        buttonText:'Show Date',
        showAnim: 'fadeIn',
        showButtonPanel: true,
        dateFormat: 'DD, MM d, yy',
        buttonImage: 'Images/imgCalendar.png',
        buttonImageOnly: true
     }
   );
             
   $(".ui-datepicker-trigger").mouseover(function() {
        $(this).css('cursor', 'pointer');
   });
  });  
}
</script>
pageLoad() function is available in JavaScript if you are using ASP.NET ajax. AJAX framework automatically wires up any client-side function named pageLoad() as an Application.Load handler. Visit my post for more info on "jQuery does not work properly after ajax partial postback."

Now run the page and you will be happy to see your datepicker working with ajax.

Feel free to contact me for any help related to jQuery. I will gladly help you.
Read more...

Tuesday, July 13, 2010

jQuery does not work properly after ajax partial postback

Don't get shocked by the title of the post. This is true. Recently I have faced this issue. Let us walkthrough of what we are talking about. We all are familiar with below code. A script manager, update panel and content template. As you see I have placed 2 buttons. One gets binded on document.ready() function and other does a async postback.
<asp:ScriptManager ID="sManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="upd1" runat="server">
 <ContentTemplate>
   <asp:Button ID="btnClient" runat="server" Text="jQuery Event" />
   <asp:Button ID="btnServer" runat="server" Text="Server Event" 
   onclick="btnServer_Click" />
  </ContentTemplate>
</asp:UpdatePanel>

Related Post:

jQuery code which binds the click event of "btnClient" button.
$(function()
{
    $("#btnClient").bind('click', function()
    {
        alert('I am clicked');
    });
});
Server side event of "btnServer" button.
protected void btnServer_Click(object sender, EventArgs e)
{
    Thread.Sleep(10000);
}
Just run this page. Click on btnClient and you will see an alert('I am clicked') message. Now click on btnServer event. An async postback occurs. Now again click on btnClient button. Oops!! No alert this time. :(

Well, just for the info that document.ready() event is fired when you DOM is ready. It does not fire on ajax async postback. So it doesn't reattach the functionality to the elements. So what to do now? Well, jQuery has introduced a new function called live() in jQuery 1.3.2 which can solve your purpose.
$(function()
{
    $("#btnClient").live('click', function()
    {
        alert('I am clicked');
    });
});
But live() only works for limited set of functionalities. Like if you have placed a datepicker control on textbox, live() function will not help you to attach it again after async postback.

Well, it's not that difficult to achieve it with Ajax. There are couple of ways to make your jQuery work after async postback.
  1. Create an End_request handler of Ajax and place your document.ready() code inside it.
    <script type="text/javascript" language="javascript">
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequest);
    function EndRequest(sender, args)
    {
        if (args.get_error() == undefined) {
                BindEvents();
         }
    }
    function BindEvents()
    {
       $("#btnClientSide").bind('click', function()
       {
             alert('I am clicked');
       });
    }
    
    BindEvents();    
    
    </script>
    
  2. Add a pageLoad() function in the page and put all your jQuery within it. pageLoad() function is available in JavaScript if you are using ASP.NET ajax. AJAX framework automatically wires up any client-side function named pageLoad() as an Application.Load handler. Both examples are same.
    Sys.Application.add_load(LoadHandler); 
    function LoadHandler() { 
     //Your code goes here.
    }
    
    OR
    function pageLoad(sender, args)
    {
        $("#btnClientSide").bind('click', function()
        {
            alert('I am clicked');
        });
    }
    
    This pageLoad function also provides a property args.get_isPartialLoad(), which returns true if it is a partial postback and false if it is normal postback.
So, you can enjoy the power of jQuery along with ASP.NET ajax to create your applications.

Feel free to contact me if you face any problem. I will gladly help you.
Read more...