Home > Enterprise >  How to pass form data from javascript event listener to Flask_WTFoms
How to pass form data from javascript event listener to Flask_WTFoms

Time:10-16

I have a JavaScript event listener which is called to display a modal window when a form is submitted to confirm that the action should go ahead. In the event listener I call this function to display a modal. If the positive action is selected then we call event.target.form.submit(); to carry on submitting the form.

  function confirm_delete_submit(event) {
  // prevent the default form submit action
  event.preventDefault()

  // Use modbox to display the confirm modal
  modbox.confirm({
    title: 'Confirm delete',
    center: true,
    body: 'Do you want to delete this question?',
    okButton: {
      label: 'Delete',
      size: 'sm'
    },
    closeButton: {
      label: 'Cancel',
      size: 'sm'
    }
  })

  // The positive action was chosen
  .then(() => {
    // Submit the form
    event.target.form.submit(); 
  })

  // The negative action was chosen so do nothing
  .catch(() => console.log('No delete'));
}

If I try to read the form data using the request object, for example

value = request.form.get("delete")

to read the value of the 'delete' field then everything works OK

However, if I try to read the form data using the wtf_forms code:

value = form.delete.data

then nothing is received.

Ideally I'd like to do everything with the WTForms methods for consistency across my site.

Any advice much appreciated

NOTE: Edited to include the full JavaScript event listener function

CodePudding user response:

Use FormData to fill in the fields for you form and then post.

const formData = new FormData();

formData.append("delete", "yes");
formData.append("something", "somethingElse");

const request = new XMLHttpRequest();
request.open("POST", "http://yoururl");
request.send(formData);

of course you can combine with jinja if you're using flask.

  • Related