jQuery: Simple Ajax Request + Event Handlers


/ Published in: jQuery
Save to your folder(s)

Here is a basic example as to how to set up an Ajax request.


Copy this code and paste it in your HTML
  1. <!-- jQuery Framework -->
  2. <script type="text/javascript" charset="utf-8" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
  3.  
  4. <script type="text/javascript" charset="utf-8">
  5. function getData( url ){
  6. $.ajax({
  7. url: url,
  8. dataType: "json",
  9. encoding:"UTF-8",
  10. beforeSend: ajaxStart,
  11. success: ajaxSuccess,
  12. error: ajaxError,
  13. complete: ajaxComplete
  14. });
  15. }
  16.  
  17. function ajaxStart( xhrInstance ){
  18. //A. Clear Any Previously Written HTML
  19. //B. Show Preloader
  20. console.log( "ajaxStart:" )
  21. }
  22.  
  23. function ajaxError( xhrInstance, message, optional ){
  24. console.log( "ajaxError:" );
  25. }
  26.  
  27. function ajaxComplete( xhrInstance, status ){
  28. //A. Remove any preloaders
  29. console.log( "ajaxComplete:" );
  30. }
  31.  
  32. function ajaxSuccess( data, status ){
  33. //Write your Parse XML Function
  34. parseData( data );
  35. }
  36.  
  37. function parseData( data ){
  38. console.log( "parseData:", data );
  39. }
  40. </script>
  41.  
  42. <script type="text/javascript" charset="utf-8">
  43. $(document).ready(function(){
  44. getData("http://path/to/xml/or/json/feed");
  45. }
  46. </script>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.