0

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!!!

8
  • 1
    Why not just calling window.location.reload() in JavaScript? Otherwise you need to refresh the HTML content in the browser. Ajax is capable of delivering that content as well. Commented Jun 15, 2017 at 9:59
  • @btl window.location.reload() reloads the page but doesn't work will closing my dialog and displaying my flash message. How do I refresh the html content? Commented Jun 15, 2017 at 10:28
  • Make an AJAX request and return the new data with return response()->json($reponse);. Then in the success callback append the data to your HTML document. Commented Jun 15, 2017 at 10:30
  • @btl in my controller store method, I'm sure that's where it should be done, but now base on what I have I can I return both the response and the flash message? Commented Jun 15, 2017 at 10:32
  • @btl I'm currently returning only the flash mess with a field from the response. Commented Jun 15, 2017 at 10:33

3 Answers 3

2

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

Comments

0

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..

5 Comments

How do I do option 2?
@NathanSiafa, check If the edit is enough for you to understand the idea.
I did this $('#subjects').append('<td>'+response.subject+'</td>') and I got [object Object]
for me to archieve that I had to the id to the tbody tag.
@Nathan Siafa Glad you finished the job :)
0

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>*');

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.