Adding an item to database in Laravel using AJAX and then displaying the item

After several hours of googling, I cannot find an answer to this seemingly simple problem. I cannot add data to the database and show this data without refreshing the page. My goal is to create an object from the form to upload to the database and then show all items in the database (without refreshing the page). I've tried to get AJAX to work many times, but I can't seem to get it done. The app works by adding stars to the students, so basically I would like to be able to update the student stars without reloading the page. But right now I can't even console.log

submit form data. My controller code looks like this:

    public function addStar(){

    $id = Input::get('id');
    $user_id = Input::get('user_id');

    if(Auth::user()->id == $user_id){

        Student::addStar($id);

    }

    return Redirect::back();

}

      

And my form:

             {{Form::open(array('action'=>'HomeController@addStar','id'=>'addStar','method'=>'post'))}}
        {{ Form::hidden('id', $student->id, array('id'=>'id_value')) }}
        {{ Form::hidden('user_id', $student->user_id, array('id'=>'user_id_value'))}}
        {{ Form::submit('+')}}
        {{ Form::close() }}

      

And my extremely bad AJAX attempts:

$('#addStar').on('submit',function(e) {
    e.preventDefault();
    $.ajax({
        type: 'POST',
        cache: false,
        dataType: 'JSON',
        url: '/addstar',
        data: $('#addStar').serialize(),
        success: function(data) {

            console.log(data);
        },

    });
    return false;
});

      

The code works fine if I agree to allow page reloads, but I don't want to. Basically my question is how to add data to the database and show it without page reloading? Many thanks!

+3


source to share


2 answers


The controller does the redirect after the logic, ajax won't be able to do anything with the response. One of them would be adding a start that returns a new star rating.

public function addStar(){

    $id      = Input::get('id');
    $user_id = Input::get('user_id');

    if(Auth::user()->id == $user_id){

        Student::addStar($id);

    }

    $star_count = //get new star count;

    return Response::json(['star_count' => $star_count]);
}

      



Since the controller is now returning a json response, the callback success

on $ .ajax can grab it and do something (update the star count).

+3


source


@codeforfood,

If you want to receive the response and show it immediately on the page without reloading, you can return with a JSON response and then process that response on the client side. Javascript conditions for success or failure.

You can try something like this if you want: In the controller's addStar () response:

$data = ['star_count' => 'COUNT OF STARS'];
return json_encode($data);   

      



In the view for that particular Star Div:

    <script>
        $('#stardiv).on('submit', function (e) {
            $.ajax({
                type: 'POST',
                url: "{{URL::to('xxxxx')}}",
                data: $(this).serialize(),
                dataType: "JSON",
                success: function (data) {
Handle the success condition here, you can access the response data through data['star_count']
                },
                error: function (data) {
Handle the error condition here, may be show an alert of failure
                }
            });
            return false;
        });
    </script>

      

At the end of the day, this is just one approach, you can try the other one that ever works for you.

Cheerz.

+1


source







All Articles