user2263104
user2263104

Reputation: 109

ajax post fails to redirect to action

Javascript:

$("#containerr").on('click', '#select', function() {
        data = {};
        val = {
               "name": 'John',
               "id": 10,
                }
        data.user = JSON.stringify(val);
        data.token = $("input[name=token]").val();
        console.log(data);
        url = '/test/ajax/';
        $.ajax({
            url: url,
            type: "POST",
            data: data,
            success: function(data) {
                alert('success');
            },
            error: function(xhr, ajaxOptions, error) {
                alert(xhr.status);
                alert(error);
            },
        });
        return true;
    });

PHP:

public function ajax()
{
       $input = $this->input->post();
       print_r($input['user']);
}

HTML:

<div id="container">
       <input type="hidden" name="token" value="8sdf243dfa426b2sfwe434fdg43gwsf" />
       <button type="submit" id="select">Select</select>
</div>

Description:

When i click the select button, i see the the result of the post action. The print_r($input) in the php function also returns the desired result. However, as i am not using a form to perform this submission, the browser does not redirect to the post action (/test/ajax/ in this case). I can see the redirect occuring on the firebug console, but the browser does not actually redirect to that link. When i try window.location = 'http://www.mybaseurl.com/'+url, i cannot access data anymore, i lose the data. How can i redirect the browser to the post action url and still retain the data?

Edited javascript:

$("#container").on('click', '#select', function() {
            data = {};
            val = {
                   "name": 'John',
                   "id": 10,
                    }
            data.user = JSON.stringify(val);
            data.token = $("input[name=token]").val();
            console.log(data);
            url = '/test/ajax/';
            $.post(url, data, function(data) {
            alert('success');
            });
            return true;
        });

Upvotes: 0

Views: 493

Answers (1)

mpriscella
mpriscella

Reputation: 381

The entire point of AJAX is that it doesn't redirect to the URL you define, it just sends data to it. If you want the user to go to the URL after the AJAX call is finished, you may not want to use AJAX. Just use a regular form.

<form method="POST" action="/test/ajax">
  <input type="hidden" name="token" value="8sdf243dfa426b2sfwe434fdg43gwsf" />
  <button type="submit" id="select">Select</select>
</form>

edit:

With the data you're sending, the form would actually look like

<form method="POST" action="/test/ajax">
  <input type="text" name="name" />
  <input type="text" name="id" />
  <input type="hidden" name="token" value="8sdf243dfa426b2sfwe434fdg43gwsf" />
  <button type="submit" id="select">Select</select>
</form>

Upvotes: 2

Related Questions