0

I am currently struggling to figure out an issue with my project relating to the creation of new SP List items from a SP2013 (Online) App using Angular as its base framework. I am quite new to Angular and it has been a train smash to grasp the concepts although I feel way more confident now and am not confused by the way things work any loner. Anyway, I will give a brief explanation of my problem and my snippets below. Hopefully someone can give me advice or suggestions.

I have a few inputs where i can throw in data and upon clicking a button it must create a new list item within my specified list. My controller is below:

ADD ITEM CONTROLLER SNIPPET

$scope.saveitem = function () {
        var id = $('#projectidhidden').val();
        var priority = $('#txtPriority').val();

        PMOService.addItem({
            title: "RPID" + id,
            description: $scope.Item.description,
            option: priority
        })
    };

Debugging at run-time via the browser reveals that all my values are mapped correctly, ie, all 3 values above are being populated correctly (grabbing values from the form inputs)

Now, here is my actual saving script:

  PMOService.addItem = function (item, callback) {
      //ensure form digest
      PMOService.ensureFormDigest(function (fDigest) {
          $http.post(
              PMOService.appWebUrl + '/_api/web/Lists/getbytitle(\'ItemsList\')/Items',
                {
                    'Title': item.title,
                    'Description': item.description,
                    'Option': item.option,
                },
              {
                  headers: {
                      'Accept': 'application/json; odata=verbose',
                      'X-RequestDigest': fDigest
                  }
              }).success(function (d) {
                  item.id = d.d.ID;
                  items.push(item);
                  callback();
              }).error(function (er) {
                  alert("Error creating Item: " + er);
              });
      });
  };

Upon clicking the save button, there are no errors although the .error method is definitely not being hit and yet no item is being added. Also there are no helpful js errors in the console.

My SPFormDigest does work and all other parts of my project are working, adding new SPList items correctly, it is just this specific example that does not work and I cannot see any specific errors. The funny thing is this was working, then it somehow stopped working. I am sure that the issue is not on the html markup, since all my values are fully populated in the controller section. Please can someone let me know if you can see anything that is incorrect or that I may try as I cannot for the life of me figure out what I changed or how I broke this step.

If you need any other info, please let me know. Thanks in advance.

1

Apps are virtually a differnet domain than the host site. Hence browsers dont allow cross domain requests. In order to circumvent this you need to either use sp.RequestExecutor.js or SP.APPContextSite() instead of the standard procedure.

This is the structure of the URL if using SP.AppContextSite

  var url = appwebUrl + "/_api/SP.AppContextSite(@target)/web/lists/getbytitle('"+listName+"')/items?$select=Title,ID&@target='" + hostUrl + "'";

This is the general structure of the call if using SP.RequestExecutor.js

    var scriptbase = hostUrl + "/_layouts/15/";
    $.getScript(scriptbase + "SP.RequestExecutor.js", function () {

        var url =  appwebUrl +
                  "/_api/SP.AppContextSite(@target)/web/lists/getbytitle('" + listName + "')/items?$select=Title,ID&@target='" + hostUrl + "'";


        var executor = new SP.RequestExecutor(appwebUrl);
        executor.executeAsync(
        {
            url:     url,
            method:  "POST",
            headers: { "Accept": "application/json; odata=verbose", "content-type": "application/json; odata=verbose"},
            success: function () {alert('success')},
            error:   function(){alert("error");
        }

You need to get hostUrl and webUrl from the querystring using string operations.

Here is a handy jquery extension

jQuery.extend({

getQueryStringValues: function () {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
},

getQueryStringValue: function (name) {
    return jQuery.getQueryStringValues()[name];
}

});

Just add this to a script file and reference it into the aspx/html page after you reference the jquery file

Then you can just use it like the following

       var appWebUrl = decodeURIComponent(jQuery.getQueryStringValue('SPAppWebUrl'));
       var hostUrl = decodeURIComponent(jQuery.getQueryStringValue('SPHostUrl'));
  • Hi Swayam, thanks for the quick reply and willingness to help. I do already have the webapp and hostweb URLs defined and they do resolve correctly. I have one method which has this and populates both my URL values, as is I have not had cross domain issues - I am also currently working on my dev environment which happens to be the server anyway. Either way I can confirm that this is not where my issue is i'm afraid. Thanks for the idea though. I should have mentioned that I have this already. I can add list items through other views in my app. – geostima Apr 22 '15 at 9:09
  • PMOService.appWebUrl = decodeURIComponent(PMOService.getQueryStringParameter('SPAppWebUrl')).split('#')[0]; PMOService.hostWebUrl = decodeURIComponent(PMOService.getQueryStringParameter('SPHostUrl')).split('#')[0]; – geostima Apr 22 '15 at 9:13
  • Np. I am into my second week with angular js based apps. Just shared the jquery function as it it very handy. The list you are trying to add to, is it in the host site or the app site? – Swayam Siddha Apr 22 '15 at 9:29
  • Hi Swayam, I have figured out my issue, there was a value which was out of scope directly above the adding of the risk. I stepped through it again with an alert to see where the code suddenly stops functioning and it pointed to the item which was out of scope, I have rectified it and I have added some of the modifications to my URL and query string function as you have suggested, this will help me vastly. Thanks bud. – geostima Apr 22 '15 at 9:33
  • Great. No Problem – Swayam Siddha Apr 23 '15 at 7:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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