Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Using AJAX to pass Javascript variable to PHP and retrieve those

How can I use Ajax to pass a Javascript variable to Php and retrieving those?

I am using a Jquery Ui Slider and on each slide I want to pass the javascript slider value to php so to say.

I have no ( not much ) experience in Ajax and really appreciate help.

This is how my slider looks:

    $("#sliderNumCh").slider({
        range: "min",
        min: 0,
        max: 20,
        step: 1,
        value: numbersOfChapters,
        change : function(e, slider){
            $('#sliderAppendNumCh').empty();
            var i = 0;
            var sliderValue = slider.value;
            var getSliderVal = document.getElementById('sliderValue').value = sliderValue;

            $.ajax({
                type: 'POST',
                url: '',
                headers: {'X-Requested-With': 'XMLHttpRequest'},
                data: {
                    value: getSliderVal
                },
                success: function (option) {
                    console.log(getSliderVal);
                }
            });
            ...
      }
  })

My route example:

Edit my route looks like this now:

Route::post('edit/{productID}', ['as' => 'editProductPost', 'uses' => 'ProductController@editProduct']);

Edits what I have tried:

url: '{{ route("editProductWeb") }}',

and got this error:

POST http://localhost/myApp/public/product/edit/%7BproductID%7D 500 (Internal Server Error)

and tried this:

url: 'edit',

and got this error:

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

Edit my edit controller method:

public function editProduct($productRomID = 0)
{
    $product = ProductRom::find($productID);
    $sheets  = Chapters::where('product_id', '=', $productID)->get();

    $productId = $product->id;

    $sheetCount    = count($sheets);

    return view('product.edit', [
        'productId' => $productId,
        'product' => $product,
        'sheets' => $sheets,
        'sheetCount' => $sheetCount,
        'type' => 'edit',
        'route' => 'updateProductRom'
    ]);
}

Edit using haakym suggestion so far:

            $.ajax({
                type: 'post',
                url: "{{ Route('editProduct', $product->id) }}",
                headers: {'X-Requested-With': 'XMLHttpRequest'},
                data: {
                    value: getSliderVal,
                    productId : getPrId
                },
                success: function (option) {
                    console.log(getSliderVal);
                }
            });

does print me the id + the current slider value in my debug, so that works so far. Now I need to get that value and use it in my view(php) any suggestion how to proceed?

using this in my controller method:

$sliderValue = $request->input('value');

returns me

null

Edit I also tried this:

$sliderValue = Input::get('value');

which also returned me

null

Edit I added a Log:

Log::info(Input::all());

This shows the correct slider value and product id on slide. But my Input::get('value') still returns me null

Edit I think I should add this information:

I changed my routes to this now:

Route::get('edit/{productID}', ['as' => 'editProduct', 'uses' => 'ProductController@editProduct']);
Route::post('edit/{productID}', ['as' => 'editProductPost', 'uses' => 'ProductController@editProductPost']);

The get shows the data from the database for a specific product and shows them in my view, I added the post one to post the slidervalue data to the editProductPost method and returns afterwards the value(sliderValue) in the edit view, is this correct?(Btw still does not work)

EDIT

If I put this in my controller method:

if ($request->isMethod('post')){
    return response()->json(['response' => 'This is post method']);
}

return response()->json(['response' => 'This is get method']);

I keep getting the following error (if I slide):

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

I have this in my head:

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

and put this before my ajax post:

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

EDIT:

Doing this returns the correct current slider value in the logs:

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

I tried this:

    return view('productRom.edit', [
        'value' => $value,
    ]);

But I get an error in the console:

Failed to load resource: the server responded with a status of 500 (Internal Server Error) http://localhost/myApp/public/product/edit/73

like image 221
utdev Avatar asked Jul 18 '16 11:07

utdev


People also ask

How pass data from JavaScript to PHP using AJAX?

click(function() { var userID = $(this). attr('id'); //alert($(this). attr('id')); $. ajax({ type: "POST", url: 'logtime.

How do I pass variables and data from JavaScript to PHP?

The way to pass a JavaScript variable to PHP is through a request. This type of URL is only visible if we use the GET action, the POST action hides the information in the URL. Server Side(PHP): On the server side PHP page, we request for the data submitted by the form and display the result. $result = $_GET [ 'data' ];

How use JavaScript variable on same page in PHP?

You can easily get the JavaScript variable value on the same page in PHP. Try the following codeL. <script> var res = "success"; </script> <? php echo "<script>document.


1 Answers

As @julqas stated you need to include the URL in your $.ajax() method.

As you have a named route editProduct, you can output the link using blade:

$.ajax({
  type: 'POST',
  url: '{{ route("editProduct" }}',
  ...

Edit 1:

Your route is get and your ajax method is post, I guess this is the issue. You need to make them the same.

If you change the route to post you will need to add the CSRF token to the ajax request when it is sent. There is some guidance on the docs how to do this here:

https://laravel.com/docs/5.2/routing#csrf-x-csrf-token

The docs recommend adding this in your HTML head:

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

then use the following code before sending the request:

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

alternatively you can add it to the request in the ajax call.

Edit 2

A side point - I was just guessing what the error is, it would have been better if I'd asked you if you could debug it yourself in order to see what the error was. Learning to debug ajax requests is very useful and not too difficult.

The best way to do that is by using the developer console in your browser of choice when making the ajax request. If you're using Chrome for example open Developer tools and then click on the Network tab before making your request. After making the request you can inspect the request and its details. Hope that helps!

Edit 3

I would change your editProduct() method to not accept any parameter and instead get the id value for the product from the request

public function editProduct()
{
    // value here is referring to the key "value" in the ajax request
    $product = ProductRom::find(\Request::get('value');
    ...
}

Consider changing the value key in your json to something more useful, such as productId

data: {
    productId: getSliderVal
}
like image 81
haakym Avatar answered Oct 01 '22 00:10

haakym