Ad

Deployed Laravel App Can't Handle Variables Passed To Controller Via Ajax

- 1 answer

I created a Laravel app in my local environment and it works just fine. When I deployed it to a VPS server, for accessing it online, for some reason, my AJAX stopped working. Here's an example of a very simple AJAX function which works in local, but doesn't work in my server.

The view:

<html>
<head>
    <title>Ajax Example</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
    </script>

    <script>
        function getMessage() {
            $.ajax({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                type: 'GET',
                url: '/getmsg',
                data: {
                    greeting: 'Hello'
                },
                success: function (data) {
                    $("#msg").html(data.msg);
                }
            });
        }
    </script>
</head>

<body>
<div id='msg'>This message will be replaced using Ajax.
    Click the button to replace the message.
</div>
<?php
echo Form::button('Replace Message', ['onClick' => 'getMessage()']);
?>
</body>

</html>

The controller:

class TestAjaxController extends Controller {
    public function index(Request $request) {
        return response()->json(array('msg'=> $request->greeting), 200);
    }
}

The route:

//Test routes
Route::get('ajax-test',function() {
    return view('ajax-test');
});
Route::get('/getmsg','[email protected]');

All this function does, is by clicking a button it send a defined variable to the controller and the the controller returns a response with the same message to the view and then Jquery changes the text to the message.

The problem is when the button is pressed no data is being passed to the controller, so the controller returns empty array.

Note: My local environment uses Apache (XAMPP), but my VPS uses NGINX. Altho I doubt it is the problem here.

I am totally lost in what could be wrong. Maybe there are some PHP modules missing from my VPS install or something similar?

Ad

Answer

So for some reason i just needed to use POST methods. I don't know why everything was working locally with GET, but on production server I had to use POST.

Here is the working code: View:

<script>
    function getMessage() {
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'POST',
            url: '/getmsg',
            data: {
                greeting: 'Hello'
            },
            success: function (data) {
                $("#msg").html(data.msg);
            }
        });
    }
</script>

The route:

Route::get('ajax-test',function() {
    return view('ajax-test');
});
Route::post('/getmsg','[email protected]');
Ad
source: stackoverflow.com
Ad