without select category not show subcategory

后端 未结 2 1455
独厮守ぢ
独厮守ぢ 2021-01-28 00:38

This is create.blade.php file. In this include css and js file too.. Html code and ajax code view file

2条回答
  •  一个人的身影
    2021-01-28 01:00

    you have done silly mistake , you are sending ajax request on change of category select dropdown to your create function , while your create function is rendering view post.create instead of return json response to ajax request .

    so now what you can do ? 2 options available to you :

    option 1 : create other function named "get_subcategory_by_category_id" and that will return subcategories in json , also create new route in routes/web.php for same .

    option 2 : laravel provide $request->ajax() to detect that request is ajax or not ? so use that and return response in json , so you will get response .

    public function create(Request $request){
        $categories = Category::all();
        $subcategories = DB::table('subcategories')
                            ->where('category_id', $request->category_id)
                            ->pluck('subcategory', 'id');
    
        if($request->ajax()){
            $response=array('categories'=>$categories,'subcategories'=>$subcategories);
            return response()->json($response,200);
        }
        return view('post.create', compact('categories', 'subcategories'));
    }
    

    your ajax function should be like below :

    
    

    make sure that your request url is proper , also check Inspect Element > Network tab for ajax request response .

提交回复
热议问题