Posted By

daisyfig99 on 03/13/13


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite


Ajax Request and Handler using jQuery & JSfiddle

 / Published in: jQuery

This is how to make an Ajax request using jQuery. This code is meant to be tested in JSfiddle, however it can easily be adapted for anyone's needs.

1) Makes an AJAX request & tell it where to grab the data from. 2) If request has failed, a message will displayed. 3) If the request was successful, gets the data and then it displays the filtered data.

  1. var aRequest;
  3. //Makes an AJAX request
  4. aRequest = jQuery.ajax({
  5. type: "POST",
  6. url: "/echo/html/", //change this to desired path. this is for testing ajax in JSfiddle.
  8. //this data section is only used for testing. remove once url has been changed.
  9. data: {
  10. html: "<div id='dataId'><p>Test data</p></div>"
  11. }
  13. });
  15. {
  16. //Good place to tell the user to try again or you got some debugging to do.
  17. console.log("A request has failed.");
  18. });
  20. //Handles all the data coming in.
  21. aRequest.done(function(data) {
  22. //finds certain id plus what it contains as plain text.
  23. var pieceOfData = jQuery(data).filter("#dataId").text();
  25. //displays the filtered data back to you
  26. console.log( "Here's the data you requested: " + pieceOfData);
  27. });

Report this snippet  

You need to login to post a comment.