Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery post request (not AJAX)

In an ASP.NET MVC app I use jQuery for posting data on button-click:

<button onclick="addProducts()">Add products</button>
....
$.post('<%= Url.Action("AddToCart", "Cart") %>',
            {
                ...
                returnUrl: window.location.href
            });

In the "AddToCart" action of "Cart" controller I use redirection to another View after posting:

    public RedirectToRouteResult AddToCart(..., string returnUrl)
    {
        ...
        return RedirectToAction("Index", new { returnUrl });            
    }

All is okay, except this redirection. I stay on the same page after posting. I suspect it's due to AJAX type of "POST" request.

How to solve the problem with jQuery POST request blocking the redirection?

like image 843
rem Avatar asked Jan 03 '11 10:01

rem


People also ask

How do I make a post request in Javascript?

To send an HTTP POST request, we need to first create the object by calling new XMLHttpRequest() and then use the open() and send() methods of XMLHttpRequest. To receive notifications when the status of a request has changed, we need to subscribe to the onreadystatechange event.

How do I send a post request in Ajax?

Send Http POST request using ajax()In the options parameter, we have specified a type option as a POST, so ajax() method will send http POST request. Also, we have specified data option as a JSON object containing data which will be submitted to the server.

What is jQuery POST?

jQuery post() Method post() method loads data from the server using a HTTP POST request.


3 Answers

I created a $.form(url[, data[, method = 'POST']]) function which creates a hidden form, populates it with the specified data and attaches it to the <body>. Here are some examples:

$.form('/index')

<form action="/index" method="POST"></form>
$.form('/new', { title: 'Hello World', body: 'Foo Bar' })

<form action="/index" method="POST">
    <input type="hidden" name="title" value="Hello World" />
    <input type="hidden" name="body" value="Foo Bar" />
</form>
$.form('/info', { userIds: [1, 2, 3, 4] }, 'GET')

<form action="/info" method="GET">
    <input type="hidden" name="userIds[]" value="1" />
    <input type="hidden" name="userIds[]" value="2" />
    <input type="hidden" name="userIds[]" value="3" />
    <input type="hidden" name="userIds[]" value="4" />
</form>
$.form('/profile', { sender: { first: 'John', last: 'Smith', postIds: null },
                     receiver: { first: 'Foo', last: 'Bar', postIds: [1, 2] } })

<form action="/profile" method="POST">
    <input type="hidden" name="sender[first]" value="John">
    <input type="hidden" name="sender[last]" value="Smith">
    <input type="hidden" name="receiver[first]" value="John">
    <input type="hidden" name="receiver[last]" value="Smith">
    <input type="hidden" name="receiver[postIds][]" value="1">
    <input type="hidden" name="receiver[postIds][]" value="2">
</form>

With jQuery's .submit() method you can create and submit a form with a simple expression:

$.form('http://stackoverflow.com/search', { q: '[ajax]' }, 'GET').submit();

Here's the function definition:

jQuery(function($) { $.extend({
    form: function(url, data, method) {
        if (method == null) method = 'POST';
        if (data == null) data = {};

        var form = $('<form>').attr({
            method: method,
            action: url
         }).css({
            display: 'none'
         });

        var addData = function(name, data) {
            if ($.isArray(data)) {
                for (var i = 0; i < data.length; i++) {
                    var value = data[i];
                    addData(name + '[]', value);
                }
            } else if (typeof data === 'object') {
                for (var key in data) {
                    if (data.hasOwnProperty(key)) {
                        addData(name + '[' + key + ']', data[key]);
                    }
                }
            } else if (data != null) {
                form.append($('<input>').attr({
                  type: 'hidden',
                  name: String(name),
                  value: String(data)
                }));
            }
        };

        for (var key in data) {
            if (data.hasOwnProperty(key)) {
                addData(key, data[key]);
            }
        }

        return form.appendTo('body');
    }
}); });
like image 64
Jeremy Avatar answered Oct 09 '22 09:10

Jeremy


$.post is an AJAX call.

Your best bet is to make the button a trigger for a form and just submit that using the post method.

An alternative would be to echo your new url from the server, but that defeats the point of AJAX.

like image 21
Horia Dragomir Avatar answered Oct 09 '22 09:10

Horia Dragomir


Use jQuery.submit() to submit form: http://api.jquery.com/submit/

like image 39
Victor Haydin Avatar answered Oct 09 '22 09:10

Victor Haydin