Cris
Cris

Reputation: 4044

jQuery Ajax - json datatype, send more than 1 parameter?

I have the ajax call:

$.ajax({
    url: '/articles/moveArticle/' + article.id,
    type: 'POST',
    dataType: 'json',
    success: function(result) {
    console.log(result);
         //something
    },
    error: function (result) {
    }
});

The php function that gets called by the ajax is:

function moveArticle ($articleId) {
  // move it
}

This works great but how do I send more than 1 parameter?

Upvotes: 0

Views: 471

Answers (3)

Linek
Linek

Reputation: 1363

Use data parameter in your ajax call.

https://api.jquery.com/jQuery.ajax/

EDIT

As I read other answers I have decided to enhance my answer.

dataType parameter as stated in jQuery documentation stands for:

The type of data that you're expecting back from the server.

Which means you are expecting JSON data from the server. If you set dataType to json it does NOT mean you are sending a JSON object to the server.

There is a parameter in ajax call that you have set, it is type. This parameter states how you are going to send the data to server. You have used a POST method. It means that anything set in the data is accessible by PHP from the $_POST array

$.ajax({
    url: '/articles/moveArticle/' + article.id,
    type: 'POST',
    dataType: 'json',
    data: {
        something: 'Something that can be accessed by PHP as $_POST["something"]',
    },
    success: function(result) {
    console.log(result);
         //something
    },
    error: function (result) {
    }
});

Upvotes: 1

neel shah
neel shah

Reputation: 2271

You can create an object and then pass it in the data property of ajax call using JSON.stringify(data)

var data ={
    id : article.id,
    name : article.name // other parameters
} 

$.ajax({
    url: '/articles/moveArticle',
    type: 'POST',
    dataType: 'json',
    data = JSON.stringify(data),
    success: function(result) {
    console.log(result);
         //something
    },
    error: function (result) {
    }
});

Upvotes: 2

yossi
yossi

Reputation: 3164

By the function moveArticle, I guess you use some php framework.
Without knowing which one - it is impossible to answer.
From the structure of the function - i assume that it uses routing - so it's not a POST request (that is why i ignored the use of data as others mentioned).

So, my best guess is:

$.ajax({
    url: '/articles/moveArticle/' + article.id + '/' + anotherParameter,
    type: 'POST',
    dataType: 'json',
    success: function(result) {
    console.log(result);
         //something
    },
    error: function (result) {
    }
});


function moveArticle ($articleId, $theOtherParameter) {
  // move it
}

Upvotes: 1

Related Questions