0

I am using code.jquery.com/jquery-3.5.0.js in my application, and trying to post data without reload. It posts fine without ajax, but not with ajax script.

Controllers:

public function index()
{
    $tasks = Task::orderBy('id', 'desc')->paginate(9);
    return view('empmodel', compact('tasks'));
}

public function store(Request $request)
{
    $tasks = new Task;
    $tasks->t_title = $request->input('t_title');
    $tasks->project_id = $request->input('project_id');
    $tasks->save();
}

Ajax:

<script type="text/javascript">
$(document).ready(function () {
    $('#addform').on('submit', function(e) {
        e.preventDefault();

        $.ajax({
            type: "POST",
            url: "/addstudent",
            data: $('#addform').serialize(),
            success: function (response) {
                console.log(response)
                $('#studentaddmodal').modal('hide')
                alert("data saved");
            },
            error: function(error) {
                console.log(error)
                alert("Data not saved");
            }
        });
    });
});
</script>
</body>

Routes:

Route::get('/tasks', 'projects\ProjectpController@index');
Route::post('/addstudent', 'projects\ProjectpController@store');

When I fill integer in the field with project_id, alert says "data saved", but it does not appear in the database. If I put text in project_id field, then the alert is as supposed to be "data not saved". CSRF token is not missing. I am using regular bootstrap Modal.

linktoahref
  • 7,812
  • 3
  • 29
  • 51
Tomas Am
  • 433
  • 4
  • 13

1 Answers1

0

Parse the string that you send from the AJAX in the Controlller using parse_str

Change the data definition of your ajax to

data: {
    formData: $('#addform').serialize()
}

and in your Controller method

public function store(Request $request)
{
    parse_str($request->formData, $output);
    $tasks = new Task;
    $tasks->t_title = $output['t_title'];
    $tasks->project_id = $output['project_id'];
    $tasks->save();
}

Similar Question: How do I PHP-unserialize a jQuery-serialized form?

Read: https://stackoverflow.com/a/3817220/5808894

linktoahref
  • 7,812
  • 3
  • 29
  • 51