Rakesh Shakya
Rakesh Shakya

Reputation: 21

How to send Ajax data in controller

I want to recommend the visitors the hotels near by him based on his current location. My problem is how to get not login user latitude and longitude so that i can recommend him nearby hotel.

home.blade.php

    <script>
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (position) {
            console.log(position);
            var lat = position.coords.latitude;
            var lng = position.coords.longitude;

            $.ajax({
                url:'http://localhost:8000/getgeo',
                type:'get',
                data:{latitude:lat,longitude:lng},

//even when  i set some value here data:{latitude:1222323}, i did not get `1222323` in controller


                success:function(data)
                {
                    alert('success');
                }

            });
        });
    }

    </script>

I got null in controller controller:

public function geo()
{
    return view('home');

}
public function getCoordinate(Request $request)
{
    return $request->latitude;
}

Here i am getting latitude and longitude at console in home.blade.php page .But now got in controller

Route:

Route::get('/geo', 'ProductController@geo');

Route::get('/getgeo', 'ProductController@getCoordinate');

Upvotes: 1

Views: 87

Answers (1)

kunal
kunal

Reputation: 4248

Change following points:-

change ajax url : url:'/getgeo'
And function :-
public function getCoordinate(Request $request)
 {
  if($request->ajax()){
    $data = $request->all();
    echo "<pre>"; print_r($data); // print all data here 
  }

 }  
 Try to change Route:-
 Route::any('/getgeo', 'ProductController@getCoordinate');

Upvotes: 1

Related Questions