简体   繁体   中英

pass ajax values into laravel controller

This is my ajax request and i'm trying to pass those values into a controller in laravel

var deviceid="<?php echo $id; ?>";
var day="<?php echo $day; ?>";

$.ajax({

    'async': false,
    'global': false,
    url: '/location/show/getLocation/{id}/{date}',
    dataType: 'json',
    type: 'GET',
    data: { id:deviceid,date:day},

    success:function(data){
        myVariable=data;
        console.log(data);
    }
});

In my controller i got these values as

$id=$_GET['id'];
$date =$_GET['date'];
echo $id.$date;

But values doesn't show in console can anyone tell me the issue??

edited code

view

<script>  
var deviceid="<?php echo $id; ?>";
var day     ="<?php echo $day; ?>";
// console.log(deviceid,day);
$.ajax({

    'async': false,
    'global': false,
    url: '/location/show/getLocation',
    dataType: 'json',
    type: 'POST',
    data: { id:deviceid,date:day},

    success:function(data){
        console.log(data);
    }
});
</script>

controller

public function getLocation(Request $request)
{       
$id=$request->input('id');
$date=$request->input('date');
echo $id;
echo $date; exit;
}

route

Route::post('location/show/getLocation', 'DemoController@getLocation');

in your ajax call...

var deviceid="<?php echo $id; ?>";
var day="<?php echo $day; ?>";

$.ajax({

'async': false,
'global': false,
url: '/location/show/getLocation',
dataType: 'json',
type: 'POST',
data: { id:deviceid,date:day},

success:function(data){
   var myVariable=data;
    console.log(data);
}
});

your route.php like

Route::post('location/show/getLocation/', 'demoController@getlocation');

define your controller name and function name which is you call on ajax

now in Controller add "getlocation function".

public function getlocation(Request $request)
{       
    $id=$request->input('id');
    $date=$request->input('date');
    echo $id;
    echo $date; exit;
 }

dont forgot to add use Illuminate\\Http\\Request; in Controller file if you dont add this line then Request method does not work.

if you want returning something so just do your result in jason decode which is response in ajax suceess then as you wish

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM