The Zurich release has arrived! Interested in new features and functionalities? Click here for more

How to stop submission of a form based on the value returned by an asynchronous callback ?

PriyaVerma
Tera Contributor
I have written following code in Catalog Client Script. I want to stop submit record based on the value returned by ValidateAttachment. If ValidateAttachment returns false, I am using return false (to stop submit record). But this is not working as the issue is: Script continues to submit record before the callback returns response. 
 
 
 function onSubmit()  
{
      var id = '50eebf051bff35501738eb17ec4bcb59';
    // var id = g_form.getUniqueValue();
 
    // AJAX call to the server-side script include
    var ga = new GlideAjax('NGRPPortalUtilAjax');
    ga.addParam('sysparm_name''validateAttachment');
    ga.addParam('sysparm_app_id', id);
    ga.getXML(ValidateAttachment);
 
}

 

function ValidateAttachment(response)
{
    var answerFromXML= response.responseXML.documentElement.getAttribute("answer");
    var result = JSON.parse(answerFromXML);
    if(result=='true')
    {
        alert('Valid Insert' + result);
        return true;
    }
    else
    {
         alert("Please upload valid format" + result);
         return false;
    }
}
1 REPLY 1

Aniket Chavan
Tera Sage
Tera Sage

Hello @PriyaVerma ,

Please give a try to the script below and let me know how it works for you.

function onSubmit() {
    var id = '50eebf051bff35501738eb17ec4bcb59';

    // AJAX call to the server-side script include
    var ga = new GlideAjax('NGRPPortalUtilAjax');
    ga.addParam('sysparm_name', 'validateAttachment');
    ga.addParam('sysparm_app_id', id);

    // Set the callback function
    ga.getXML(ValidateAttachmentCallback);
    
    // Return false to prevent the form submission
    return false;
}

function ValidateAttachmentCallback(response) {
    var answerFromXML = response.responseXML.documentElement.getAttribute("answer");
    var result = JSON.parse(answerFromXML);
    
    if (result == 'true') {
        alert('Valid Insert' + result);
        // If validation passes, submit the form
        g_form.submit();
    } else {
        alert("Please upload valid format" + result);
        // If validation fails, do not submit the form
    }
}


Please let me know your views on this and Mark
Correct if this solves your query and also mark 👍Helpful if you find my response worthy based on the impact.

 

Thanks,

Aniket