Tuesday, January 15, 2019

How to avoid "Ajax error" when calling SharePoint Rest services in SharePoint framework?

When I tried to follow the instructions to set up a SPFx with SharePoint rest call, I get the following error when running from local.

"DataTables warning: table id=DataTables_Table_0 - Ajax error. "

After debugging the code, it seems like we need to change the ajex code to following line. Please note the two level for the url.


  'ajax': {
          'url': "../../_api/web/lists/getbytitle('IT Requests')/items?$select=ID,BusinessUnit",

}


Then we deploy the code to the site and it got the error again. The actual url is now pointing to:

https://mytennat.sharepoint.com/sites/_api/web/lists/getbytitle('IT Requests')/items?$select=ID,BusinessUnit

The url is missing the site name. I had to change the ajax call url to the following line with one level up.

  'ajax': {
           'url': "../_api/web/lists/getbytitle('IT Requests')/items?$select=ID,BusinessUnit",

}


Now it's one level up deployed on server and two level up running from local!

The best practice is to change the code to get the site url and pass to the ajax.

siteurl: this.context.pageContext.web.absoluteUrl

    jquery.ajax({ 
        url: `${this.props.siteurl}/_api/web/lists/getbytitle('EmployeeList')/items`
        type: "GET"
        headers:{'Accept': 'application/json; odata=verbose;'}, 
        success: function(resultData) { 
            this.setState({ 
            items: resultData.d.results 
          }); 
        }, 
        error : function(jqXHR, textStatus, errorThrown) { 
        } 

    }); 


Hope this will avoid some frustration for you when using ajax in SPFx.

No comments:

Post a Comment