Friday, March 20, 2020

Laravel ajax from submit by serializeArray

AJAX ` $(".submit").click(function(e) {
    e.preventDefault();

var formSelector = $(this).data("form");
    var form = $("#" + formSelector);
    var url = form.attr('action');
    var product = form.serializeArray();

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': csrf
        }
    });
 
    $.ajax({
        type: "POST",
        url: url,
        data: product,
        success: function(returndata){
            //debugger;
            location.reload();
        }
    });`
routes.php Route::group(['prefix' => 'admin'], function(){ Route::post('categories/add', BackendPagesController@addCategory'); });
BackendPagesController.php ` public function addCategory(Request $request){
    $name = $request->input('category-name');
    $categoryUrl = $request->input('category-url');
    $parentCategory = $request->input('kategorie');
    $categoryImageUrl = $request->input('category-image-url');

    if($parentCategory == "keine"){
        $parentCategory = 0;
    }

    $position = Categories::max('order_by');

    $category = new Categories;

    $category->name = $name;
    $category->url_alias = $categoryUrl;
    $category->parent_id = $parentCategory;
    $category->image_url = $categoryImageUrl;
    $category->meta_title = $request['meta-category-title'] ?? '';
    $category->meta_description = $request['meta-category-description'] ?? '';
    $category->order_by = $parentCategory;

    $category->save();

    if($category->id){                
        return $category->id;                   
    }else{                    
        return "wurde nicht eingetragen";
    }
        
}