Halnex
Halnex

Reputation: 4526

Form redirecting to route on ajax request in Laravel 5

I am trying to add ajax functionality to a like button.

Everything works, except that I get redirected to a page with json data after I click the like button.

I am using e.preventDefault() and it's still redirecting me.

If I use on('click') I get a TokenMismatch error in the console log even though I have included a hidden input with a token.

jquery.min.js:4 POST http://localhost/socialnet/public/likeStatus 500 (Internal Server Error)

If I use on('submit') the data goes through but I get redirected to the page with the json response.

This is in my controller FeedController@likeStatus()

public function likeStatus() {

    if (Input::has('like_status')) {
        $status = Input::get('like_status');
        $selectedStatus = Status::find($status);

        $selectedStatus->likes()->create([
            'user_id' => Auth::user()->id,
            'status_id' => $status
        ]);

        $response = array(
            'status' => 'success',
            'msg' => 'You have liked this status',
        );

        return Response::json($response);
    }
}

The view

{!! Form::open(['action' => 'FeedController@likeStatus', 'id' => 'like_form']) !!}
    {!! Form::hidden('like_status', $status->id) !!}
    {!! Form::hidden('user_id', Auth::user()->id) !!}
    <button type="submit" name="likeStatus" class="btn btn-info btn-xs" id="like-status">
          <i class="fa fa-thumbs-up"></i> Like ({{ $likes_count }})
    </button>
{!! Form::close() !!}

The Javascript

$('#like-status').on('click', function(e){
    e.preventDefault();

    var status_id = $('input[name=like_status]').val();
    var user_id = $('input[name=user_id]').val();

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').val()
        }
    });

    $.ajax({
        url: 'http://localhost/socialnet/public/likeStatus',
        method: 'post',
        data: {status_id: status_id, user_id: user_id},
        success: function( data ) {
            console.log(data.msg);
        }
    });
});

EDIT: I just added the CSRF token into a variable and added it to the data

    var status_id = $('input[name=like_status]').val();
    var user_id = $('input[name=user_id]').val();
    var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');

    $.ajax({
        url: 'http://localhost/socialnet/public/likeStatus',
        method: 'post',
        data: {status_id: status_id, user_id: user_id, _token: CSRF_TOKEN},
        success: function( data ) {
            console.log(data.msg);
        }
    });

This gives Status Code: 200 in the Network tab but gives undefined in the console and no data is going through.

EDIT 2: Something very weird is happening. I get undefined in the console when I try to like the newest status, and nothing happens. But it works when I like previous (old) status, however when I click the like button I get redirected to the json data page and data goes through.

What am I doing wrong?

Upvotes: 2

Views: 1672

Answers (4)

Yanaro
Yanaro

Reputation: 345

It seems that the problem lies in your PHP code, it looks for like_status with

if (Input::has('like_status'))

but you send

{ 
 status_id: status_id, 
 user_id: user_id
}

There's no like_status to be found. Input::has... will return false. Your code essentially turns into

public function likeStatus() {

   if (Input::has('like_status')) { //It's always false
    //
   }
  return undefined;
}

Upvotes: 0

Mohamed Akram
Mohamed Akram

Reputation: 2117

That mean your ajax call not working at all, first make sure you have Javascript enabled in your browser and jquery is included,if its, then try to change button type submit to button, if the button is being generated dynamically you may try the live function too

 $('#like-button').live("click",function(){   })

try to debug with alert with jquery submit call to make sure the function being called

Upvotes: 1

Ahmed Sayed Sk
Ahmed Sayed Sk

Reputation: 684

You need to add this line in success AJAX function

var new_data = JSON.parse(data);

to decode you data has coming from request

Upvotes: 0

Daniel Waghorn
Daniel Waghorn

Reputation: 2985

You should use .on('submit') as that way you can correctly prevent the form's default action of redirecting.

As it stands you're trying to cancel a click event on #like-status.

Ensure that the start of your jQuery function is:

$('#like_form').on('submit', ... 

Just to be extra safe to ensure that the event handlers get bound correctly you should also bind within $(document).ready as below:

$(document).ready( function () {

    $('#like_form').on('submit', ... 

}

Upvotes: 0

Related Questions