0

So Ive seen AJAX syntax done two different ways. Seems like on the boards here everyone uses the format like this:

$.ajax({
type: 'POST',
url: 'mm.php',
data: { color: color},
success: function (res) {

},
error: function (jqXHR) {

}

But my text uses

$.post('mm.php', data, processResponse);

Is there a difference and what is preffered?

2
  • 1
    The latter is just a shorthand syntax Commented Mar 4, 2013 at 23:30
  • 1
    Visit api.jquery.com - enjoy. Personally, I use deferred objects for jQUery AJAX request event handling. I find it works better across single-purpose functions and allows composition via then. Commented Mar 4, 2013 at 23:31

2 Answers 2

1

This is a shorthand Ajax function, which is equivalent to:

$.ajax({
  type: "POST",
  url: url,
  data: data,
  success: success,
  dataType: dataType
});

[http://api.jquery.com/jQuery.post/]

Sign up to request clarification or add additional context in comments.

4 Comments

Ah. I guess what I dont recognize is why there is a data AND a datatype
it depends on datatype of data (You have to omit it, if you dont know what kind data are you sending, but it is better to choose one - as a string), from original documentation: The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). api.jquery.com/jQuery.ajax
oh. So you would do something like dataType: text if you were expecting an array output from a PHP page?
dataType: The type of data that you're expecting back from the server. Please, use quotes - it is a string: "text": A plain text string. dataType: "text"
1

Would it help to understand with this form:

$.ajax({
    type: 'POST',
    url: 'mm.php',
    data: { color: color},
    success: processResponse,
    error: function (jqXHR) {
    }
});
  • basically the .post is a shorthand for the long version of .ajax

EDIT PER COMMENT:

var color = "red";
var mydata = {color: color};

$.ajax({
    type: 'POST',
    url: 'mm.php',
    data: mydata,
    success: processResponse,
    error: function (jqXHR) {
    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.