Jc John
Jc John

Reputation: 1859

page refreshes and data won't add when inserting data using ajax in laravel 5

I've a piece of code where I wanna add/insert data from database using ajax in laravel 5. I am a beginner in ajax and laravel and I'm not sure why it's refreshing my page.

Here is what I did so far: In my view I have a modal like this:

<div class="modal fade" id="addcategory" tabindex="-1" role="dialog" aria-labelledby="contactLabel" aria-hidden="true">
    <div class="modal-dialog">
    <div class="panel panel-primary">
        <div class="panel-heading">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
            <h4 class="panel-title" id="contactLabel"><span class="glyphicon glyphicon-info-sign"></span> Add Category</h4>
        </div>
        <form id="frmAddcategory">
        <div class="modal-body" style="padding: 5px;">
                <div class="row">
                   <div class="col-lg-12 col-md-12 col-sm-12 {{ $errors->has('email') ? ' has-error' : '' }}" style="padding-bottom: 10px;">
                        <input class="form-control" name="catname" placeholder="Category name" type="text" required />
                    </div>
                </div>
                <div class="row">
                    <div class="col-lg-12 col-md-12 col-sm-12 {{ $errors->has('email') ? ' has-error' : '' }}">
                        <textarea style="resize:vertical;" class="form-control" placeholder="Description" rows="4" name="catdesc" required></textarea>
                    </div>
                </div>                
            </div>  
            <div class="panel-footer" style="margin-bottom:-14px;">                
                <button class="btn btn-success btn-sm" onclick="addCategoryAjax()">Submit</button>
                    <!--<span class="glyphicon glyphicon-ok"></span>-->
                <input type="reset" class="btn btn-danger btn-sm" value="Clear" />
                    <!--<span class="glyphicon glyphicon-remove"></span>-->
                <button style="float: right;" type="button" class="btn btn-default btn-close btn-sm" data-dismiss="modal">Close</button>
            </div>
            {{ csrf_field() }}
        </form>
        </div>
    </div>
</div>

to submit the button in my ajax, as u can see i used <button class="btn btn-success btn-sm" onclick="addCategoryAjax()">Submit</button> on my form. i added the function on click.

Here is my ajax function :

function addCategoryAjax() {
    $.ajax({         
        url: "{{ route('admin.addcat') }}",        
        type: "POST",
        data: $("#frmAddcategory").serialize(),
        dataType: "JSON",
        success: function(data) {

        }
    }); 
}

here is my controller:

 public function addCategory(Request $request) 
    {
        $stat = "published";

        DB::table('categories')->insert([
        'name'=>$request->catname, 
        'description'=>$request->catdesc, 
        'status'=>$stat,
        'created_at' =>  \Carbon\Carbon::now(), # \Datetime()
        'updated_at' => \Carbon\Carbon::now()  # \Datetime()
        ]);

    }

Upvotes: 0

Views: 61

Answers (2)

RamAnji
RamAnji

Reputation: 470

         <form  name="itemGroupForm" id="itemGroup" data-parsley-validate="" method="post"  onsubmit="return submitFormItemGroup();">
 function submitFormItemGroup() {

  var form_data = new FormData(document.getElementById("itemGroup"));
  form_data.append("label", "WEBUPLOAD");
  $.ajax({
      url: "{{URL::to('addItemGroupAjax')}}",
      type: "POST",
      data: form_data,
      processData: false,  // tell jQuery not to process the data
      contentType: false   // tell jQuery not to set contentType
  }).done(function( data ) {
    console.log(data);
})
Route::post('/addItemGroupAjax','ItemGroupsController@storeAjax');

Upvotes: 1

Duc Filan
Duc Filan

Reputation: 7157

You should prevent the default actions of the button, like:

e.preventDefault();

You can pass in event into the function inline which will be the event object for the raised event in W3C compliant browsers.

So your code should be:

HTML:

<button class="btn btn-success btn-sm" onclick="addCategoryAjax(event)">Submit</button>

Js:

function addCategoryAjax(e) {
    e.preventDefault();

    $.ajax({         
        url: "{{ route('admin.addcat') }}",        
        type: "POST",
        data: $("#frmAddcategory").serialize(),
        dataType: "JSON",
        success: function(data) {

        }
    }); 
}

Upvotes: 1

Related Questions