简体   繁体   English

Laravel 5.2添加Ajax

[英]Laravel 5.2 adding ajax

I have the following laravel code that uses get and post requests, which works. 我有以下使用get和post请求的laravel代码,可以正常工作。 I am trying to add ajax to this but I am struggling. 我试图为此添加ajax,但我正在努力。 How would I add ajax to this? 我该如何添加ajax?

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 //控制器1

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

// controller 2 //控制器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");
 }

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. 假设您对JQuery / Javascript的知识是有限的(如果没有,请原谅我),我将比现有答案更详细一些。

I would start by adding an ID to your form. 我将从在您的表单中添加一个ID开始。

<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". 接下来,我将研究Laravel上的CSRF文档,否则您可能会遇到与“令牌不匹配”相关的错误。 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. 添加<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">太多您的表格。

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

If option 2 you will also need to add this javascript to the bottom of your template: 如果选择2,则还需要将此JavaScript添加到模板的底部:

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

This will add your token to all your AJAX requests. 这会将您的令牌添加到所有AJAX请求中。

Next use JQuery to handle the form submission. 接下来,使用JQuery处理表单提交。

$('#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): 您的控制器方法将需要返回一些值(假设控制器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. 我添加了一个try / catch,以防您的数据库插入失败。 Also just echoing for test purposes, you can update this later. 同样,仅出于测试目的,您可以稍后进行更新。

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. 根据我的评论,您可以使用jQuery通过jQuery的$ .get$ .post方法执行此操作(还有其他一些选项不需要您下载jQuery)。

Here's an example of how you would do a get using jQuery: 这是一个如何使用jQuery进行获取的示例:

$.get( "goal", function( data ) {
  //this is called when a successful get request is made. The server response is in the data object
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM