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

I looked around and tried many different methods, but I can not pass the actual data to my controller function.

Here is the 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 displays 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"), two parameters are populated with the default TimesheetEntry default parameters (0).

Am I transmitting this correctly?

+8
json jquery put ajax
source share
3 answers

The dataType attribute dataType used only when you receive data from the server. You must set contentType to application/json when sending data to the server.

+26
source share

Use the headers: {"X-HTTP-Method-Override": "PUT"} and override the type of POST request. He is working on my project ...

 $.ajax({ type: 'POST', // Use POST with X-HTTP-Method-Override or a straight PUT if appropriate. dataType: 'json', // Set datatype - affects Accept header url: "http://example.com/people/1", // A valid URL headers: {"X-HTTP-Method-Override": "PUT"}, // X-HTTP-Method-Override set to PUT. data: '{"name": "Dave"}' // Some data eg Valid JSON as a string }); 
+3
source share
 $.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' }) 

It worked for me

0
source share

All Articles