-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");
 }
asked Apr 28, 2016 at 14:32
4
  • There's a few options - one option is to import jQuery and use the inbuilt $.get](https://api.jquery.com/jquery.get/) and [$.post methods Commented Apr 28, 2016 at 14:39
  • I have tried doing it both ways but a jQuery answer would be nice as it would work with different browsers Commented Apr 28, 2016 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. Commented Apr 28, 2016 at 14:58
  • 1
    Can I also suggest that you may like to look into Laravels Request class documentation and use that instead of $_POST['variableName'] - its safer than using $_POST directly and has some nice features. Commented Apr 28, 2016 at 15:03

2 Answers 2

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.

answered Apr 28, 2016 at 15:29
Sign up to request clarification or add additional context in comments.

6 Comments

no worries my knowledge of both is limited. I have followed your instructions but I am not getting any alerts.
That could be because your controller method is not returning anything. I will update with some more details
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.
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.
I changed it to a value but that isn't working either
|
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
});
answered Apr 28, 2016 at 14:47

2 Comments

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 ? <script> $.get("goal", function(data)) { alert("test"); }); </script>
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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.