Trigger A SharePoint Workflow From JavaScript

Intro

Sometimes, we get the requirement to start a SharePoint workflow from JavaScript code or have to rerun a work on all existing list items and want to give an easy option to users to trigger a workflow on all items, then this the solution will help you. We’re basically triggering a workflow from JavaScript code and you have the option to rerun workflow on all items or on a few items based on your requirement. Prerequisites We need SPServices JS file reference to use this solution and I think we can use SharePoint REST API as well to trigger a workflow. But you need to update code a little bit and REST API endpoints may not work with SP2010. 

Steps

 Save the below code in a text file by updating the global variable to point out to the List, Workflow name, and Workflow Template ID. I selected all items to trigger workflow but if you have to filter the result then update query in REST call. I used logging to make sure the code runs correctly. You may discard the console logging if you want. Update the HTML code block as I have used <span> to show a message and a button to trigger a JavaScript function, you can update it as per your need. Finally, upload this text file to the Site assets folder of your SharePoint site and refer it in the content editor web part to render the HTML and code on-page. 

Code

< !DOCTYPE html > < script > < /script> / / add the SPService webservice reference here..... < script type = "text/javascript" >  
    //global variables  
    var workflowName = ""; //Name of your workflowName  
var listName = ""; //list name on which workflow is configured  
var listGUID = ""; // list listGUID  
var tempalteID = ""; //Workflow temaplte id, you will get this tempalte id and list guid both on workflow start page.  
//This function will trigger on button click and itemrate on items of mentioned list to start workflow.  
function RunWorkflow() {  
    var context = SP.ClientContext.get_current();  
    if (context != null) {  
        $.ajax({  
            async: true,  
            //you can use either one method - getbytitle() or getbyid() to get list items from list.  
            url: _spPageContextInfo.webAbsoluteUrl + "/api/web/lits/getbyid(guid'" + listGUID + "')/items/?$top=1500,  
            //url: _spPageContextInfo.webAbsoluteUrl +"/api/web/lits/getbytitle('"+listName +"')/items/?$top=1500,  
            method: "GET",  
            headers: {  
                "accept": "application/json;odata=verbose",  
                "content-type": "application/json;odata=verbose"  
            },  
            success: function(data) {  
                if (data != null || data !== "" || data !== undefined) {  
                    console.log("Total item count is:" + data.d.results.length);  
                    for (var i = 0; i < data.d.results.length; i++) {  
                        var item = data.d.results[i];  
                        console.log("workflow starting on item: " + item.ID);  
                        //calling function to pass item id to start workflow instance on it.  
                        startWorkflow(item.ID);  
                    }  
                }  
            },  
            error: function(error) {  
                JSON.stringify(error);  
            }  
        })  
    }  
}  
//this function triggers workflow on given input list item id.  
function startWorkflow(itemId) {  
    var url = _spPageContextInfo.webAbsoluteUrl + "/Lists/" + listName + "/" + itemId + "_.000";  
    $().SPService({  
        operation: "StartWorkflow",  
        item: url,  
        async: true,  
        temaplteId: tempalteID,  
        workflowParameters: "<root />",  
        completefunc: function() {  
            console.log("workflow started on item :" + itemId);  
        }  
    });  
}  
</script>  
<body>  
    <!-- you can add HtmL code here and invoke the RunWorkflow() fucntion. I used here simple button -->  
    <div class="row">  
        <span>  
            <h2> Click on below button to run a workflow.</h2>  
        </span>  
        <br/>  
        <br/>  
        <button type="button" class="btn btn-primary" onclick="RunWorkflow()"></button>  
    </div>  
</body>undefined</html> 

Conclusion

 We can leverage client-side code to trigger the SharePoint workflow and even update the current context. We can trigger the workflow out of SharePoint.

This blog is part of SharePoint Week. For more great content, click here

About the Author:

He is a SharePoint, .Net developer working from Plano, Texas. Microsoft certified in Azure Cloud and SharePoint 2013/2010 technologies. Have been working in 2010, 2013, and Office 365 versions of SharePoint along with Asp.Net, WCF services. Have experience in design, built and customize SharePoint sites, migrate sites to newer platforms, and implement custom solutions using .NET as a WSP package for SharePoint. Learning Azure and Power Platform along with Sharepoint custom development for Office 365 i.e. SPFX web parts.

Reference:

Bobalade, U. (2021). Trigger A SharePoint Workflow From JavaScript. Available at: https://www.c-sharpcorner.com/blogs/trigger-a-sharepoint-workflow-from-javascript [Accessed: 31st August 2021].

Share this on...

Rate this Post:

Share: