URL :: action not working in jquery ajax

I am using laravel 4.2 and trying to update data using ajax, but in ajax redirect url does not work for me. Because I use URL: an action like,

$.ajax({
    type: 'POST',
    dataType: 'json',
    url : "store",
    data: { title: postTitle['post-title']['value'], body: postContent['post-body']['value'] },
    success: function(data) {
        if(data.success === false)
        {
            $('.error').append(data.message);
            $('.error').show();
        } else {
            $('.success').append(data.message);
            $('.success').show();
            setTimeout(function() {
                window.location.href = "{{ URL::action('PostsController@index') }}";
            }, 2000);
        }
    },
    error: function(xhr, textStatus, thrownError) {
        alert('Something went wrong. Please Try again later...');
    }
});

I do not know why it does not work. please help me.

+4
source share
3 answers

You need to add the route to the routes file:

Route::post('post', 'PostsController@index');

But if you have enabled CSRF, you also need to publish the CSRF code. You can do this by adding it to your "data".

...
url : "{{ url('store') }}",
Data: data: { title: postTitle['post-title']['value'], body: postContent['post-body']['value'] }, _token: {{ csrf_token() }},
...

I was hoping this would work for you!

+2
source

, . JS- , .

, JS PHP- ( -MVC). . . () JS ..

JS PHP -

URL :

window.location.href = "/post/something";

URL::

Route::post('post/something', 'PostsController@postSomething');
+1

Add the route to the route file:

Route::get('post','PostsController@index');

change js to:

 setTimeout(function() {
                window.location = "<?php echo URL::action('PostsController@index') ?>";
            }, 2000);

or

   setTimeout(function() {
                    window.location = "<?php echo action('PostsController@index') ?>";
                }, 2000);
0
source

All Articles