0

As you can see the js and html code below are in the same page. When I press the button, ajax will return Item json. My goal is to know whether it is possible to return the json response with the $item variable at the same time in test function. This is because I wanted to use the $item variable in view blade. If so, then how to do it?

Controller

public function index()
{
    $furniture = Furniture::all();

    return view('index', compact('furniture'));
}

public function test(Request $request)
{
    $item = Item::findOrFail($request->item_id);

     return response()->json([
         'data' => [
             'success' => $item,
             'key1' => "hello",
             'key2' => "world",
         ]
     ]);
}

JS

$(document).on('click', '.edit_modal', function() {
var item_id = this.id;
$.ajax({
    type: 'POST',
    url: "{{ URL::route('test') }}",
    headers: {'X-CSRF-TOKEN': '{{ csrf_token() }}' },
    data: { "item_id" : item_id},
    success: function(data){
      if(data.data.success){
            $('#edit_id').val(data.data.success.id);  // this will output the id eg. 1
            $('#edit_desc').val(data.data.success.description); // this will output the description eg. "hi there"
            console.log(data.data.key1); // this will output "hello"
            console.log(data.data.key2); // this will output "world"
      }
    }
});

View

<button type="button" class="edit_modal btn btn-primary" id="{{ $furniture->item_id }}">Button</button>
LearnProgramming
  • 814
  • 1
  • 12
  • 37
  • yes...of course. You can return anything you like. just include $item somewhere in your response()->json structure.... it will get serialised into JSON – ADyson Jul 17 '18 at 14:44
  • @ADyson like this? `return response()->json([ 'data' => [ 'success' => $item, 'key1' => "hello", 'key2' => "world", ], $item ]);` ....so in view, i could use dd($item)? – LearnProgramming Jul 17 '18 at 14:47
  • You shouldn't be using AJAX if you want to load a view after the request. You can't pass a PHP variable to javascript via AJAX. The view has already rendered from PHP and been sent to your browser by the time the page loads. – Devon Bessemer Jul 17 '18 at 14:47
  • @Devon not sure what you're getting at. The "test" PHP method called by the ajax request generates the $item variable within that context, so it should be possible to return it. – ADyson Jul 17 '18 at 14:49
  • @ADyson "This is because I wanted to use the $item variable in view blade". The OP seems to be confused about when PHP renders the view. You can't run an AJAX request and have the blade view read the response. – Devon Bessemer Jul 17 '18 at 14:49
  • @learnprogramming exactly, something like that, although you probably want to give the item a key to refer to it by, so you can easily access it from JavaScript like you do with the `data` object.. so maybe `return response()->json([ 'data' => [ 'success' => $item, 'key1' => "hello", 'key2' => "world", ], "item" => $item ]);` for instance. – ADyson Jul 17 '18 at 14:50
  • @Devon I'm not a laravel expert so perhaps "blade" is term I'm not familiar with, but given the code above where OP is returning other JSON, and using the successfully in the JS code, I assumed, they simply wanted to add this extra data in and use it in a similar way when the AJAX returns. It can of course be used to alter the page's HTML in any way desired at that moment. But maybe that phrase means something specific I wasn't aware of. – ADyson Jul 17 '18 at 14:51
  • 1
    Blade is the PHP templating engine included with Laravel – Devon Bessemer Jul 17 '18 at 14:52
  • @ADyson i just edit my code into what you provided, and i put `dd($item)` in view, i got an error `Undefined variable: item` – LearnProgramming Jul 17 '18 at 14:53
  • @learnprogramming perhaps there is some confusion. Your data will be available in JavaScript within the "success" function of your AJAX request. You'll be able to `console.log(JSON.stringify(data.item));` for instance. Or use that data to change something in your HTML. As Devon explained, since you create this variable during an ajax request, it isn't available until the ajax request completes. It's not available at the time when your view is first created - that happens in a different PHP method. – ADyson Jul 17 '18 at 14:57
  • @learnprogramming ....I assume it's the "index()" method you showed which is the one which creates your view? If you wanted this item data to be available when the view is created, you'd have to run that query inside that method, not in the "test" method. But of course, at that time you don't know the required Item ID. So you have to do it via AJAX. Which means you have to write some JavaScript which will use that data to update your HTML. Unless of course you dump the ajax and use a regular post back to send the data and render a whole new view (instead of returning JSON), as Devon mentions. – ADyson Jul 17 '18 at 14:58

1 Answers1

2

Blade views are rendered server side. The rendering has completed by the time the view is displayed on your browser.

When you run an AJAX request, there is no further rendering in the current view (by Blade or PHP). Therefore, you cannot pass additional variables through AJAX to the blade template.

If you really want this functionality, it seems strange that you are using AJAX to begin with. You should just submit the form normally and render a new view from the server side with the $item passed to that view. When using AJAX, you'll want to return a response Javascript can understand (JSON), not that PHP can understand, since Javascript will be rendering the response on the client side.

Read more about the difference between server side and client side programming here: What is the difference between client-side and server-side programming?

Devon Bessemer
  • 34,461
  • 9
  • 69
  • 95