ray ray - 7 months ago 116
Javascript Question

Laravel 5.2 adding ajax

I have the following laravel code that uses get and post requests, which works. I am trying to add ajax to this but I am struggling. How would I add ajax to this?

Here is the code in the view.

<form action="goal" method="post">
<input name="usersID" type="form"> usersID </input> <br>
<input name="goalValue" type="form"> goal </input> <br>
<input name="goalpoints" type="form"> goalpoints </input> <br>
<input name="points" type="form"> points </input> <br>
<input name="activitiesID" type="form"> activitiesID </input> <br>
<button type="submit"> Submit </button>
</form>


Here is the code in the route

Route::get("goal", "PagesController@getGoal");
Route:: post("goal",
["as" => "goal",
"uses" => "tableController@getGoal"]);


Here is the code in the controllers

//controller 1

public function getGoal()
{
return view("pages.goal");
}


// controller 2

public function getGoal()
{
$usersID = $_POST["usersID"];
$goal = $_POST["goalValue"];
$goalpoints = $_POST["goalpoints"];
$points = $_POST["points"];
$activitiesID = $_POST["activitiesID"];

DB :: table("goals") -> insert
(
array("usersID" => $usersID, "goal" => $goal, "goalpoints" => $goalpoints, "points" => $points,
"activitiesID" => $activitiesID)
);
return view("pages.goal");
}

Answer

Assuming that your knowledge of JQuery/Javascript is limited (forgive me if not) I will go into a little more detail than the existing answer.

I would start by adding an ID to your form.

<form action="goal" method="post" id="goalForm">

Next I would look into CSRF documentation on Laravel otherwise you may get errors related to "Token mismatch". In short you need to do 1 of two things:

  1. Add <input type="hidden" name="_token" value="<?php echo csrf_token(); ?>"> too all your forms.

  2. Add <meta name="csrf-token" content="<?= csrf_token() ?>"> in your <head> section.

If option 2 you will also need to add this javascript to the bottom of your template:

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

This will add your token to all your AJAX requests.

Next use JQuery to handle the form submission.

$('#goalForm').submit(function(e){

    // I have passed in the event 'e' and preventing default browser functionality. 
    e.preventDefault();

    var formData = $(this).serialize(); //Get the form data and put in a structure i can send

    $.post('goal', formData).done(function(response){
        // after the ajax is done, do something with the response
        alert(response);
    });
});

Your controller method will need to return something (assuming controller 2):

public function getGoal()
{
    $usersID = $_POST["usersID"];
    $goal = $_POST["goalValue"];
    $goalpoints = $_POST["goalpoints"];
    $points = $_POST["points"];
    $activitiesID = $_POST["activitiesID"];

    try{
        DB::table("goals")->insert(
            array("usersID" => $usersID, "goal" => $goal, "goalpoints" => $goalpoints,  "points" => $points, "activitiesID" => $activitiesID)
        );
    } catch (\Exception $e) {
        echo "something went wrong";
    }
    echo "Awesome it worked";
}

I have added a try/catch incase your DB insert fails. Also just echoing for test purposes, you can update this later.

Comments