Reputation: 181
I have a ajax function which gets some graph data from a database. It works fine but I want to make it generic.
function getGraphData() {
$.ajax({
url: "/wordpress/wp-admin/admin-ajax.php",
method: "POST",
data: { action: "databaseName" },
success: function (response) {
//Some code;
}
})
}
So to make the function generic I need to pass a database name to the function instead of hard code it but I can't seems to get it to work.
I changed the code to this:
Function call:
var dbname = "action: " + "mydatabase";
getGraphData(dbname);
Changed function:
function getGraphData(database) {
$.ajax({
url: "/wordpress/wp-admin/admin-ajax.php",
method: "POST",
data: database,
success: function (response) {
//Some code;
}
})
}
Where do I go wrong ??
Regards Flemming.
Upvotes: 1
Views: 10375
Reputation: 53
You can pass the full object:
db = { action: "myDatabase" };
getGraphData(db);
function getGraphData(dbObject) {
$.ajax({
url: "/wordpress/wp-admin/admin-ajax.php",
method: "POST",
data: dbObject,
success: function (response) {
//Some code;
}
})
}
OR (if the object is always the same) simply pass the actual database name:
name = "myDatabase";
getGraphData(name);
function getGraphData(dbName) {
$.ajax({
url: "/wordpress/wp-admin/admin-ajax.php",
method: "POST",
data: { action: dbName },
success: function (response) {
//Some code;
}
})
}
Upvotes: 0
Reputation: 182
try passing just the value
getGraphData("mydatabase");
function getGraphData(database) {
$.ajax({
url: "/wordpress/wp-admin/admin-ajax.php",
method: "POST",
data: { action: database },
success: function (response) {
//Some code;
}
})
}
Upvotes: 0
Reputation: 371
function getGraphData(database) {
$.ajax({
url: "/wordpress/wp-admin/admin-ajax.php",
method: "POST",
data: {action: database}, <-- change this line
success: function (response) {
//Some code;
}
})
}
Upvotes: 1
Reputation: 9359
Doing "action: " + "mydatabase"
doesn't create an object, it creates a string. The output of that would be:
"action: mydatabase"
What you want is the following:
{ "action" : "mydatabase" }
You need to do something like:
var dbname = { action :"mydatabase" }
Combining your function into a full example, it would be like this:
var database_name = "database1";
var data = { action : database_name }
getGraphData(data);
// Your original function
function getGraphData(database) {
$.ajax({
url: "/wordpress/wp-admin/admin-ajax.php",
method: "POST",
data: database,
success: function (response) {
//Some code;
}
})
}
Upvotes: 4