Nathan Siafa
Nathan Siafa

Reputation: 741

How to reload a view in laravel after insert with JQuery Ajax

I'm inserting records into a table using jQuery ajax. It works fine and returns a flash message that notifies that the record was inserted successfully. Now my problem is after the record have been inserted I don't know how to reload my table so that changes can be reflected.

Note I'm inserting via a bootstrap modal on the same page the table lies.

This is the controller that returns my records:

public function index()
{
    //
    $subjects = Subject::all();


    return view('subjects.show', compact('subjects'));
}

After records are return this is how I'm displaying it:

<table class="table table-responsive table-hover table-condensed table-bordered">
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>Level</th>
                            <th colspan="2">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach($subjects as $subject)
                            <tr>
                                <td>{{$subject->name}}</td>
                                <td>{{$subject->level}}</td>
                                <td>
                                    <a data-toggle="tooltip" title="Edit" href="#" role="button"><i class="glyphicon glyphicon-edit text-info"></i></a>
                                </td>
                                <td>
                                    <a data-toggle="tooltip" title="Edit" href="#" role="button"><i class="glyphicon glyphicon-trash text-danger"></i></a>
                                </td>

                            </tr>
                        @endforeach
                    </tbody>
                </table>

This is my script to insert record:

$(document).on('submit', '#subject-form', function(event) {
            event.preventDefault();
            /* Act on the event */

            var name = $('#name').val();
            var level = $('#level').val();

            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });

            $.ajax({
                type: "POST",
                url: $("#subject-form").attr('action'),
                data: {name: name, level: level},
                success: function(response) {
                    console.log(response);

                    if (response.success) {
                        $.notify({
                            icon: 'glyphicon glyphicon-check',
                            message: response.success
                          },{
                              type: 'info',
                              timer: 4000,
                              offset: 20,
                              spacing: 10,
                              z_index: 1031,
                              delay: 5000,
                              placement: {
                                from: "bottom",
                                align: "right"
                              },

                              animate: {
                                enter: 'animated fadeInDown',
                                exit: 'animated fadeOutUp'
                              },
                        });
                    } else {
                        // display error
                    }

                    $('#subject-modal').modal('toggle');
                }
            });

This is the controller method that inserts the record and generate a flash response:

public function store(Request $request)
{
    //

   //return json_encode(request('name'));
    $response = array();

   if (Subject::create(request(['name', 'level']))) {

       $response['success'] = '<b>'.request('name').'</b>'.' created successfully';
   } else {
       $response['fail'] ='Error creating subject: <b>'.request('name').'</b>'.'. Try again, if problem persist contact administrator';
   }

    return \Response::json($response);


}

Are there ways I can make this work? Appreciate feed backs and suggestions. Thanks!!!

Upvotes: 0

Views: 6961

Answers (3)

Pankaj Makwana
Pankaj Makwana

Reputation: 3050

Get response from controller and append new row into the table.

        $.ajax({
            type: "POST",
            url: $("#subject-form").attr('action'),
            data: {name: name, level: level},
            success: function (response) {
                console.log(response);

                if (response.success) {
                    var html = '<tr>';
                    html = '        <td>' + response.subject.name + '</td>';
                    html = '<td>' + response.subject.level + '</td>';
                    html = '<td>';
                    html = '<a data-toggle="tooltip" title="Edit" href="#" role="button"><i class="glyphicon glyphicon-edit text-info"></i></a>';
                    html = '</td>';
                    html = '<td>';
                    html = '<a data-toggle="tooltip" title="Edit" href="#" role="button"><i class="glyphicon glyphicon-trash text-danger"></i></a>';
                    html = '</td>';
                    html = '</tr>';
                    $("table.table-responsive").append(html);
                    });
                } else {
                    // display error
                }

                $('#subject-modal').modal('toggle');
            }
        });

Controller Code

public function store(Request $request) {
    $response = array();
    $data["name"] = request('name');
    $data["level"] = request('level');
    $subject = Subject::create($data);
    if ($subject) {
        $response['success'] = '<b>' . request('name') . '</b>' . ' created successfully';
        $response['subject'] = $subject;
    } else {
        $response['fail'] = 'Error creating subject: <b>' . request('name') . '</b>' . '. Try again, if problem persist contact administrator';
    }

    return \Response::json($response);
}

Upvotes: 2

whatTheCase
whatTheCase

Reputation: 152

You can use load function. Give your table an id and use this whenever you want:

var url = '/page_adress';
$('#table_id').load(url + '#table_id>*');

Upvotes: 0

Nauman Zafar
Nauman Zafar

Reputation: 1103

Two possible solutions for this.

  1. window.location.reload() to reload the page.
  2. Send the newly added record as a response and in success call back append this to your current table showing all records. (no reload will be required)

EDIT

Your controller method might look like this

public function store(Request $request)
{
    //

   //return json_encode(request('name'));
    $response = array();

   if ($subject = Subject::create(request(['name', 'level']))) {

       $response['success'] = '<b>'.request('name').'</b>'.' created successfully';
       $response['subject'] = $subject;
   } else {
       $response['fail'] ='Error creating subject: <b>'.request('name').'</b>'.'. Try again, if problem persist contact administrator';
   }

    return \Response::json($response);


}

Now your response array has an object (newly created subject record) and you can access it via subject key within your success callback.

Give your table an id and access it using jquery to append a <tr> </tr> element containing your subject record..

Upvotes: 0

Related Questions