Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

I intend to insert a list item from the main page in intranet to a list hosted on another site collection.

I made this simple HTML & JS to get it done, but I always get the 403 / FORBIDDEN error: "The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again."

Page URL: http://intranetv2/Incidencias.aspx (site collection 1)

List URL: http://intranetv2/teams/sistemas/Incidencias (site collection 2)

Auth is standard claims.

Now this is my code, it is embedded in a script editor webpart:

<div style=" margin: 40px; ">
   <h3>Reportar una incidencia</h3> 

   <script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.1.min.js"></script>
   <script>
     window.jQuery || document.write('<script src="js/jquery-1.11.1.min.js"><\/script>')
   </script>

   <script src="/_layouts/15/SP.RequestExecutor.js"></script>

   <script>
   var targetUrl = _spPageContextInfo.webAbsoluteUrl;
   var apiEndpoint = "/teams/sistemas/_api/lists/getbytitle('Incidencias')/items";


   //var targetUrl = '/teams/sistemas';
   var listName = 'Incidencias';
   var listURL = '/teams/sistemas/Lists/Incidencias/';

   // Adding a list item with the metadata provided
   function addListItem(targetUrl, endpoint, listname, itemType, metadata, successCallback, errorCallback) {
       var targetSiteUrl = _spPageContextInfo.webAbsoluteUrl;

       metadata.__metadata = { type: itemType };

       var re = new SP.RequestExecutor(targetUrl);
       re.executeAsync({
          url: endpoint,
          headers: { 'Accept': 'application/json; odata=verbose', 'X-RequestDigest' : $('#__REQUESTDIGEST').val() },
          method: 'POST',
          body: JSON.stringify(metadata),
          success: successCallback,
          error: errorCallback
       });
   }

   function NuevaIncidencia(){

       var metadata = {
          Title:         'AA',
          Description:  'AA',
          'Tipo Incidencia':   'Problema de red, no funciona internet',
          Prioridad:      'Baja'
       };


       addListItem(targetUrl, apiEndpoint, listName, 'SP.Data.IncidenciasListItem', metadata, success, error);
   }

   function error (xhr) {
      alert('ERROR: ' + xhr.error.message.value);
   }

   function success (data) {
      var jsonObject = JSON.parse(response.body);

      alert('incidencia creada: ' + jsonObject.ID);

      window.location.reload();
   }

   </script>

   Título
   <input id="titulo" name="titulo" type="text" />
   <br />

   Descripcion
   <input id="descripcion" name="descripcion" type="text" />
   <br />

   Tipo
   <input id="tipo" name="tipo" type="text"/>
   <br />

   Prioridad
   <input id="prioridad" name="prioridad" type="text" />
   <br />

   <input id="Aceptar" name="Aceptar" type="button" value="Aceptar" onclick="NuevaIncidencia(); this.disabled = true; return false;"/>
</div>

REQUEST:

Remote Address:192.168.0.26:80
Request URL:http://intranetv2/teams/sistemas/_api/lists/getbytitle('Incidencias')/items
Request Method:POST
Status Code:403 FORBIDDEN

Request Headers
Accept:application/json; odata=verbose
Accept-Encoding:gzip,deflate,sdch
Accept-Language:es-ES,es;q=0.8,en;q=0.6
Connection:keep-alive
Content-Length:162
Content-Type:text/plain;charset=UTF-8
Cookie:Ribbon.EditingTools.CPInsert=1920955|-1|1392|-1142501406; Ribbon.List=1920955|-1|330|905164056; Ribbon.Permission=1920955|-1|1472|2082598053; SearchSession=60b28d12%2D8186%2D4121%2Da4d0%2Df746bf476ccf; databaseBtnText=0; databaseBtnDesc=0; PWA_Perf=0; Ribbon.Read=1376808|-1|0|1699301174; Ribbon.WikiPageTab=1920430|-1|503|1699301174; Ribbon.EditingTools.CPEditTab=1920430|-1|593|-1142501406; WSS_FullScreenMode=false
DNT:1
Host:intranetv2
Origin:http://intranetv2
Referer:http://intranetv2/Pages/Incidencias.aspx
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36
X-RequestDigest:0x9CAF12232FF74ECE20D646319A2FBC4D4D3983130A1D23495833A73FFCDC9A59C21CE4A465C14600C94C31E2DD3B8E1E78D2F7989F2DAA9BFE37EC501691BB58,05 Aug 2014 12:15:00 -0000

Request Payload
    {Title:AA, Description:AA, Tipo Incidencia:Problema de red, no funciona internet, Prioridad:Baja,…}
    Description: "AA"
    Prioridad: "Baja"
    Tipo Incidencia: "Problema de red, no funciona internet"
    Title: "AA"
    __metadata: {type:SP.Data.IncidenciasListItem}

RESPONSE:

Response Headers

Cache-Control:private, max-age=0
Content-Type:application/json;odata=verbose;charset=utf-8
Date:Tue, 05 Aug 2014 12:15:02 GMT
Expires:Mon, 21 Jul 2014 12:15:03 GMT
Last-Modified:Tue, 05 Aug 2014 12:15:03 GMT
MicrosoftSharePointTeamServices:15.0.0.4569
request-id:4f84ab9c-4d19-3070-f7fd-b53939c67167
Server:Microsoft-IIS/8.5
SPRequestGuid:4f84ab9c-4d19-3070-f7fd-b53939c67167
Transfer-Encoding:chunked
X-AspNet-Version:4.0.30319
X-Content-Type-Options:nosniff
X-FRAME-OPTIONS:SAMEORIGIN
X-MS-InvokeApp:1; RequireReadOnly
X-Powered-By:ASP.NET
X-RequestDigest:0x69A556EF83654433A02D9DEFEA7A748C41D2D9C6803C2973B2341C661F1BF3BCB27C328D363271D61BF296D7938589CE032DB10376A0CBA87357022B944A1159,05 Aug 2014 12:15:03 -0000
X-RequestDigest:0x69A556EF83654433A02D9DEFEA7A748C41D2D9C6803C2973B2341C661F1BF3BCB27C328D363271D61BF296D7938589CE032DB10376A0CBA87357022B944A1159,05 Aug 2014 12:15:03 -0000
X-SharePointHealthScore:0

Using Ajax inside the addListItem (the params of the function are from later version, thus not thoroughly used here):

UpdateFormDigest(_spPageContextInfo.webServerRelativeUrl, _spFormDigestRefreshInterval)

$.ajax({
    url: _spPageContextInfo.webAbsoluteUrl + "/teams/sistemas/_api/lists/getbytitle('Incidencias')/items",
    type: "POST",
    headers: { "accept": "application/json", "X-RequestDigest" : $('#__REQUESTDIGEST').val },
    data: JSON.stringify(metadata), 
    success: function (data) {
                if (data.d) { 
                   alert(data.d.__metadata.etag);
                }
             },
    error: function (xhr) {
                alert('ERROR: ' + xhr.status + ': ' + xhr.statusText);
           }
});
share|improve this question
1  
You don't need the RequestExecutor library, that's only for cross domain calls. And X-ReqestDigest is not needed when using RequestExecutor. –  wjervis Aug 6 at 13:29
    
I tried with plain $.ajax, also I tried without the X-ReqestDigest field, wich the RequestExecutor adds automatically for you. also I tried with UpdateFormDigest(_spPageContextInfo.webServerRelativeUrl, _spFormDigestRefreshInterval) before the call. –  Juan Ochando Aug 7 at 9:47
    
What's your code when you use plain $.ajax()? Also, what's the internal name for Tipo Incidencia? –  wjervis Aug 7 at 11:07
    
Edited the question with the ajax version. –  Juan Ochando Aug 8 at 9:09

2 Answers 2

up vote 1 down vote accepted

Just found a way around! Using SPservices:

function NuevaIncidencia(){

        $('#Aceptar').attr("disabled", "disabled");

        var values = [['Title', $('#titulo').val()], ['Descripci_x00f3_n', $('#descripcion').val()], 
            ['Tipo_x0020_Incidencia', $('#tipo').val()], ['Prioridad', $('#prioridad').val()], ['Estado', 'Abierta']];

        $().SPServices({
            operation: "UpdateListItems",
            async: false,
            batchCmd: "New",
            webURL: targetUrl,
            listName: listName,
            valuepairs: values,
            completefunc: function(xData, Status) {
                if (Status == 'success') {
                    if ($(xData).hasSPError()) {
                        alert("Sucedió un error: " + $(xData).getSPError());
                    } else {
                        alert("Incidencia creada con identificador: " + $(xData.responseXML).SPFilterNode("z:row").attr("ows_ID") );

                        $('#titulo').val('');
                        $('#descripcion').val('');
                        $('#tipo').val('');
                        $('#prioridad').val('');

                        $('#Aceptar').removeAttr("disabled");
                    }
                } else {
                    alert("No se pudo contactar con el servidor");
                }
            }
        });
    }
share|improve this answer

I use to call REST like this in my current project:

var formDigest =  $('#__REQUESTDIGEST').val();

$.ajax({
    type: "POST",
    url: "your URL here",
    headers: { "X-RequestDigest": formDigest },
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify({ "ParamName": "Param Value" }),
    datatype: 'json',
})
.done(function (data) {
   // success way
})
.fail(function (xhr, status, error) {
   // error way
});
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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