Search code examples
phpajaxlaravel-5

how to store multiple form with multiple buttons data on single page using ajax in laravel


This is my form and I don't want to any change or form action and button id:-

<form action="store" method="post">
<input type="text" class="form-control" id="add_related_product" name="addons_heading" value="<?php if (isset($setting['addons_heading'])){echo htmlentities($setting['addons_heading']);}?>">
<input type="text" class="form-control" id="label_quantity" name="quantity" value="<?php if (isset($setting['quantity'])){echo $setting['quantity'];}?>">
<button type="button" onclick="saveAjaxSetting()" class="sg-main-btn sg-primary-btn" id="ajaxSubmit">Save</button>
</form>

<form action="store" method="post">
<input type="number" class="form-control" id="max_accessories" name="max_accessories" value="<?php if (isset($setting['max_accessories'])){echo $setting['max_accessories'];}?>">
<input type="text" class="form-control" id="max" name="max" value="<?php if (isset($setting['max'])){echo $setting['max'];}?>">
<button type="button" onclick="saveAjaxSetting()" class="sg-main-btn sg-primary-btn" id="ajaxSubmit">Save</button>
</form>

This is my route:- Route::post('/store','Crud\SettingController@saveSetting');

here is my setting controller:-

public function saveSetting(StoreSetting $request)
{
    try{
        //Log::info($request);
        $setting= request(['is_active','max_accessories','quick_view','accessory_discription','thumbnail','quantity_selector','addons_heading','quantity','variant','price']);

        $data= array_map(array($this,'settingData'), array_keys($setting), array_values($setting));

        $keys=array_keys($setting);
        //Log::info($data);
        if (!empty($data))
        {
            Model::whereIn('entity_name',$keys)->delete();
            $settingData= Model::insert($data);
            return true;
        }
        return false;

    }
    catch (\Exception $e) {
        Log::error($e->getMessage());
        throw new \Exception("Setting not saved in ");
        return false;
    }
}

And my ajax script is:-

function saveAjaxSetting(data) {
console.log(data);
$.ajax({
    type: 'POST',
    url: "/spiceaddons/public/store",
    dataType: 'json',
    data: {
        "method": 'POST',
        "data": data
    },
    error: function (err) {
        console.log(err);
        toastr.error('Error in saved');
    },
    success: function (data) {
        console.log(data);
        toastr.success(' Setting saved');

    },
});

}

This is all of the code is here And Problem:- data not insert in database.


Solution

  • Thank you but I am submitting data without {{ csrf_field() }} because I stopped middleware. and I am using the onclick event on a button so my new ajax code is here and it is work properly:-

    <script>
        function accessorySetting() {
            var data={'max_accessories':$('input[name="max_accessories"]').val(),
                      'quick_view':$('input[name="quick_view"]:checked').val(),
                      'thumbnail':$('option:selected').val(),
                      'accessory_discription':$('input[name="accessory_discription"]:checked').val(),
                      'quantity_selector':$('input[name="quantity_selector"]:checked').val()
                    };
    
            saveAjaxSetting(data);
        }
    
        function languageSetting() {
            var data={'addons_heading':$('input[name="addons_heading"]').val(),
                      'quantity':$('input[name="quantity"]').val(),
                      'variant':$('input[name="variant"]').val(),
                      'price':$('input[name="price"]').val()};
            //alert(JSON.stringify(data));
            saveAjaxSetting(data);
        }
    
        function saveAjaxSetting(data1) {
        //alert(JSON.stringify(data1));
        $.ajax({
        type: 'POST',
        url: "/spiceaddons/public/store",
        dataType: 'json',
        data:data1,
            success: function (data) {
                console.log(data);
                toastr.success("Setting Save Successfully");
            },
            error: function (err) {
                var response = JSON.parse(err.responseText);
                $.each( response.errors, function( key, value) {
                    toastr.error(value);
                });
    
            },
    
        });
        }
    </script>