2

I get a 400 Bad Request from this code, hard to debug, what can the problem be?

        function saveSelectedAnswer(radioValue) {

            var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_vti_bin/listdata.svc/PollUserData";
            var listItems = {
                'Question': allQuestionsArray[0].Question,
                'Answer': radioValue,
                'QuestionID': allQuestionsArray[0].ID,
                'UserID': userGuid 
            };
            var requestBody = JSON.stringify(listItems);
            var requestHeaders = {
                "ACCEPT": "application/json;odata=verbose"
            }
            $.ajax({
                url: requestUri,
                type: "Post",
                processData: false,
                contentType: "application/json;odata=verbose",
                data: requestBody,
                headers: requestHeaders,
                success: function(data) {
                    console.log("data saved");
                },
                error: function(xhr, thrownError) {
                    alert(xhr.status + " " + thrownError);
                }
            });
        }
2
  • Do you have a list with title PollUserData? Dec 9, 2014 at 15:43
  • Try to open http://siteurl/_vti_bin/listdata.svc and check you can see the Mentioned list Dec 9, 2014 at 15:44

3 Answers 3

1

Check if you can see the list with a basic get request with something like:

$.getJSON("_spPageContextInfo.webAbsoluteUrl + "/_vti_bin/listdata.svc/PollUserData",
     function(data) { console.log(data) });

Which will log the contents to your browser dev tools console.

Once you get that figured out.... You're also not passing the request digest in your post request. The request digest acts as an anti-forgery token and is required for all POST operations to SP. This isn't too big of a problem though, if you're on a SharePoint page you there is a hidden form element containing this information -- it has the ID: __REQUESTDIGEST

Change your headers object to:

headers: { 
    "Accept": "application/json;odata=verbose", 
    "X-RequestDigest": $('#__REQUESTDIGEST').val() 
}
1

The ajax call was correct, the error was because of my SharePoint field type:text, changed it to number, now it works.

1

Try to check this below which has Get the info from sharepoint list using REST Ajax call

SharePoint + REST + Ajax

Add this below script into the Content Editor Webpart

(function ($) {
    $(document).ready(function () {
        // Ensure that the SP.js file is loaded before the custom code runs.
        SP.SOD.executeOrDelayUntilScriptLoaded(loadCompletedEventsData, 'SP.js');
    });

    /**************************************************************************************************
    * Function : loadCompletedEventsData                                                              *
    * Descritption : This function is used to get the data and assign the data to the respective table*
    **************************************************************************************************/
    //Get today Date and Year
    var curDate = new Date();
    curDate = curDate.getFullYear() + '-' + (curDate.getMonth() + 1) + '-' + curDate.getDate() + 'T00:00:00Z';
    function loadCompletedEventsData() {
        var CompletedEventListName = "Upcoming Events";
        jQuery.ajax({
            url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + CompletedEventListName + "')/Items?$orderby=EventEndDate desc&$filter=EventEndDate lt datetime'" + curDate + "'",
            type: "GET",
            headers: { Accept: "application/json;odata=verbose" },
            success: function (data) {
                if (data.d.results.length > 0) {
                    var results = data.d.results;
                    var convertDate;
                    var cplMonthNames = ["January", "February", "March", "April", "May", "June", "July",
                                    "August", "September", "October", "November", "December"];
                    var uniqueYear = new Array();
                    var viewAllCompletedEvents = _spPageContextInfo.webAbsoluteUrl + "/Pages/Completed-Events.aspx";
                    var completedEventDisplayUrl;
                    var iCounter = 0;
                    var finalCounter = 4;
                    $.each(results, function (index, dataEvents) {
                        var completedEventID = dataEvents.Id;
                        var completedEventTopic = dataEvents.Title;
                        var completedEventDescription = dataEvents.EventDescription;
                        var completedEventImageUrl = dataEvents.Image;
                        var completedEventEndDate = dataEvents.EventEndDate;
                        var tblhddate = new Date(completedEventEndDate);
                        var cplStrItem = "";
                        var completedEventDisplayUrl = _spPageContextInfo.webAbsoluteUrl + "/Pages/Event-Details.aspx?ID=" + completedEventID + "&InitialTabId=Ribbon.Read";
                        if (completedEventEndDate != "") {
                            $("#tbl-EveAndHapCompletedEventsViewAllLink").html();
                            if (iCounter < finalCounter) {
                                // Create a table row dynamically based on the content from the list.
                                cplStrItem = "<tr>" +
                                                "<td>" +
                                                    "<h3 >" + cplMonthNames[tblhddate.getMonth()] + " " + tblhddate.getDate() + ", " + tblhddate.getFullYear() + "</h3>" +
                                                    "<a href='" + completedEventDisplayUrl + "' > " + completedEventTopic + "</a>" +
                                                "</td>" +
                                            "</tr>";
                                $("#tbl-EveAndHapCompletedEventsContents").append(cplStrItem);
                                iCounter++;
                            }
                            else {
                                $("#tbl-EveAndHapCompletedEventsViewAllLink").html("<a href='" + viewAllCompletedEvents + "' > View All </a>");
                                return false;
                            }
                        }
                    });
                }
                else {

                    strItem = "<tr><td><div class='queryEmptyMsg'> There are currently no Completed Events available. </div></td></tr>";
                    $("#tbl-EveAndHapCompletedEvents").html(strItem);
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                Console.log("completedEvents.js:loadCompletedEventsData:: " + textStatus);
            }
        });
    }
})(jQuery);
3
  • Please do not post link-only answers. When the link breaks they are of no use Oct 29, 2015 at 11:58
  • I always to use links of my blog. Are you happy for this one..:) Oct 30, 2015 at 5:51
  • Looks much better! Oct 30, 2015 at 9:42

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.