I have a instance and category table. There is a many to many relationship between them. I need to fetch all the categories belonging to instance via a ajax request when the instance is selected from the dropdown menu. How do I achieve this?
$('#instance_id').change(function(){ var url = $('Form#CreateArticleForm').prop('action');//get the base url specified on the form var method = $('Form#CreateArticleForm').prop('method');//get method action var data = $('Form#CreateArticleForm').serialize();//get all the data submitted via form url = url + "/instanceCategoryDomain"; //say we wan to call instanceCategoryDomain() on controller $.ajax({ url: url, type: get_method, data: data, success: function(result) { var jsonResult = $.parseJSON(result); console.log(jsonResult); } }); });
Route::get('articles/instanceCategoryDomain', 'ArticlesController@instanceCategoryDomain');
class ArticlesController { public function instanceCategoryDomain() { $instance_id = Request::input('instance_id'); $output['instance'] = [$instance_id]; return json_encode($output); } }
$('#instance_id').change(function(){ var url = $('Form#CreateArticleForm').prop('action'); var method = 'get'; var instance_id = $(this).val(); url = url + "/instanceCategoryDomain/"+instance_id; $.ajax({ url: url, type: get_method, success: function(result) { var jsonResult = $.parseJSON(result); console.log(jsonResult); } }); });
Route::resource('articles/instanceCategoryDomain/{instance_id}', 'ArticlesController@instanceCategoryDomain');
class ArticlesController { public function instanceCategoryDomain($instance_id) { $output['instance'] = [$instance_id];//suppose return json_encode($output); } }
Hope this helps!