Search code examples
javascriptphpajaxlaravellaravel-blade

Laravel javascript variable get in blade file


I need get js var in view blade file. I got this one in Controller and got success in console in route file

Route::post('/some-route', [Controller::class, 'someMethod']);
Route::post('/some-route', 'Controller@someMethod');//this also work

in js file in $("#applyBonus").on("click", function () method

$.ajax({ 
    url: base_url + '/some-route', // The route to your Laravel controller 
    type: 'POST', 
    data: { 
        someVarName: someInput, // someInput is from blade file input value. got successfully 
         
    }, 
    success: function(response) { 
        console.log(response); //success
        alert("ssuccessss___" + someInput); //success
        
    }, 
    error: function(xhr) { 
        console.error(xhr.responseText); 
        alert("error___");
    } 
}); 

in Controller

public function yourMethod(Request $request) { 
    //$variable = 'someVarName'; //this also work
    $variable = $request->input('someVarName'); 
    
    //return view('frontend.checkout', compact('variable')); // this also work
    //return view('frontend.checkout')->with('variable'); //this also work
    return view('frontend.checkout')->with('variableName', $variable);//success in console and alert message
} 

and now I tried to get this $variable in view.blade.php

@foreach($variable as $varr) //undefined $variable
       <div class="row">{{ $variable }}</div>
       <div class="row">{{ $varr }}</div>
@endforeach

or

echo $variable;
//or next. also span tag
<div class="row">{{ $variable }}</div>

and all time I get error - $variable is undefined

with I want do is to get input value as php $variable. maybe there other to get $variable from input value without page refresh? or How get this variable from controller in view blade file? Thanks

try get input value via input value->js var -> controller -> blade file. on last step get error $variable undefined


Solution

  • Okay ,I assumed that your main blade file is checkout.blade.php and view.blade.php(as per your shared code) file is the page where you want to update the data that will be reflected also in the checkout.blade.php after successful AJAX call.

    Follow these steps ..

    1. In the controller method load the view.blade.php.Do this.

       public function yourMethod(Request $request) { 
         $variable = $request->input('someVarName');
      
         // here `$variable` may not be in array format unless you fetch record from database.
         // So convert it to array if necessary
         if (!is_array($variable)) {
            $variable = [$variable];
         }
      
         //Return a partial view (in you case `view.blade.php`)
         return view('path-to-your-view.blade.php', compact('variable'))->render();
         //Or you can send data like this in JSON-format
         return response()->json([
           'html' => view('path-to-your-view.blade.php', compact('variable '))->render()
         ]);
       } 
      

    Here in controller method return the view.blade.php file where you want to show the data after the successful AJAX call. Remember to send the $variable array format.

    1. In the main view file i.e. checkout.blade.php(as per your code) add this lines of code where you want to show your data.

      <div id="variable-container">
        {{-- Rendered data from the AJAX call will be injected here --}}
      </div>
      
    2. Finally in the AJAX code do this in this particular section.

       success: function(response) { 
         // Inject the rendered view into the #variable-container div
           $('#variable-container').html(response); 
         //In case you send JSON response from Controller
           $('#variable-container').html(response.html)
      
         console.log("View rendered successfully");
         alert("ssuccessss___" + someInput);
       }, 
      

    After loading frontend.checkout file whenever $("#applyBonus").on("click", function ().. gets triggered AJAX will update the data in the view.blade.php file without even refreshing the page which will also be reflected in checkout.blade.php as well automatically.

    Try this once ,it will work for sure if your AJAX-call returns data. Still if something goes wrong then don't bother to ask me.

    EDIT :-

    In case you need input value as php $variable in the respective blade file you can do this in the controller.

    public function yourMethod(Request $request) { 
       $variable = $request->input('someVarName');
    
       //Either store the input value in the session using `request` instance
       $request->session()->put('variable', $variable);
    
       //Or, store the input value in the session using the global "session" helper...
       session(['variable', $variable]);
    
      //--Do all the other related task in the method & send response--//
       
     }
    

    This session not only will set the input value but also override it with each request.

    After you set the $variable in the session variable , You can get it as PHP variable in the blade template like this.

    @php
        $responseData = session('variable', 'No data available');
    @endphp
    
    <div>
        <p>Response Data: {{ $responseData }}</p>
    </div>
    

    In this particular scenario please avoid the 1st part of the answer before EDIT section.