Page 1 of 1

Ajax request with JQuery

Posted: Fri Apr 24, 2009 6:19 am
by Sindarin
I just started learning jquery and I am trying to use the ajax functions, I made a test page which loads some data from a php file while showing a throbber in the process. Is there a way to make it so to be notified when the request fails?

Code: Select all

<html>
  <head>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
$(document).ready(function(){
 
//START
$("div").click(function(event){
 
$("#getcontent").html("<img src='throbber.gif' alt='Loading...' />"); 
$.get("test.php", function(data){
$("#getcontent").html(data);
});
});
//END
 
});
 
 
    </script>
 
  </head>
  <body>
<div id='getcontent' width='343' height='333' style='background-color:red;height:333;'>test</div>
  </body>
  </html>

Re: Ajax request with JQuery

Posted: Fri Apr 24, 2009 7:30 am
by miyur
The method you have used is an easy way to send a simple GET request to a server. It allows a single callback function to be specified that will be executed when the request is complete (and only if the response has a successful response code).
If you need to have both error and success callbacks, you may want to use $.ajax.
so your modified code in that case would be

Code: Select all

 
    $.ajax({
  url: 'test.php',
  success: function(){
    alert('success');
  },
  error: function(){
    alert('failure');
  }
});
 
 

Re: Ajax request with JQuery

Posted: Fri Apr 24, 2009 8:14 am
by Sindarin
Thanks, it works great!
I also noticed the beforeSend function, which is really useful to set the starting/activity state (loader image etc.).