简体   繁体   中英

Error 403 when submitting constructed form in JQuery

I'd like to construct and send a form when a button is clicked:

$(document).on('click', '.btn-follow', function () {
  let _self = this;
  let token = $('.token').val();
  let username =$('.username').text();
  let form = `<form  method="post">
      <input name="token" value="${token}">
      <input name="flwd" value="${username}">      
    </form>
  `
  console.log('form to submit is:', form);
  $.ajax({
    url: "/follow",
    type: 'post',
    data: form,
    success: function (res) {
      console.log('followed successfully', res)
    },
    error: console.log('an error occured')
  });
});

And the constructed form is logged as:

form to submit is: <form  method="post">
      <input name="token" value="bjT2rjk6dfefCWQ68Y31VwS8K2DHl8jYjK">
      <input name="followed" value="Bob">      
    </form>

However I get 403 error in response, despite the fact that the backend is presumably set up correctly to deal with such POST requests.

What could be wrong here and how can I fix it?

Try changing your code to this:

  $.ajax({
    url: "/follow",
    type: 'post',
    data: $(form).serialize(),
    success: function (res) {
      console.log('followed successfully', res)
    },
    error: console.log('an error occured')
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM