user3481788
user3481788

Reputation: 149

How can I add more variables to this ajax post...?

I am making a game and I need to send some variables via a post request to a leaderboards page.

This is my current post code:

var toDatabase = confirm('Do you want to save your score to the database?');
if (toDatabase) {
    $.post("leaderboards.php", {"Level1": "Level1"}, function() {
    window.location.href="leaderboards.php";
});
} else {
    $.post("gameL2.php", {"Level1": "Level1"}, function() {
      window.location.href='gameL2.php';
    });
}

This top code linking to the leaderboards.php file is the one I wish to add more variables too. How can this be done? Do I add a new pair of curly braces?

Upvotes: 0

Views: 74

Answers (4)

Callum Linington
Callum Linington

Reputation: 14417

If you have a base object you wish to send, and it only gets added two in the two different events happening to then you can use jQuery.extend

var baseObj = {
   Level1: "Level1"
}

if (toDatabase) {
    $.extend(baseObj, { complete: true });
}else{
    $.extend(baseObj, {doSomething: "yeah" });
}

This takes the idea of just adding another key/val pair a bit further and more flexible

Upvotes: 0

James Montagne
James Montagne

Reputation: 78670

The 2nd parameter is simply an object:

$.post("leaderboards.php", {"Level1": "Level1", "abc": "def", "num": 123}, function() {

Just separate with commas

Upvotes: 1

Ko Cour
Ko Cour

Reputation: 933

You will just add more variables to your data object.

if (toDatabase) {
    $.post("leaderboards.php", {"Level1": "Level1","variable1":0,"variable2":"value","variable3":546}, function() {
    window.location.href="leaderboards.php";
});

And so on.

Upvotes: 1

tymeJV
tymeJV

Reputation: 104785

Data is sent via an object, just add another key/val:

$.post("leaderboards.php", {"Level1": "Level1", "anotherKey": "anotherVal"}, function() {

Upvotes: 4

Related Questions