0

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.

4
  • What errors do you see? Does your ajax call complete or is there an error? Commented Aug 14, 2018 at 19:21
  • @niraj not an error in console. but data not insert in database Commented Aug 14, 2018 at 19:43
  • I would have expected at least one error as you're not sending a CSRF token in your Ajax calls, unless you've disable CSRF or have added the route to the exclude list. Are you using $fillable or $guarded in your Model? Commented Aug 14, 2018 at 23:11
  • @niraj yes i used in model $fillable Commented Aug 15, 2018 at 7:26

2 Answers 2

1

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>
Sign up to request clarification or add additional context in comments.

Comments

0

There could be number of reasons why your code isn't working.

1 - CSRF Token

Your API call is using POST. Assuming this route is in the web.php routes file, it means your form needs to include the CSRF token. To do this, add the following line to each of the HTML forms (after the opening form tag):

{{ csrf_field() }}

2 - Fillable Fields

If you are using $fillable in your Model, you need to make sure the array contains all the fields you expect. If any column is missing form the $fillable array, data won't be saved to that column.

protected $fillable = [ 'name', 'value', ... ];

3 - Check the laravel.log file

Check the error log file in storage/logs/larave.log to see if any other errors or exceptions are being thrown by your code. This will give you a stack trace to help you which file and line could be causing the error.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.