How to Make AJAX Requests w/ jQuery

An introduction to GET and POST with AJAX

When should you use Ajax?

When should you use Ajax?

The short answer: for a more seamless experience.

Ajax with jQuery is the new way to sizzle up the old system.
Ajax with jQuery is like offering a really nice hotel room.

When should you use Ajax?

Anytime you want to:

  • Avoid a page reload
  • Grab optional data after page load
    • Then use the returned data on the page
  • Create a more interactive UI
    • Attempt to submit a form

WHAT is Ajax?

Set of frontend technologies

Grab another page, feed, api, etc invisibly

jQuery will handle cross browser issues

We used it before with XMLHttpRequest

AJAX: Asynchronous Javascript And XML.

Why jQuery today?

1 CDN link to include it

Easier to read

Very popular/widespread

Look for things with great docs or communities.

So let's do it

Open your text editor of choice.

Let's make some GET and POST Ajax Requests today

Grab the starter files for this project

Go to: github.com/sprise/jquery-ajax

In this project:

  • HTML all ready to go (index.php)
  • A scripts.js file that we are going to fill in together
  • PHP file to handle GET requests
  • PHP file to handle POST requests

Pssst: hit the down arrow next

1. Let's detect the dropdown choice


// GET request, populate products
$('select#your-industry').change(function(){
  console.log('You changed the dropdown to '+$(this).val());
});

2. Set up a $.get call


// GET request, populate products
$('select#your-industry').change(function(){
  var url = window.location.href+'get-api.php';
  
  $.get(url, function(data){
    console.log(data);
  });
});

3. Start the Query String


// GET request, populate products
$('select#your-industry').change(function(){
  var url = window.location.href+'get-api.php?key=my-api&industry='+$(this).val();
  
  $.get(url, function(data){
    console.log(data);
  });
});

4. Parse JSON if needed, show error


// GET request, populate products
$('select#your-industry').change(function(){
  var url = window.location.href+'get-api.php?key=my-api&industry='+$(this).val();
  
  $.get(url, function(data){
    if(typeof data == 'string') data = JSON.parse(data);

    // Not successful
    if(data.success === false){
      if(data.msg) $('select#your-industry').after('<p class="error">'+data.msg+'</p>');
      else $('select#your-industry').after('<p class="error">Error - please try again.</p>');
      return;
    }

  });
});

4.5 Add one more query string param

Now we at least know what will happen in an error.


// GET request, populate products
$('select#your-industry').change(function(){
  var url = window.location.href+'get-api.php?get_photos=true&'+
	'key=my-api&industry='+$(this).val();

5. We're expecting data.images


  $.get(url, function(data){
    if(typeof data == 'string') data = JSON.parse(data);

    // Not successful
    if(data.success === false){
      if(data.msg) $('select#your-industry').after('<p class="error">'+data.msg+'</p>');
      else $('select#your-industry').after('<p class="error">Error - please try again.</p>');
      return;
    }
    
    // Did we get the data we were expecting?
    if(!data.images) {
      alert('Images not defined.');
      return;
    }
  });
});

6. Handle successful image grab


    // Did we get the data we were expecting?
    if(!data.images) {
      alert('Images not defined.');
      return;
    }
				
    // Yes, we got the images array - add it to the page
    $('#products').html(''); // blank it

    for(var i = 0; i < data.images.length; i++){	
      var html = '<div class="col-sm-4"><img src="https://source.unsplash.com/'+
        data.images[i]+'/300x168" class="imgscale" /><div class="form-group">'+
        '<label><input type="checkbox" name="images[]" value="'+data.images[i]+
        '" /> Buy This Image for $1</label></div></div>';

      $('#products').append(html).closest('form').fadeIn();
    }

  });
});

Test your GET request

Lookin' good?

7. Detect the form submit event


    $('form').submit(function(e){
      e.preventDefault();
      console.log('You tried to submit the form');
    });
    
  });
}); // end of (function(){ })(jQuery)

8. Prepare the data to send


    $('form').submit(function(e){
      e.preventDefault();
      
      // Prepare our variables to send
      var post_vars = {
        crsf_token:	$('input[name="crsf_token"]').val(), 
        items: 		[], 
        ajax_order: true
      };

      $.each($("input[name='images[]']:checked"), function(){            
        post_vars.items.push($(this).val()); // Add all checked images
      });
    });
    
  });
}); // end of (function(){ })(jQuery)

9. Let's create that $.ajax request


      $.each($("input[name='images[]']:checked"), function(){            
        post_vars.items.push($(this).val()); // Add all checked images
      });
      
      $.ajax({
        type: 	"POST",
        url: 	window.location.href+'post-handler.php',
        data: 	post_vars,
        success: function(data){
          console.log(data);
        }
      }).fail(function(){
        alert('Ouch, failed'); // the endpoint could not be reached
      });
      
    });
    
  });
}); // end of (function(){ })(jQuery)

10. Did we get what we expected?


      $.ajax({
        type: 	"POST",
        url: 	window.location.href+'post-handler.php',
        data: 	post_vars,
        success: function(data){
          if(typeof data == 'string') data = JSON.parse(data); 

          if(data.success === false){
            if(data.msg) alert(data.msg);
            else alert('Something went wrong.');
            return;
          }

          console.log(data);
        }
      }).fail(function(){
        alert('Ouch, failed'); // the endpoint could not be reached
      });
      
    });

11. Handle successful submit


        success: function(data){
          if(typeof data == 'string') data = JSON.parse(data); 

          if(data.success === false){
            if(data.msg) alert(data.msg);
            else alert('Something went wrong.');
            return;
          }

          // Show receipt
          if(!data.msg) data.msg = 'RECEIPT GOES HERE';
          $('form').hide().after(data.msg);
          $('select').hide();
        }
      }).fail(function(){
        alert('Ouch, failed'); // the endpoint could not be reached
      });

12. Test in the browser

Open up F12 developer tools, choose Console panel, watch the requests.

Next Time:

What's going on in those PHP scripts?

Is there something really cool or useful you could be using AJAX for?

The answer is yes, so start nibbling on it.

Do you need to be well versed in asynchronicity, xml, and javascript to use it?

No you do not! Learn by doing.

Make some personal projects and fiddle with it.

What Next?

  • Work some Ajax magic into your projects
  • Use these slides for your own presentation
  • Let me know if you enjoyed this!
    Github stars, upvotes, emails, shares, comments all welcome.