locked
SharePoint 2013 REST api XHR vs jQuery RRS feed

  • Question

  • Hello guys,

    I am trying to post a request with XHR and with jQuery. When i use jQuery it is working fine, but when i post same message with XHR i get an error:

    error

    Here are the requests:

    jQuery:

    jQuery example

    XHR:

    XHR example

    I want to use the plain JavaScript because i do not want to load jQuery only for this post message.

    I will appreciate any feedback,

    Thank you in advance!

    Best Regards,

    Jordan




    Saturday, November 26, 2016 8:34 AM

Answers

  • Hi,

    Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.

    I suggest to you using jQuery with promise to perform async http request and this is a great benefit for the user experience:

    here an example how to use the deferred object of jQuery:

    function getListItem(Uri) {
            var dfd = $.Deferred();
            // Send the request and return the response.
            $.ajax({
                url: Uri,
                type: "GET",
                headers: { "accept": "application/json;odata=verbose" },
                success: function (data) {
                    dfd.resolve(data);
                },
                error: function (data) {
                    dfd.reject(data);
                }
            });
    
            return dfd.promise();
    }
    function update(itemUrl, title) {
        var dfd = $.Deferred();
        var getItem = getListItem(itemUrl);
        getItem.done(function (listItem, status, xhr) {
    
            // Change the display title of the list item.
            var changeItem = updateListItem(listItem.d.__metadata,
                title);
            changeItem.done(function (data, status, xhr) {
                console.log('List updated');
                dfd.resolve();
            });
            changeItem.fail(onError);
        });
        getItem.fail(onError);
    }
    function updateListItem(itemMetadata, title) {
        var dfd = $.Deferred();
        var body = String.format("{{'__metadata':{{'type':'{0}'}},'Title':'{1}'}}",
            itemMetadata.type, title);
    
        // Send the request and return the promise.
        // This call does not return response content from the server.
        $.ajax({
            url: itemMetadata.uri,
            type: "POST",
            data: body,
            headers: {
                "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                "content-type": "application/json;odata=verbose",
                "content-length": body.length,
                "IF-MATCH": itemMetadata.etag,
                "X-HTTP-Method": "MERGE"
            },
            success: function (data) {
                dfd.resolve(data);
            },
            error: function (data) {
                dfd.reject(data);
            }
        });
    
        return dfd.promise();
    }
    // Display error messages. 
    function onError(error) {
        alert(error.responseText);
        dfd.reject(error);
    }
    
    $(document).ready(function() {
        update(_spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Tasks')/items(1)", "Item updated");
    });
    

    I tried personally and works, in any case jQuery give to you other great benefit like for example the DOM manipulation.

    Kind regards


    Giuliano De Luca - MCSD SharePoint, MCSD Web Applications, MCPS, MS. www.delucagiuliano.com Twitter: @giuleon

    Saturday, November 26, 2016 3:14 PM

All replies

  • Hi,

    Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.

    I suggest to you using jQuery with promise to perform async http request and this is a great benefit for the user experience:

    here an example how to use the deferred object of jQuery:

    function getListItem(Uri) {
            var dfd = $.Deferred();
            // Send the request and return the response.
            $.ajax({
                url: Uri,
                type: "GET",
                headers: { "accept": "application/json;odata=verbose" },
                success: function (data) {
                    dfd.resolve(data);
                },
                error: function (data) {
                    dfd.reject(data);
                }
            });
    
            return dfd.promise();
    }
    function update(itemUrl, title) {
        var dfd = $.Deferred();
        var getItem = getListItem(itemUrl);
        getItem.done(function (listItem, status, xhr) {
    
            // Change the display title of the list item.
            var changeItem = updateListItem(listItem.d.__metadata,
                title);
            changeItem.done(function (data, status, xhr) {
                console.log('List updated');
                dfd.resolve();
            });
            changeItem.fail(onError);
        });
        getItem.fail(onError);
    }
    function updateListItem(itemMetadata, title) {
        var dfd = $.Deferred();
        var body = String.format("{{'__metadata':{{'type':'{0}'}},'Title':'{1}'}}",
            itemMetadata.type, title);
    
        // Send the request and return the promise.
        // This call does not return response content from the server.
        $.ajax({
            url: itemMetadata.uri,
            type: "POST",
            data: body,
            headers: {
                "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                "content-type": "application/json;odata=verbose",
                "content-length": body.length,
                "IF-MATCH": itemMetadata.etag,
                "X-HTTP-Method": "MERGE"
            },
            success: function (data) {
                dfd.resolve(data);
            },
            error: function (data) {
                dfd.reject(data);
            }
        });
    
        return dfd.promise();
    }
    // Display error messages. 
    function onError(error) {
        alert(error.responseText);
        dfd.reject(error);
    }
    
    $(document).ready(function() {
        update(_spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Tasks')/items(1)", "Item updated");
    });
    

    I tried personally and works, in any case jQuery give to you other great benefit like for example the DOM manipulation.

    Kind regards


    Giuliano De Luca - MCSD SharePoint, MCSD Web Applications, MCPS, MS. www.delucagiuliano.com Twitter: @giuleon

    Saturday, November 26, 2016 3:14 PM
  • I can not un-vote this; I accidental upvoted when I meant to DOWN vote it.  This is NOT the answer.  The question SPECIFICALLY states that they do not want to use jQuery, after showing that they successfully used jQuery.

    It is very frustrating combing through the technet forums and seeing so many of these non-answers being labeled as the answer.


    Friday, February 15, 2019 7:14 PM
  • I agree the marked answer ignores "I want to use the plain JavaScript because I do not want to load jQuery only for this post message."

    I too am in a situation where I do not want to/cannot (easily) use jQuery to POST to SharePoint REST. I have thousands of SP Items to update and I want to use a web worker to update the items to keep the DOM from freezing up. The web worker cannot access jQuery loaded in the DOM w/o a LOT of extra work. Therefore plain JavaScript is the fastest path. After enough trial and error I discovered the issue.

    The URI will not work with a plain JavaScript XMLHttpRequest

    "_api/Web/Lists/GetByTitle('MyList')/Items('MyId')"

    Instead you must use:

    "_api/Web/Lists(guid'xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx')/Items('MyId')"

    Some quality time with Fiddler might explain why this is...

    • Proposed as answer by frankcole Friday, September 6, 2019 6:10 PM
    Friday, July 12, 2019 8:05 AM