Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

innovation mecom's avatar

[SOLVED] Passing data from JS to Laravel Controller

Hello Community.

I have a system, that works completely in javascript and i want to sent a value to a Controller to my Route. My JavaScript looks like that:

GameManager.prototype.addValueSession = function (value) {
  this.value= value;
  $.ajax({
    type: "POST",
    url: '/session/storeValue',
    data: "",
    success: function() {
      console.log("Value added");
    }
  })
};

and my Controller like that:

public function storeValue(Request $request, $value)
{
      $request->session()->put('value', $value);
}

I don't know how to pass the data and how to write it to the current session. Thank you for your help.

0 likes
20 replies
katifrantz's avatar

But you have a data property in your $ajax object , so why not pass it with the post request ?


GameManager.prototype.addValueSession = function (value) {

  var data = { value : value };
  $.ajax({
    type: "POST",
    url: '/session/storeValue',
    data: data,
    success: function() {
      console.log("Valueadded");
    }
  })
};

And your controller will look like this :


public function storeValue(Request $request)
{
       session([ 'value' => $request->value  ]);
}

1 like
innovation mecom's avatar

Thank you for your fast answer!

I have changed it, but i get an Internal Server Error (500). My JS has as well a function (success), but it was never called. What should I do, to return a value to it and how can I solve the problem with the Internal Server Error?

giovanniciriello's avatar

try to insert a

Log::info($request);

in your controller to see if the server function is correctly called and if the request is correctly set

innovation mecom's avatar

Thank you @giovanniciriello . I have tried that too, but I am getting now this:

MethodNotAllowedHttpException in RouteCollection.php line 218:

What can I do to solve this?

giovanniciriello's avatar

This happens usually when you call a route with the wrong method with it was defined (POST or GET etc..)

innovation mecom's avatar

Yes, but I have a value, which I will take from the JS and sent it to the Router, where it will be added to the current session. I need a POST-Request at this point, because session isn't initialised then.

Maybe you have another idea. I am playing with Laravel for the first weeks.

giovanniciriello's avatar

Yes, you Can do it. But you have to define your route in this way

Route::post('url-to-route', 'Controller@method');
innovation mecom's avatar

It is defined exactly like that

Route::post('session/storeValue', 'SessionController@storeValue');
innovation mecom's avatar

Okey. I have a function in my JS-File, which calls this here:

GameManager.prototype.addValueSession = function (value) {
  var data = { value : value };
  $.ajax({
    type: "POST",
    url: '/session/storeValue',
    data: data,
    success: function() {
      console.log("Value added");
    }
  })
};

Then I have my Route, which I showed you before. This Route posts on this function in my SessionController:

public function storeValue(Request $request)
{
        session([ 'value' => $request->value]);
}

Thats it.

giovanniciriello's avatar

You probabily make a mistake when define the route in your js function. Try to remive the initial slash

katifrantz's avatar
Level 6

1 - Make sure in your routes file you have no other routes with the same path ( Like duplicate routes ) 2 - Then try tweaking your ajax function as such :

$.post("/session/storeValue",
    {
        value : value
    },
    function(data, status){
        alert('value stored');
    });

2 likes
willvincent's avatar

A 500 error should be getting logged.. somewhere. Check your log files

WebKenth's avatar

show us your Route file or your php artisan route:list output

When you have a MethodNotAllowedException in Route Collection it means your routes are conflicting

So if you have a route like Route::post('something/{id}', 'someController@method') it will override calls that use something like Route::post('something/somethingelse', 'someController@method') because of the wildcard

innovation mecom's avatar

So, I have changed the JS Method to your Ajax-Post-Request.

Here is my Routeslist:

+--------+----------+--------------------+------+------------------------------------------------------+--------------+
| Domain | Method   | URI                | Name | Action                                               | Middleware   |
+--------+----------+--------------------+------+------------------------------------------------------+--------------+
|        | GET|HEAD | /                  |      | App\Http\Controllers\SiteController@showLan          | web,web      |
|        | GET|HEAD | api/user           |      | Closure                                              | api,auth:api |
|        | GET|HEAD | description        |      | App\Http\Controllers\SiteController@showDescription  | web,web      |
|        | GET|HEAD | don                |      | App\Http\Controllers\DonController@showDon           | web,web      |
|        | GET|HEAD | ga                 |      | App\Http\Controllers\GaController@showGa             | web,web      |
|        | POST     | session/storeValue |      | App\Http\Controllers\SessionController@storeValue    | web,web      |
|        | GET|HEAD | top                |      | App\Http\Controllers\TopController@showTop           | web,web      |
+--------+----------+--------------------+------+------------------------------------------------------+--------------+

I am getting stil the same Error.

innovation mecom's avatar

Now I have tested something in my Function in my Controller and I got this here:

Failed to load resource: the server responded with a status of 500 (Internal Server Error)
http://localhost:8000/session/storeValue

My Controller looks now like that:

public function storeValue(Request $request)
    {
        dd($request);
        session([ 'value' => $request->value]);
    }
WebKenth's avatar

an error 500 means something went wrong serverside, what does the network console say?

Open up chrome dev tools, go to the network panel and click on the request that failed, then click on the preview tab

it will display the error

innovation mecom's avatar

I opened my DevTools and i had this here


Name        | Status  |  document    | Initiator   |  Size      | Time
storeValue  | 500     |  xhr         | ?d41d:9536  |  17.1 KB   | 203 ms  

In my Headers I have this:

Request URL:http://localhost:8000/session/storeValue
Request Method:POST
Status Code:500 Internal Server Error
Remote Address:[::1]:8000
Response Headers
view source
Cache-Control:no-cache, private
Connection:close
Content-Type:text/html; charset=UTF-8
Date:Thu, 20 Oct 2016 07:39:51 GMT
Host:localhost:8000
Set-Cookie:savevalue=eyJpdiI6Ikxqa0xXY2p1SjkxRkU4bWJuS0dXUmc9PSIsInZhbHVlIjoiMWhWZDRqNlZkWlwvejcrVXJaaWVyVE1CalBaa3g4TTJRQWdTRWduQ2JwXC9cL2N6RFE2NnNVbUhCZHpacWF1THdXYWpLWFZvd2tXcnprdVRwTFwvOVdYU01RPT0iLCJtYWMiOiJlMDA3ZjRhOTIyN2M5ZjFjYTZkMjU4M2ZmYjVhOGNkNjQzMzNjYjQ0ZDljZmUwY2U1MDQ0MTk5MmVlZjEzYWYzIn0%3D; path=/; httponly
X-Powered-By:PHP/5.6.21
Request Headers
view source
Accept:*/*
Accept-Encoding:gzip, deflate
Accept-Language:de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4
Cache-Control:no-cache
Connection:keep-alive
Content-Length:7
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Cookie:XSRF-TOKEN=eyJpdiI6IjFMOWxoR1V4U1R3cDI4SVNLR2FYc3c9PSIsInZhbHVlIjoiVkwrNkhMaFkzNXZzMkphVTVwdVlheE5UelJuYWJ4bkZYXC9LVEpBSlZEbFlpcGVkelhHUVNHaFRwWm9mTGd6NUJnSzR5Rk5pMjRDclRNdEZPdXd0eVBRPT0iLCJtYWMiOiI1M2M4MTg5YjcwZTUyZjhkZGQzZWEwZWRhNWUyZDZhMWVkNGVjZTc0Nzk1Mzg0MWViOWVkYjRhMWRmOWRhYzI2In0%3D; savepoints=eyJpdiI6InBZU1dFaVFISlA1RzVKS0dFZDJmVWc9PSIsInZhbHVlIjoialZVSHU3aWlBM0YwRGU4eHBBNFFiN0pIeXJIYVB2bkFUZFgzcnpXRDl0UTdTYWFMNkVnRFJuMGZFdTB1VlF2bmpVZHorZHJscGdkalRtcXR0Y3VvWEE9PSIsIm1hYyI6Ijg4YWE1OTA4ZjE1YzM0OTk3OTgzMjFhY2E3ZWQ3MjY3N2FjMmJhMmE5YmE3NTQ1MzBlMGIwZDMwODQ5Njg4NTcifQ%3D%3D
Host:localhost:8000
Origin:http://localhost:8000
Pragma:no-cache
Referer:http://localhost:8000/ga
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36
X-Requested-With:XMLHttpRequest
Form Data
view source
view URL encoded
value:0

My Preview shows this:

TokenMismatchException in VerifyCsrfToken.php line 68:

I don't know if this have something to do with the CSRF-Token. Hope we can solve this here. :)

innovation mecom's avatar

I have changed the JS-Function to that, and I got the "success" console.log.

var data = { value : value };
  $.ajax({
    type: "POST",
    url: '/session/storeValue',
    data: data,
    headers: {
      'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    },
    success: function() {
      console.log("Value added " + value);
    }
  });

Now I am getting the Message "Value added 0" in the Console in my Dev-Tools.

At this point I want to say a big Thank you, to them, who helped me to get to this point.

It is working now :)

Please or to participate in this conversation.