Steve
Steve

Reputation: 1672

Should I check for ajax request or not

AJAX:

$.ajax({
        type:"POST",
        url: "{{url('/post/add')}}",
        data: {
        "_token": "{{ csrf_token() }}",
        "id": id
        },

        success: function (data) {
          var res = $.parseJSON(data);
          if(res == true)
          {
              alert('hi');
          }
       }
   });

Laravel Controller: I have checked for the ajax request in the controller.

public function add(Request $request)
{
    if($request->ajax())
    {
        // codes 
        echo json_encode(TRUE);die;
     }
}

but, I noticed that I do not require to check for ajax request? And without checking if the ajax request how am i getting the alert?

  public function add(Request $request)
    {
            // codes 
            echo json_encode(TRUE);die
    }

Upvotes: 0

Views: 269

Answers (3)

Can Vural
Can Vural

Reputation: 2067

It just depends on you. You can do different things based on if the request is AJAX request or not. For example returning JSON or a normal view.

If you want your routes to be accessed by only AJAX requests maybe you can protect those routes with a middleware. Check this answer for more information about that.

Upvotes: 1

Alexey Mezenin
Alexey Mezenin

Reputation: 163768

You should use $request->ajax() to determine if the request is the result of an AJAX call. If you're working only with AJAX requests in your method, you can omit this check.

Upvotes: 1

alaric
alaric

Reputation: 987

The check is simply one additional measure of a valid request. It is not necessary as you've noticed, but if you'd like to verify that the request is coming via an AJAX request as you'd expect - you may.

Upvotes: 1

Related Questions