Flex
105
9
Laravel

Not working Laravel and Ajax data insert in to the database

Posted 6 days ago by Flex

working with Laravel 5.7 and Ajax to insert data and display in the following blade file,

<table border="0">
    <th colspan="6">Members</th>
    <tr>
    <td>Id</td>
    <td>Name</td>
    <td>Email</td>
    <td>Address</td>
    </tr>

    @foreach($member as $value)
    <tr>
    <td>{{$value->id}}</td>
    <td>{{$value->name}}</td>
    <td>{{$value->age}}</td>
    <td>{{$value->email}}</td>
    <td>{{$value->address}}</td>
    </tr>
    @endforeach
    </table>

    <!--insert data-->
    <table border="0">
    <th colspan="2">Insert</th>
    <tr>
    <td>Name:</td>
    <td><input type="text" name="name"></td>
    </tr>

    <tr>
    <td>Age:</td>
    <td><input type="text" name="age"></td>
    </tr>

    <tr>
    <td>Email:</td>
    <td><input type="text" name="email"></td>
    </tr>

    <tr>
    <td>Address:</td>
    <td><input type="text" name="address"></td>
    </tr>

    <tr>
    <td colspan="2"><button type="submit" id="insert">Insert</button></td>
    </tr>
    </table>
    {{ csrf_field() }}

$('#insert').click(function(){
    $.ajax({
        type:'post',
        url:'insertdata',
        data:{
            '_token':$('input[name:_token').val(),
            'name':$('input[name:name').val(),
            'age':$('input[name:age').val(),
            'email':$('input[name:email').val(),
            'address':$('input[name:address').val(),
        },
        success:function(data){
            window.location.reload();
        },
    });
});

My HomeController is like this,

public function index()
    {
        $member = membersmodel::all();
        return view('home.index')->with('member',$member);
    }

    public function insertdata(Request $request)
    {
        $member = New membersmodel();
        $member->name = $request->name;
        $member->age = $request->age;
        $member->email = $request->email;
        $member->address = $request->address;
        $member->save();
        return response()->json($member);
    }

and route is,

Route::get('/','[email protected]');

Route::post('insertdata','[email protected]');

but when I insert data in the insert table and click insert button, anything not happens. not saving data or displaying. No, any error occurred.how can fix this problem?

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.