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>