Danielle Rose Mabunga Danielle Rose Mabunga - 5 months ago 18
Ajax Question

Retrieving value from Ajax in Laravel 5.2

I want to retrieve the value from ajax, use it as a value when saving in the database

$("ul.dropdown-menu li").click(function() {
par = $(this).find("span.widgets").html();
$.ajax({
url: '/partA-save',
type: "POST",
data: {
'test': latest,
'widget': par,
_token: CSRF_TOKEN
},error:function(log) {
console.log(log);
}
});
console.log(par);
return true;
});


In console, the par variable correctly log the value when a user click the li inside ul. Now I want to use it in the controller for an if else statement

public function save(Request $request)
{
$newdata = $request->input('test');

$newWidget = $request->input('widget');
if ($newWidget == 'COST') {
$us = new Cost();
$us->api = $newWidget;
$us->save();
} else {

$us = new Map();
$us->api = $newWidget;
$us->save();
}
}


route

Route::post('/partA-save','PartAController@save');


Even if the user choose the COST, the controller always use the code in the else block. Any idea what I am lacking here? Also, how to debug this in the controller so that I can see whats in side in the variable $newWidget. If I change this like

date: { 'widget': 'COST'


saves to COST.

using var_dump or dd return null.How to correctly set the value in Ajax?

Answer

Try the below code

Change Your URL Calling From Ajax

$("ul.dropdown-menu li").click(function() {
    par = $(this).find("span.widgets").html(); 
  $.ajax({
    url: '{{url("/partA-save")}}',
    type: "POST",
    data: {
    'test': latest,
    'widget': par,
    _token: CSRF_TOKEN
    },error:function(log) {
    console.log(log);
  }
  });
  console.log(par);
  return true;
});

In Controller Replace Input with get method of request.

public function save(Request $request)
{
    $newdata = $request->get('test');

    $newWidget = $request->get('widget');
    if ($newWidget == 'COST') {
        $us = new Cost();
        $us->api = $newWidget;
        $us->save();
    } else {

        $us = new Map();
        $us->api = $newWidget;
        $us->save();
    }
}