Skip to main content

Search

Examples how to use http request

Comments

8 comments

  • Andrii Katsiubka

    Hi Heikki Salminen

     

    You can generate request data based on form fields with expressions.

    Suppose our external service accepts json data. So we can open expression builder fot Data field and set expression type to Function code (drop down at the top of expression builder dialog). Then define some object:

    var data = {   
       title: [[Title]],
       customerId: [[LookupToCustomers.ID]]
    };
    data.SomeField = [[SomeField]];

    Function Expression should return some value, in our case its should be a json string. For this purpose you can use JSON.stringify. So this expression will look like this:

    var data = {   
       title: [[Title]],  
       customerId: [[LookupToCustomers.ID]]
    };
    data.SomeField = [[SomeField]];

    return JSON.stringify(data);

     

    With Http Request action you can not preview request before sending. You can only see it in DevTools of you browser atfter sending the request. As well at the moment it is not possible to handle the response from the server.

     

    You can use Execute script action and write custom javscript to call your service by using jQuery (jQuery.get, jQuery.post or jQuery.ajax methods). In this case you can define success and error callbacks to handle the response from the server.

     

    To set some value to the field in the current form you can use this script (replace <FieldName> with your field name):

    var inputController = jQuery('span.ms-formbody[fieldname="' + <FieldName> + '"]').closest('.ard-formfield').data('Controller');
    inputController.InstanseData.SetValue(val);
    0
  • Salminen Heikki

    Hi

     

    I've made some progress, but not completed. Sorry for stupid questions, but I'm really a newbie with JavaScript.

     

    I know that when I create a user successfully, API returns status code "200 OK" and the following json object

    {
    "Message": "New user created with id: 23c74704-0c96-470c-bae9-b5dc244c10c5. User creation is waiting for approval.",
    "Code": 1
    }

     

    A few weeks ago I received a code example below. I tried to modify the code to catch the status code and response, but with no luck. Can you please assist me?

     

     

    var redirectionUrl = [[@Page.GetQueryString("Source")]];
    var requestData = 'Firstname=' + [[extUserFirstName]] +
    '&Lastname=' + [[extUserName]] +
    '&AccountName=' + [[extUserFirstName]] + '.' + [[extUserName]] +
    '&Company=' + [[extUserCompany]] +
    '&DisplayName=' + [[extUserName]] + " " + [[extUserFirstName]] +
    '&Manager=' + [[OrderedBy.LoginName]]
    ;
    var requestUrl = 'https://xxxxxx.azurewebsites.net/api/v1/adduser';
    var options = {
    type: 'POST',
    url: requestUrl,
    data: requestData,
    crossDomain: false,
    headers: {
    'Content-Type':'application/json',
    'Authorization':'Basic xxxxxxxxxxxxx'
    }
    };
    jQuery.ajax(options).done(function(data){
    var statusId = SP.UI.Status.addStatus("Success!" + data.Message);
    SP.UI.Status.setStatusPriColor(statusId, 'green');
    window.location.href = redirectionUrl;
    }).fail(function(data){
    var statusId = SP.UI.Status.addStatus("Error occurred during adding user throw MIM. Status Code: " + data.status.toString() + ". Status Text: " + data.statusText);
    SP.UI.Status.setStatusPriColor(statusId, 'red');
    });
    0
  • Andrii Katsiubka

    Hi Heikki Salminen,

     

    When you set content type to 'application/json' and use 'post' method type you should send json in request body.

    So try to make this changes for requestData variable:

    var requestData = { 
        Firstname = [[extUserFirstName]],
        Lastname = [[extUserName]],
        AccountName = [[extUserFirstName]] + '.' + [[extUserName]],
        Company = [[extUserCompany]],
        DisplayName = [[extUserName]] + " " + [[extUserFirstName]],
        Manager = [[OrderedBy.LoginName]]
    };

    and replace line

    data: requestData,

    by

    data: JSON.stringify(requestData),
    0
  • Salminen Heikki

    Hi Andrii

     

    I have already made those changes. But how do I catch the status code and response from API?

    0
  • Andrii Katsiubka

    Hi Heikki Salminen

     

    You can handle status code and response from API in done and fail callbacks.

    According to jQuery documentation callback function for done and fail accepts three arguments.

     

    jQuery.ajax(options).done(function(data, textStatus, jqXHR){
    //You can access response in done callback by using data argument or jqXHR object
    console.log(data);
    console.log(jqXHR.responseText);
    //Status code
    console.log(jqXHR.status);
    }).fail(function(jqXHR, textStatus, errorThrown){
       //in fail callback use jqXHR object
       //Response
       console.log(jqXHR.responseText);
       //Status code
       console.log(jqXHR.status);
    });
    0
  • Salminen Heikki

    Hi

     

    Handling responses works, thanks for quidance. 

     

    I tried to save the results to a form field called "Response" (lines 12-13), but with no luck. Alert on row 11 shows the values correctly. 

     

    jQuery.ajax(options).done(function(data, textStatus, jqXHR){
    //You can access response in done callback by using data argument or jqXHR object
    console.log(data);
    console.log(jqXHR.responseText);
    //Status code
    console.log(jqXHR.status);
    var apiRequest = JSON.parse(jqXHR.responseText);
    var myApiMessage = apiRequest.Message;
    var myApiCode = apiRequest.Code;
    var myApiStatus = jqXHR.status;
    alert("SUCCESS! responsetext= " + myApiMessage + " Code = " + myApiCode + " status=" + myApiStatus);
    var inputController = jQuery('span.ms-formbody[fieldname="' + [[Response]] + '"]').closest('.ard-formfield').data('Controller');
    inputController.InstanseData.SetValue("responsetext= " + myApiMessage + " Code = " + myApiCode + " status=" + myApiStatus);
    }).fail(function(jqXHR, textStatus, errorThrown){
       //in fail callback use jqXHR object
       //Response
       console.log(jqXHR.responseText);
       //Status code
       console.log(jqXHR.status);
    var apiRequest = JSON.parse(jqXHR.responseText);
    var myApiMessage = apiRequest.Message;
    var myApiCode = apiRequest.Code;
    var myApiStatus = jqXHR.status;
    alert("FAIL! responsetext= " + myApiMessage + " Code = " + myApiCode + " status=" + myApiStatus + " errorthrown = " + errorThrown);
    });
    0
  • Taras Lozynskyy

    Hi Heikki Salminen
    You should use 

     var inputController = jQuery('span.ms-formbody[fieldname="Response"]').closest('.ard-formfield').data('Controller');

    on line 12

    0
  • Salminen Heikki

    Here's my "final" version. I'll share it if it's usable for someone else as well. If you have any ideas how to improve this, please comment!

     

     

    var requestUrl = 'https://xxx.azurewebsites.net/api/v1/adduser';
    var dataType = 'json';
    var apiRequest;
    var myApiMessage;
    var myApiCode;
    var myApiStatus;
    var myResponse;
    var inputController;
    var requestData = {
    AccountName: [[extAccountName]],
    FirstName: [[extUserFirstName]],
    LastName: [[extUserName]]
    };
    var options = {
    type: 'POST',
    url: requestUrl,
    data: JSON.stringify(requestData),
    crossDomain: true,
    /*
    Use "async: false" here. Otherwise the response is not captured before the form is closed
    and you have no idea if the request was successful or not
    */

    async: false,
    headers: {
    'Content-Type':'application/json',
    'Authorization':'xxx'
    }
    };

    jQuery.ajax(options).done(function(data, textStatus, jqXHR){
    /*
    If http responss = 200, execute this block
    */

    apiRequest = JSON.parse(jqXHR.responseText);
    myApiMessage = apiRequest.Message;
    myApiCode = apiRequest.Code;
    myApiStatus = jqXHR.status;
    myResponse = (myApiMessage);
    alert("Success");
    }).fail(function(jqXHR, textStatus, errorThrown){
    /*
    If http response != 200, execute this block
    */

    apiRequest = JSON.parse(jqXHR.responseText);
    myApiMessage = apiRequest.Message;
    myApiCode = apiRequest.Code;
    myApiStatus = jqXHR.status;
    myResponse = (myApiMessage);
    alert("FAIL!");
    });
    /*
    Save response from API to form fields for later usage
    */

    inputController = jQuery('span.ms-formbody[fieldname="Response"]').closest('.ard-formfield').data('Controller');
    inputController.InstanseData.SetValue(myResponse);
    inputController = jQuery('span.ms-formbody[fieldname="apiResponseCode"]').closest('.ard-formfield').data('Controller');
    inputController.InstanseData.SetValue(myApiCode);
    inputController = jQuery('span.ms-formbody[fieldname="httpResponseCode"]').closest('.ard-formfield').data('Controller');
    inputController.InstanseData.SetValue(myApiStatus);
    0

Please sign in to leave a comment.