Veljko Stefanovic
Veljko Stefanovic

Reputation: 511

Getting value from request in Laravel using ajax

I have this ajax method in PostsController

public function ajax(Request $request)
    { 

        //dd($request);
        $this->authorize('view', Post::class);

        $posts = Post::orderBy("created_at","desc")->paginate(5);
        $comments = Comment::all();

        return response()->json(array("posts"=> $posts, "comments"=> $comments), 200);

    }

which works great when you just getting data and sending it. So i tried besides requesting data by ajax, to send some data alongside ajax request. How can i access that data inside controller?

Here is a method which resides inside certain blade:

function ajax(){

  let var1 = "gg";
  let var2 = "bruh";
  let token = document.querySelector("meta[name='csrf-token']").getAttribute("content");
  let url = '/posts';

  $.ajax({
    type: "POST",
    url: url,
    headers:
        {
            'X-CSRF-TOKEN': token
        },
    data: {
        'var1': var1,
        'var2': var2
    },
    success: function(data) {
        console.log(data);
    }
  });         

}

To simplify: How can i, dd() or dump(), given data(var1 & var2) by ajax function from blade in PostsController?

Here is route:

Route::post('/posts', "PostsController@ajax");

And here is some "gibberish" when i try to dd() it: gibberish

Upvotes: 0

Views: 1192

Answers (2)

tohasanali
tohasanali

Reputation: 934

dd() is a laravel function and dump()for php. so you cannot use them from javaScript.

You cannot dd() or dump() from direct ajax request or JavaScript.

What you can do is, console log your data, or check from browser developer portion, network tab to see which data you are getting from the ajax response. You can find browser developer portion in,

for chrome:

Insepect > Network 

for mozila:

Insepect Element > Network 

If you are telling about get var1 and var2 on controller, you can just get them by $request->var1 and $request->var2.

Upvotes: 3

Veljko Stefanovic
Veljko Stefanovic

Reputation: 511

Hasan05 was right. Just needed to know right direction. So to get data parameter of ajax request i modified ajax controller method:

public function ajax(Request $request)
    { 
        $var1 = $request->input('var1');
        $var2 = $request->input('var2');

        $this->authorize('view', Post::class);

        $posts = Post::orderBy("created_at","desc")->paginate(5);
        $comments = Comment::all();

        return response()->json(array("posts"=> $posts, "comments"=> $comments, "var1"=> $var1, "var2"=> $var2), 200);

    }

Upvotes: -1

Related Questions