-1

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");
 }
ray
  • 903
  • 1
  • 13
  • 31
  • There's a few options - one option is to import jQuery and use the inbuilt [$.get](https://api.jquery.com/jquery.get/) and [$.post](https://api.jquery.com/jquery.post/) methods – Crwydryn Apr 28 '16 at 14:39
  • I have tried doing it both ways but a jQuery answer would be nice as it would work with different browsers – ray Apr 28 '16 at 14:41
  • 1
    The provided answer by @Crwydryn is good. Just as a side note, I'd try naming the methods in your controller a little differently. For instance, `getGoal` in controller 2 (which I assume is the `tableController`) should probably be renamed since it _`sets`_ the goal (perhaps something like `setGoal()`). This might help cut down on confusion when controllers start to get more complex. Just a thought. – camelCase Apr 28 '16 at 14:58
  • 1
    Can I also suggest that you may like to look into [Laravels Request](https://laravel.com/docs/5.2/requests#retrieving-input) class documentation and use that instead of `$_POST['variableName']` - its safer than using `$_POST` directly and has some nice features. – DavidT Apr 28 '16 at 15:03

2 Answers2

2

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.

DavidT
  • 2,341
  • 22
  • 30
  • no worries my knowledge of both is limited. I have followed your instructions but I am not getting any alerts. – ray Apr 28 '16 at 15:56
  • That could be because your controller method is not returning anything. I will update with some more details – DavidT Apr 28 '16 at 16:01
  • Thanks. When I submit the form the controller that handles post requests is supposed to return the view "pages.goal". I am pretty sure this part is working. – ray Apr 28 '16 at 16:06
  • Well, with AJAX the page won't reload. Therefore sending back a view that would be the same as the view currently loaded would be pointless. – DavidT Apr 28 '16 at 16:10
  • I changed it to a value but that isn't working either – ray Apr 28 '16 at 16:13
  • No problem. Glad it worked. When I first started coding I [struggled with Ajax too](http://stackoverflow.com/questions/12097290/calling-a-php-function-using-ajax-javascript). Nice to give back what I have learnt. – DavidT Apr 28 '16 at 16:18
1

Following on from my comment, you can use jQuery to do this (there are other options that don't require you to download jQuery) via jQuery's $.get and $.post methods.

Here's an example of how you would do a get using jQuery:

$.get( "goal", function( data ) {
  //this is called when a successful get request is made. The server response is in the data object
});
Crwydryn
  • 840
  • 6
  • 13
  • So I am trying to do this in the view file and I don't need anything in the routes, and the alert should fire on a get request ? – ray Apr 28 '16 at 14:56
  • Well personally I'd put the script in its own file - separation of concerns and all that - you will need to reference the jQuery framework in your view (and the script file if you decide to separate it out) - use Google CDN or similar for jQuery, or pull the file into your project and reference it locally – Crwydryn Apr 28 '16 at 15:27