1

As the title implies I'm looking for a better way to pass data parameters in jquery. I'm relatively new to jquery and do most of my Ajax like this:

$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", city: "Boston" });

It's ok if I'm passing a couple of parameters but once it gets to more than five it gets a bit ugly. Is there a better way?

Thanks David

David
  • 209
  • 4
  • 17
  • Seems fine to me, why does it get ugly passing an object? You could create the object outside the $.ajax function if that makes you happier ? – adeneo Apr 03 '14 at 22:01
  • Hi Adeneo, yeah as Buzinas states below creating the object outside of the call was the answer I was looking for. – David Apr 03 '14 at 22:04

3 Answers3

0

You can use .serialize()

$.ajax({
    type : 'POST',
    url : 'url',
    data : $('YOUR_FORM').serialize() 
}

Read more about it here

0

If you prefer, you can create this object before calling your AJAX method:

var myParams = {};
myParams.name = "John";
myParams.city = "Boston";
// (...)

$.ajax({
    type: "POST",
    url: "some.php",
    data: myParams
});
Buzinas
  • 11,597
  • 2
  • 36
  • 58
0

BTW, I think you are missing a {

If you have too many parameters you should consider this answer. If it is a form you can serialize as already suggested. If you just want to keep it out of the ajax call you can do:

var info = {
    name: "John", city: "Boston"
};

$.ajax({
type: "POST",
url: "some.php",
data: info});
Community
  • 1
  • 1
acarlon
  • 16,764
  • 7
  • 75
  • 94