Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a view from laravel controller function upon ajax call?

I am working on a bookstore project where books can be added to cart, a user can select many books for adding them to cart. when the user clicks on the Add to Cart button, I am adding the IDs of the selected books in a JS array called cart. When all the selected books are added to the cart then I want to link <a> tag with ajax call that will hit the url of a controller function and will send the JS cart array object to the controller function and then in the controller function, I want to return view to the browser, I do not want the controller function to return the response back to the ajax call but instead I want to return the view to the browser.

Here is the JS function that adds the ID of the selected books to the cart JS array:

function addToCart(id)
{
if(! cart.includes(id) ) cart.push(id);

cartLength.html(cart.length);
$('#successCart'+id).html('Book added to cart.');

}  

Here is the <a> tag that calls the ajax function, the function name is showCart():

<a href="#" onclick="event.preventDefault(); showCart();">
  <i class="fa fa-shopping-cart"></i>
  <span id="cartLength"></span>
</a>  

Here is the showCart() function that has ajax code:

function showCart()
{


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

$.ajax({
        url:"cart",
        method:'post',
        data:{cart:cart},
        dataType: 'html'
  })
 .done(function(msg){


  });
 .fail(function(msg){
    alert(msg.responseJSON.errors);
 });
}  

Here is the controller function - I want this function to directly return the view to the browser without sending it back to the ajax call:

public function showCart(Request $request)
{
    return view('cart', ['cart' => $request->cart ]); // this should be returned to the browser and not to the ajax call
}  

Here is the route for the controller function:

Route::post('/cart', 'HomeController@showCart')->name('home.cart');  

EDIT:

I have temporarily solved the issue with the following tricks but that is not a permanent solution:

After calling the showCart() function from ajax for sending the cart array variable from js to laravel controller, I used the following logic to store the books in a session variable whose ids are stored in the cart array:

public function showCart(Request $request)
{

    session()->put('cart_books', Book::whereIn('id', $request->cart)->get()); 
    session()->save();
    return "success";

}  

After storing the result of the query in a session variable, I created another GET route for /cart as below:

Route::get('/cart', 'HomeController@viewCart');  

Then upon success of the post ajax call, I called /cart with get method as below:

.done(function(msg){
    console.log('calling cart');
    location.href = "cart"; // Here I call the `/cart` with `get` method which will hit the `viewCart()` function of HomeController which will return the view back to the browser along with the results that were stored in the session variable.

  })  

And this is the viewCart() controller function that returns the view to the browser and sends the session variable's data to the view:

public function viewCart()
{
   $random_books = Book::all()->random(4);
   $categories = Category::all();
    return view('cart', ['cart_books' => session()->get('cart_books'), 
  'random_books' => $random_books, 'categories' => $categories]); 
}

I want the controller function to return the view to the browser without returning it to the ajax call, any help is appreciated in advance.

like image 332
Abdul Raheem Ghani Avatar asked Aug 04 '20 16:08

Abdul Raheem Ghani


People also ask

How can I return a view from an ajax call in laravel?

return response()->json( array('success' => true, 'html'=>'<span>html here</html>') ); This works just fine.

Which function returns a view in laravel?

Views may also be returned using the View facade: use Illuminate\Support\Facades\View; return View::make('greeting', ['name' => 'James']); As you can see, the first argument passed to the view helper corresponds to the name of the view file in the resources/views directory.

Can we return a value from ajax call?

You can't return "true" until the ajax requests has not finished because it's asynchron as you mentioned. So the function is leaved before the ajax request has finished.


1 Answers

You can return Raw html from ajax call by rendering and returning the view inside your controller as,

return view('cart', ['cart' => $request->cart])->render();

This will return the raw HTML and you can further use it. However, returning HTML from ajax is not a good way, You can return JSON from the controller and render the view in frontend according to the JSON data.

like image 110
Kiran Maniya Avatar answered Oct 30 '22 01:10

Kiran Maniya