Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a PUT call with JSON data using AJAX and JQuery?

I've looked around and tried many different methods, but can't seem to pass actual data to my controller's function.

Here is some code:

        var URL = "/Timesheet/Timesheet/UpdateEntry";

        var dataObject = { 'newWeekEntry': newEntry, 'oldWeekEntry': oldEntry };

        alert(JSON.stringify(dataObject));

        $.ajax({
            url: URL,
            type: 'PUT',    
            data: JSON.stringify(dataObject),
            dataType: 'json',
            success: function(result) {
                alert("success?");
            }
        });

newEntry and oldEntry are both objects.

The alert line outputs this (with some properties removed, just for brevity):

{"newWeekEntry":{"MondayHours":2,"TuesdayHours":2,"WednesdayHours":5,"ThursdayHours":5,"FridayHours":"4","SaturdayHours":0,"SundayHours":0},"oldWeekEntry":{"MondayHours":2,"TuesdayHours":2,"WednesdayHours":5,"ThursdayHours":5,"FridayHours":2,"SaturdayHours":0,"SundayHours":0}}

When I debug my controller action ("UpdateEntry"), the two parameters are filled with the TimesheetEntry class default parameters (0).

Am I passing this in properly?

like image 967
D'Arcy Rail-Ip Avatar asked Oct 24 '12 20:10

D'Arcy Rail-Ip


People also ask

Does AJAX support PUT method?

Through the ajax() function we are sending the data parameter to the Put() action defined in the person controller.

How JSON fetch data using AJAX?

The jQuery code uses getJSON() method to fetch the data from the file's location using an AJAX HTTP GET request. It takes two arguments. One is the location of the JSON file and the other is the function containing the JSON data. The each() function is used to iterate through all the objects in the array.


2 Answers

The dataType attribute is only used when you're getting data from the server. You should be setting contentType to application/json when sending data to the server.

like image 101
InPursuit Avatar answered Oct 12 '22 22:10

InPursuit


$.ajax({
        url: window.serverUrl + 'student/event/' + eventId,
        type: 'put',
        data: JSON.stringify(data),
        headers: {
            'x-auth-token': localStorage.accessToken,
            "Content-Type": "application/json"
        },
        dataType: 'json'
})

This worked for me

like image 26
Jayadeep KM Avatar answered Oct 12 '22 23:10

Jayadeep KM