Summer Sale! All accounts are 50% off this week.

sesc360's avatar

How do I make an AJAX request to a controller method

Dear all,

I have a few issues using AJAX requests to process form data. I would like to use the googlemaps API V3 in Javascript for geocoding purpose.

The workflow should be as follows:

  1. User enters StreetName into a form
  2. Street Form data is processed by GoogleMaps API JS on client side to reverse geocode to get lat/lng
  3. Form has an action to a controller function to process the data.
  4. In this function inside the controller the data will be stored to a database.

My problem is now this: The Lat/Lng Informatin by Google Maps API is client-side information whereas the rest of the stuff is processed server side. So I want to inform my server about this additional information as well.

Therefore I thought about using an AJAX request to pass this client-side information to the server. But I get stuck here. I do want to make sure, that before the server-side function in the controller is storing all information, the additional Lat/Lng info is added to the data before and then stored to the database.

Here

This is the JS method:

function reverseGeocodeAddress() {
    $.ajax({
        type: "POST",
        url: 'IncidentController@receiveReverseGeocodeInformation',
        data: "",
        success: function() {
            console.log("Geodata sent");
        }
    })
};

I want to use an AJAX request to send the information to the server. But how do I tell the method to which method in the controller I want to sent to? the method you see there should be the one that processes the info server-side.

Here is the the code I wrote so far:

Controller:

    public function createIncident(PrepareIncidentRequest $request)
    {
        $data = $request->all();
        $data = $data + [
                'incidentReference' => TicketSystem::generateIncidentReference(),
                'incidentID'        => TicketSystem::generateIncidentID(),
                'date'              => Carbon::now()->format('Ymd')
            ];
        $incident = Incident::create($data);
        Auth::user()->incidents()->save($incident);
    }

    public function receiveReverseGeocodeInformation(Request $request) {
        if(Response::ajax()) return "OK";
    }

JavaScript Function with AJAX request

function reverseGeocodeAddress() {
    $.ajax({
        type: "POST",
        url: 'IncidentController@receiveReverseGeocodeInformation',
        data: "",
        success: function() {
            console.log("Geodata sent");
        }
    })
};

I want to use a certain function in the controller to receive the information from the AJAX request. As you can see in the receiveReverseGeoCodeInformation method in the controller, I added some test response. But I don't get it to work. Do I miss something here?

0 likes
15 replies
sesc360's avatar

But I can't use this within a JS file?

Ozan's avatar

You can modify your function so that it accepts the URL you put in.

function reverseGeocodeAddress(url) {
    $.ajax({
        type: "POST",
        url: url,
        data: "",
        success: function() {
            console.log("Geodata sent");
        }
    })
};

A better option would be to create named routes and use that instead of action()

1 like
rodrigo.pedra's avatar
Level 56
  1. On your app/Http/routes.php file, create a route for this controller method:
    Router::post('geo-info-response', 'IncidentController@receiveReverseGeocodeInformation');
  1. Then in your ajax call use that route
function reverseGeocodeAddress() {
    $.ajax({
        type: "POST",
        url: './geo-info-response',
        data: "",
        success: function() {
            console.log("Geodata sent");
        }
    })
};
3 likes
sesc360's avatar

Hi Rodrigo, I tried that, but in the Console I see a 500 Internal Server Error.

TokenMismatchException in VerifyCsrfToken.php line 46:

How do I integrate the CSRF token?

Ozan's avatar

Put this to you head section

<meta name="csrf-token" content="{{ csrf_token() }}" />

Execute this code before you run ajax.

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});
3 likes
sesc360's avatar

Ah ok... But is this token not supposed to be hidden? Then when it is in the head section it would be visible to anyone?

Ozan's avatar

Only its attribute type is hidden.

rodrigo.pedra's avatar

Actually the token generated by the csrf_token() helper is the public token, which should be shared. laravel than compares it to the encrypted token info saved into the session. So no problem at all.

sesc360's avatar

So now I tested the whole thing like suggested and the CSRF issue is solved. But the response now is:

POST http://dev.server.de/incidents/geo-info-response 405 (Method Not Allowed)

I added like suggested:

Router::post('geo-info-response', 'IncidentController@receiveReverseGeocodeInformation');
function reverseGeocodeAddress() {
    $.ajax({
        type: "POST",
        url: './geo-info-response',
        data: "",
        success: function() {
            console.log("Geodata sent");
        }
    })
};
sesc360's avatar

I got it. the route should have been done 'incidents/geo-info-response'. Now it works perfectly fine. Thank you very much guys!!

Please or to participate in this conversation.