简体   繁体   中英

Laravel 5.4 Ajax save

Hi I am trying to make an save / create an item using ajax.

I am not that familiar with ajax and wanted to ask which steps I have to do next to make the save / create function make work.

How do I get the data and save it in my database.

So far my ajax code looks like this:

$(document).ready(function() {
    $("#save-item").click(function(e) {
        e.preventDefault();
        var id = $('#item-id').data('item-id');
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
            }
        });

        $.ajax({
            url: 'joke/create',
            type: 'post',
            data: {
                id: id, 
                content: $('#item').val()
            },
            success: function(data) {
                console.log("Success with data " + data);
            },
            error: function(data) {
                console.log("Error with data " + data);
            }
        });
    });
});

And my Controller looks like this:

public function create(Request $request)
{
    $item = new Item;

    if($data->save())
    {
        return response()->json(["response" => 200, "joke" => $item]);
    }
    else
    {
        return response()->json(["response" => 400, "joke" => $item]);
    }
}

try this inside your controller:

$item = new Item;
$data = $request->all();
$item->create($data);

$item = new Item;
$data = $request->all();

if($item->create($data))
{
    return response()->json(["response" => 200, "joke" => $item]);
}
else
{
    return response()->json(["response" => 400, "joke" => $item]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM