jqueryhtmlreactjsrails-ujs

Run function after jquery ujs submits remote form


    <form method='delete' data-remote='true' action={'/analysis_items/' + this.props.item.id}
      onSubmit={this.props.loadPathwayData}
    >
      <button type='submit' />
    </form>

I have this form in React + Rails. When the form is submitted jquery ujs sends the request and the onSubmit is run correctly but the onSubmit is run before the form is sent and I need it to run after. Is there any way to achieve this with jquery ujs?


Solution

  • you ultimately have two submit actions on your form, one is the action and one is the onSubmit code event. Instead you could remove the action and just do everything in clientside JS.

    For example if you want to use jQuery.

    submitForm(e) {
        // don't submit form to server (page reload)
        e.preventDefault()
        // jquery to make delete request instead of form submit
        $.ajax({
            url: '/analysis_items/' + this.props.item.id,
            type: 'DELETE',
            success: function(result) {
                // then run your previous onSubmit js code
                this.props.loadPathwayData()
            }
        });
    }
    

    and your form could be like this:

    <form onSubmit={submitForm}>
        <button type='submit' />
    </form>