Ajax request with JQuery

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
User avatar
Sindarin
Forum Regular
Posts: 521
Joined: Tue Sep 25, 2007 8:36 am
Location: Greece

Ajax request with JQuery

Post 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>
miyur
Forum Newbie
Posts: 15
Joined: Sat Jan 10, 2009 9:06 am

Re: Ajax request with JQuery

Post 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');
  }
});
 
 
User avatar
Sindarin
Forum Regular
Posts: 521
Joined: Tue Sep 25, 2007 8:36 am
Location: Greece

Re: Ajax request with JQuery

Post 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.).
Post Reply