skip to Main Content

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();

2

Answers


  1. Chosen as BEST ANSWER

    Latest Changes: added wordpress_logged_in to cookie, changed req.write to req.write(data); added content type: urlencoded and change data to url encoded


  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search