piątek, 4 września 2009

Create Fixed div where you can add messages that will fade out automatically.

When you use a lot of ajax requests in your site, especially requests that make some changes on server side and do not return any html content, there is a need to inform user if the request he performed has succeeded. The output will look like this: The plan to achieve it is: 1) Create a hidden div with fixed position in your MasterPage file: 2) Create javaScript function that will show your text for some time. 3) Call this function when your ajax request succeeded. ad. 1) Listing 1: Div html
   1:  <div id="ajax_messages" style="">Operation succeeded</div>
Listing 2: Div style
   1:  #ajax_messages {
   2:  background-color:#FFFF99;
   3:  bottom:0;
   4:  display:block;
   5:  font-family:Arial,Helvetica,sans-serif;
   6:  font-size:110%;
   7:  font-weight:bold;
   8:  height:20px;
   9:  margin:0;
  10:  padding:5px 0 0;
  11:  position:fixed;
  12:  text-align:center;
  13:  width:100%;
  14:  }
ad. 2) In your MasterPage file place javascript source code. This code uses jQuery js library. Listing 3: showMessage function
   1:  <script type="text/javascript">        
   2:          function showMessage(text) {
   3:              var am = $("#ajax_messages");
   4:              am.html(text);
   5:              am.show();
   6:              am.fadeOut(900);
   7:          }
   8:  </script>
The 3rd line grabs the div, 4th places your text in it, 5th shows the div and 6th makes the div disappear slowly (900 is the time of fading out in milliseconds). ad. 3) Listing 4: An example of using this function
   1:  <script type="text/javascript">
   2:      function MakeAjaxRequest(param1, param2) {        
   3:          var url = "/Some/Site?param1=" + param1
   4:          if (param2) {
   5:              url = url + "&param2=" + param2;
   6:          }
   7:          $.ajax({
   8:              method: "POST",
   9:              url: url,
  10:              dataType: "html",
  11:              success: function(result) {                             
  12:                  showMessage("Operation succeeded");
  13:              }
  14:          });
  15:      }
  16:  </script>
Now on your link you can put:
   1:  <a href="javascript:MakeAjaxRequest('param1value', 'param2value')">Make ajax request</a>

Brak komentarzy: