0

I have no idea about how to get Axios call success response and display a success message.

There is a button called Change Workflow Order and it has a onClick function.

<div style="display: flex">
    <button class="btn btn-info change-workflow" onclick="changeWorkflowOrder()">
        Change Workflow Order
    </button>
    <span style="color: green; margin-left: 5px;" id="alert_msg"> </span>
</div>

This is the onClick function. changeWorkflowOrder function runs an Axios call.

function changeWorkflowOrder() {

    const response = axios.post(js_site_url + '/sort-detail', $('#sortable').sortable("toArray"), {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    })
}

I want to catch Axios call success response and if Axios call response is successful, display the success message in the HTML span tag. The message must display for only 4 seconds. After 4 seconds success message must be hidden.

I tried to create that. Here is I tried changeWorkflowOrder function.

function changeWorkflowOrder() {
    const response = axios.post(js_site_url + '/sort-detail', $('#sortable').sortable("toArray"), {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    });

    response.then((result) => {
        $("#alert_msg").html(result.data.success ? "Success" : "Order change successfully");

        clearTimeout(timeoutId);

        timeoutId = setTimeout(function() {
            $("#alert_msg").hide();
        }, 4000);
    });
}

This code show error message properly. but after 4 second showing error message, "Order change successfully" message not hidden and I think Axios call response catching part is not correct.

How I catch response of Axios call and Display success message in HTML span tag for 4 second.

1 Answers1

0

I would suggest starting with creating an axios client for your api/webservice:

import axios from 'axios';

export const myApiClient = axios.create({
  baseURL: '...' /* in your case this would be js_site_url */,
  headers: {
    'Content-Type': 'multipart/form-data' /* this can of course be overwritten in any specific instance call to the this client */
  }
});

Then rewrite your onclick function and implement delay referencing this Stack Overflow answer:

import {myApiClient} from '...'; /* import your client if you decide to store it in a separate file */

const delay = ms => new Promise(res => setTimeout(res, ms));

async function changeWorkflowOrder() {
    const myPostData = $('#sortable').sortable("toArray");
    return await myApiClient.post('/sort-workflow-detail-manage', myPostData)
        .then(await res => {
            const alertMsg = res.data?.success ? 'Success' : 'Order changed successfully';
            $("#alert_msg").html(alertMsg);
            await delay(4000).then(_ => $("#alert_msg").hide());
        })
        .catch(err => /* handle failing api requests here*/);
}