1
votes

I built an ajax post which sends each slider value (I am using jquery ui slider) to my controller.

The Ajax code:

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

$.ajax({
    type: 'post',
        contentType: "application/json",
    url: "{{ Route('editProductPost', $product->id) }}",
    headers: {
        'X-Requested-With': 'XMLHttpRequest'
    },
    data: JSON.stringify({
        value: getSliderVal,
        productId : getPrId
    }),
    datatype: 'json',
    success: function(response) {
        // get response
        console.log(response.sliderValue)
    }
});

And in my Controller I am doing this:

public function editProductPost(Request $request)
{
    Log::info($request->get('value'));

    return view('product.edit', [
        'sliderValue' => $request->get('value')
    ]);
}

This returns me the correct slider value,

Log::info($request->get('value'));

But I get this error message in my browser console:

POST http://localhost/myApp/public/product/edit/98 500 (Internal Server Error)

Later on I want to call this sliderValue inside of a php loop in my view.

Edit

I do have a csrf token:

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

Edit

I have done this:

    $sliderValue = $request->get('value');
    $route = 'updateProduct';

    return view('product.edit', compact(['sliderValue', 'route']))->render();

The console print me undefined and if I do this {{ sliderValue }} I get an error that sliderValue is not defined

2
If you get Log::info($request->get('value')); value, then you should return json data instead of view. - hizbul25
@hizbul25 I had done this earlier but I can't use the variable in the view like that (in my php loop) - utdev
add error:function(response){ console.log(response.responseText); } - jaysingkar
This will get you the error that's causing the issue. - jaysingkar
@jaysingkar thanks, that returns me alot in my console alot of html - utdev

2 Answers

0
votes

Little change of your code:

    public function editProductPost(Request $request)
    {
       Log::info($request->get('value'));
       $sliderValue = $request->get('value';

       return view('product.edit', compact('sliderValue'))->render();
    }
0
votes

The problem here is that you're returning a view in your controller. If your view used {{ $sliderValue }} inside it, it should work. But there's no way for javascript to get the sliderValue variable.

If you wanted the sliderValue as is, you can return this array

return [ 'view' => view('product.edit', compact(['sliderValue', 'route']))->render(), 'sliderValue' => $sliderValue ];

That way you're sending to javascript an object with 2 properties, one should contain the view and the second one will only contain the value.