Richard Knop
Richard Knop

Reputation: 83677

jQuery ajax() vs get()/post()

Let's say I want to execute a PHP script. Which way is better?

This:

$.ajax({
    type: "GET",
    url: "php-script.php",
    dataType: "script"
});

Or this:

$.get("php-script.php", function(data) { });

Upvotes: 37

Views: 17127

Answers (3)

Jan
Jan

Reputation: 52

$.get()/$.post() don't support beforeSend like $.ajax() does. So you can't for example display a spinner while loading directly. But you can do this with .ajaxStart().

Upvotes: 2

Darko
Darko

Reputation: 38860

$.get() is just a shortcut for an $.ajax() call of type "GET".

To Elaborate $.get() just calls $.ajax() in the background. Its a shortcut kind of like what $(function(){}) is to $(document).ready(function(){}). Common use cases for $.get is for a quick and simple get, $.ajax should be used if you need to do something a bit more complex or if you need the extra flexibility.

Upvotes: 23

Stefan Kendall
Stefan Kendall

Reputation: 67802

In this case, I'd say $.get, as it's immediately clear what the type of request is. At any rate, it's just shorthand for the larger and more option-ified ajax call, and converting between the two is trivial in the worst case.

If you think that you'll need fancy $.ajax options, use $.ajax. If you don't use the convenience methods jQuery provides, such as .load, $.get, etc.

Upvotes: 29

Related Questions