Ask JW: How do I Make AJAX Requests With jQuery?

This week’s email question comes from Mohammed. He’d like to learn more about how to create AJAX request with the jQuery library. We’ll be reviewing the $.get and $.ajax methods.



Be sure to click on the “Full Screen Toggle”.

Sample Code From Video

<script type="text/javascript">
//$.get('pageToLoad.php', '', function(responseText) {
	//$('#container').text(responseText);
//});
 
 
//$('#container').load('pageToload.php');
 
$('#submit').click(function() {
	var name = $('#name').val(); // Jeffrey
	$.ajax({
		url: 'pageToLoad.php', 
		data: 'firstName=' + name,
		type: 'GET',
 
		success: function(results) {
			console.log(results);
		}
	});
 
	return false;
 
});
</script>



29

Comments
  • Sirwan says:

    Jeffrey Way all time legend!

  • Very clear, very easy to follow. I was wondering though: how would you check for that xmlhttprequest header?

  • Ionut Staicu says:

    Without watching the video, i have a small thing to add:

    $.ajax({
    		url: 'pageToLoad.php', 
    		data: {firstName:name},

    is the preffered method, especially when you have multiple parameters to send. I guess is more elegant ;)

  • Uzm says:

    Hey Jeffrey, i was wondering, what dock-program are you using? :) ) A little bit offtopic probably, but…

  • Robert DeBoer says:

    I think it is great that JQuery makes AJAX so easy, but a problem I have run into myself is having to make AJAX calls without any sort of javascript library support at all. I think it would be great to see a tutorial or two on AJAX (with JSON possibly) request using nothing but from scratch Javascript. Sometimes we are limited in what we can use with projects, and sometimes this means no Javascript library other than the one we write ourselves.

  • Crysfel says:

    @Robert DeBoer
    There is a LOT of tutorials on internet about making ajax request with plain javascript, just google it.

  • Jeffrey says:

    @Robert – Tomorrow’s screencast on Nettuts+ covers that very thing!

  • James says:

    @Uzm

    Was just going to ask the same question!

  • Ian says:

    I hope this formatting works. If not, sorry.
    @Bram
    Try this:
    $requestType = reqType();

    function reqType(){
    if ($_SERVER['HTTP_X_REQUESTED_WITH']) {
    if ($_SERVER['HTTP_X_REQUESTED_WITH'] == ‘XMLHttpRequest’) {
    return “Ajax”;
    }
    }
    return “not Ajax”;
    }
    @uzm
    He mentioned RocketDock in another post I think.

  • I’ve been building projects with this method for a few months now and suddenly ran into a problem with a project where the data loads fine in FF and Safari, but not in IE6 or 7. If I do an alert dialogue box it shows the data, but it does not load into the div.

    Any theories?

  • Jeffrey says:

    John – Seems familiar. Code snippet would help. :)

  • Ian Graham says:

    Hey jeffrey,
    I’ve been playing with the $.ajax for a couple weeks now and am really enjoying it. One question I have is how do you get around having to write duplicate content in your PHP file?
    Lets say you have two pages set up, the home page, and the about us page. if javascript is turned off it loads the page like normal with the header, footer etc. if javascript is turned on just pull in the main content of the page without the header and footer?
    The only way i can think to do it is to do this:
    if($_SERVER['x-requested-with']){

    just the main content
    }else{

    load whole page
    }

    I’ve looked at a few tutorials on it but none of them go that far into depth
    thanks

  • James says:

    @ Jeff

    Just wanted to recommend a program called “phpDesigner”, I’ve seen your other videos but wasnt sure if you’ve used it.

    It’s truely awesome for php (and other langs) has tons of features and easy to manage your projects.

    I downloaded it yesterday and its truely awesome!

    You should give it a try

  • @Jeff – here’s the ajax call:

    function getPrayers(date){
    $.ajax({
    type: ‘POST’,
    url: ‘includes/forms/get-prayer.php’,
    data: ’setdate=’+ date,
    success: function(data){
    $(‘#added-prayers’).html(data);
    prayerDetails();
    }
    });
    };

    getPrayers(‘today’);

    Today replaces with the current date in the php file.

    It loads great when I alert(data), but won’t show. You can check out the dev site at dev.bestill.com, user name and password is demo.

  • Priyanshi says:

    @john

    There should be a div of id added-prayers.

  • Jelte says:

    Hey Jeffrey,

    I really like this tutorials, I learn much from it (as a beginner in php/ajax/jquery)!
    Thanks!

    Off topic: I was wondering, how you did you make “beginhtml” work in Intype? I only get two lines of code and that’s only because of the word “html”…

  • Adam says:

    Hi, I have a question. Let’s say I can’t use special chars in the URL (?, & etc). The method you wrote about automaticlly adds the ? sign. I don’t want it, I tried to do:
    [code]
    $.ajax({
    url: 'http://visionize.co.il/check/main/',
    data: 'user/' + name,
    type: 'GET',

    success: function(results) {
    console.log(results);
    }
    });
    [/code]
    Didn’t work out. What can I do?

  • @Priyanshi – got me one of them;)

  • @Adam – It’s a little less robust, but you can use $(‘target-div’).load(‘http://visionize.co.il/check/main/user/’+name);

    That simply loads whatever is on your page without handling any errors (at least that I know of).

  • Love using AJAX with jQuery! Would love to see some videos dedicated to using JSON. Keep up the great videos!

  • alin says:

    i’m interested how the xml responses can be handled with jquery, when you have the time maybe you can talk about this to

  • Saurabh says:

    Hi

    How can we do the same thing with Asp.Net

    Please put same example with Asp.Net

    Kind Regards,
    Saurabh

  • seeal says:

    Hi Jeffrey,

    I really like this tutorials.

    thanks ^^

  • SarmenHB says:

    i noticed you place id’s into each input types before you call them through jquery. to save yourself time you can also do

    and in jquery you can type

    var name = $(‘input[name=myname]‘).val();

    and it works perfectly :)

  • SarmenHB says:

    i noticed i cant type html.
    i meant to type

  • solow says:

    I keep getting an error… object expected… hm…

  • iam says:

    instead i used

    complete:function(){
    $(‘#loading’).fadeOut(500,function(){
    $(‘#container’).append(‘Your comments are being saved’);
    $(this).remove();

    $(‘#response’).fadeOut(2000);
    $(‘#submit’).hide();

    });
    }

  • Daniel Johansson says:

    Hi! I really enjoy your tutorials Jeff! specially the series you hav here on themeforest but i’ve also watched the ajax with raw javascript-tutorials over at nettuts. thougt they were very instructive! that made me think that it would be really, really nice if you did a raw javascript-series here at themeforest. for people like me who have got stuck in a framework
    thanks!

  • Sylvin says:

    Nice Tutorial, thanks for explanations !

    I just wonder why you use GET in .ajax, POST sounds better, will check out if it is more complex with POST method