samedi 29 octobre 2016

Laravel 5.3- How call controller using AJAX function inside view

hi folks I'm newbie to Laravel and got stuck while working. I'm trying to call a controller function on onload from AJAX which will return me the categories stored in database but it gives me following error

MethodNotAllowedHttpException in RouteCollection.php line 218:

My Question/Queries

  • How to call Laravel Controller using AJAX function?
  • And how to display it in li?
    Thanks for helping me out :)
    here is the code

create_category_table.php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateCategoryTable extends Migration
{
/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create  ('categories',function($table)
    {
        $table->increments('category_id',true);
        $table->string('category_name');
        $table->text('description');
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    //
}
}

AjaxOperationController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use App\Http\Requests;

class AjaxOperationController extends Controller
{
public function category($category){
    $category=DB::select('select category_name from categories');
    return response()->json(array('category_name'=> $category), 200);
}
}

header.php (View)

 <script>
 $(document).ready(function(){
        $.ajax({
           type:'POST',
           url:'/category',
           data:'_token = <?php echo csrf_token() ?>',
           success:function(data){
              //$("#msg").html(data.msg);
              alert(data);
           }
          });
         });
</script>

routes.php

 Route::post('/category','AjaxOperationController@category');
 Route::post('/category/{category}', 'AjaxOperationController@category');



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire