i want to post to wordpress on nodejs using admin-ajax.php which set some actions to use. But i get statusCode:400 and 0, i don't know so much about wordpress and ajax. I tried use a cookie from the worked project from wordpress that what i want to transfer nodejs How can i set up this?
const https = require("https");
const data = {
action: "create_chapter",
postID: "2676",
chapterName: "2",
chapterContent: "test",
};
const options = {
hostname: "www.website.com",
path: "/wp-admin/admin-ajax.php",
method: "POST",
headers: {
"Cookie": "cookies",
"X-Requested-With": "XMLHttpRequest",
},
};
const req = https.request(options, (res) => {
console.log(`statusCode: ${res.statusCode}`);
res.on("data", (d) => {
process.stdout.write(d);
});
});
req.on("error", (error) => {
console.error(error);
});
req.write(JSON.stringify(data));
req.end();
CodePudding user response:
To make ajax work in wordpress you need to instruct wordpress about what it should do when he receive your ajax request.
To do so you need to use something like this:
add_action( 'wp_ajax_create_chapter', 'create_chapter' );
if you need that to work for non-logged in user you need this in addition:
add_action( 'wp_ajax_nopriv_create_chapter', 'create_chapter' );
the "nopriv" just means it's open for everyone. You need to paste this code into your current active theme functions.php file or in a custom plugin you could make.
After you called the "add_action" you just need to create a function like this:
function create_chapter(){
// Code goes here
}
The 400 error and 0 response usually means wordpress didn't find any action to fire so it just gives that error
If you want to learn more just read the full documentation from the wordpress site
CodePudding user response:
Latest Changes: added wordpress_logged_in to cookie, changer req.write to req.write(data); added contenent type: urlencoded and change data to url encoded