capcapdk capcapdk - 4 months ago 5
Ajax Question

Jquery AJAX from GET to POST

I have the following GET-request:

$('#Types').on('change', function () {
$.ajax({
url: '../Dashboard/DisplayTiles?type=' + $('#Types').val() + "&category=" + $('#Categories').val(),
beforeSend: function () {
$('#loading').show();
$('#search').val("");
},
success: function (data) {
$('#main').html(data);
$('#loading').hide();
}
});
});


How do i make this POST? I have tried googling it without a clear result... I want to specify the method as post and put the same data into the request as before (data in url).

Answer

Set the method property to 'POST' and provide an object with your data in to data property. Also remove the query string from the url provided

$.ajax({
    // Remove query string
    url: '../Dashboard/DisplayTiles',
    // Set method to 'POST'
    method: 'POST',
    // Provide the data object
    data: { 
       type: $('#Types').val(),
       category: $('#Categories').val()
    },
    beforeSend: function () {
        $('#loading').show();
        $('#search').val("");
    },
    success: function (data) {
        $('#main').html(data);
        $('#loading').hide();
    }
});