1

I'm trying to do a REST call to get current user information without using jQuery to handle the ajax. I've got this code:

var xmlhttp = new XMLHttpRequest();

xmlhttp.onreadystatechange = function(){
    if(xmlhttp.readyState == XMLHttpRequest.DONE){
        if(xmlhttp.status == 200){
            console.log(JSON.parse(xmlhttp.responseText))
        } else if (xmlhttp.status == 400){
            console.log("not found")
        } else {
            console.log("other")
        }
    }
}
xmlhttp.responseType="json"
xmlhttp.open("GET","https://,site/_api/web/currentuser?$format=json",true);
xmlhttp.send()

This works, but the response comes back as xml not json. Is there a way to tell the SP to return json when using XHR?

I tried the $format=json parameter, but that evidently isn't supported by the SP 2013 REST api. Nor is XMLHttpRequest.responseType supported by browsers.

1 Answer 1

2

You have to set the Accept request header to application/json; odata=verbose using XMLHttpRequest.setRequestHeader().

SharePoint looks at this header to decide if the data has to be sent as JSON or XML.

2
  • That seems to be working. Looking at the documentation you linked to, it looks like setRequestHeader() has support back to IE7, which is good, but is it supported in FireFox?
    – Rothrock
    Nov 7, 2016 at 19:35
  • Hmm. Just tested. Looks like it is not working in Firefox. May be you can use a shim just for FF.
    – NLV
    Nov 7, 2016 at 19:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.