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");
}
2 Answers 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:
Add
<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">too all your forms.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.
6 Comments
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
});
getGoalin controller 2 (which I assume is thetableController) should probably be renamed since itsetsthe goal (perhaps something likesetGoal()). This might help cut down on confusion when controllers start to get more complex. Just a thought.$_POST['variableName']- its safer than using$_POSTdirectly and has some nice features.