简体   繁体   English

在Laravel 5中使用AJAX提交表单

[英]Submitting Form in AJAX in Laravel 5

 <p style="padding:10px">Add your Facebook Account</p>

    {!! Form::open(['route'=>array('agencyNewPlatform',$influencer->getUser()->user_type_id, '1')]) !!}                        
      <input type="text" name="handle" placeholder="Profile Name" />
      <p style="padding-top:25px;padding-bottom:5px">
        <button type="submit" class="btn btn-success plat_add">Save</button>
      </p>
    {!! Form::close() !!}

I am trying to submit this form through AJAX, but I don't know how to define myurl . 我试图通过AJAX提交此表单,但我不知道如何定义myurl The following source code may contain other errors, too. 以下源代码也可能包含其他错误。 Please help me. 请帮我。

$('.plat_add').click(function(event) {
   event.preventDefault();

   var myurl = ?????????????;

   var date = new Date();
   myurl = myurl+"?noche="+date.getTime();
   mydata = $(this).closest('form').serialize();
   var jqxhr = $.ajax({
     url: myurl,
     type:'GET',
     dataType:'json',
     data: mydata,
   }).done(function() {
     var response = JSON.parse(jqxhr.responseText);
     $("#table3").append("<tr id=" + response.platform_id + "plat><td>" + response.plat_name + "</td><td>" + response.handle + "</td><td><a class='plat_remove' href=" + response.link + ">Remove</a></td></tr>");
   }).fail(function() {
     alert("Add platform fail!" + jqxhr.responseText);
   });

});

This are my route and controller functions: 这是我的routecontroller功能:

Route: 路线:

Route::get('influencer/update/{user_type_id}/add_plat/{platform_id}', ['as'=>'agencyNewPlatform','uses'=>'AgentController@postPlatform']);

and Controller: 和控制器:

  public function postPlatform(InfluencerAddPlatformRequest $request, $user_type_id, $platform_id)
  {
      $user = Auth::user();
      $agent = $user->getTypeModel();
      $influencer = $this->influencer->findById($user_type_id);
      $handle = $request->input('handle');
      $result = DB::table('influencers_platforms')->insert(['influencer_id'=>$user_type_id, 'platform_id'=>$platform_id, 'platform_handle'=>$handle]);

      $plat_name = DB::table('platforms')->where('id', $platform_id)->first()->name;



     if($request->ajax()) 
     {   
        return response()->json(array('responsecode'=>'1','action'=>'add', 'plat_name'=>$plat_name, 'handle'=>$handle, 'link'=>route('agencyDeletePlatform',[$influencer->getUser()->user_type_id, $platform->id]), 'result'=>$result,'platform_id'=>$platform_id));
     }

 }

I am really stuck at here; 我真的被困在这里; thank you all in advance! 谢谢大家!

First put an id to your form , thas better than try to catch the event from the submit button, remember, press enter on any field will gonna submit your form without press the submit button. 首先为你的form一个id ,比尝试从提交按钮中捕获事件更好,记住,按任何字段上的enter将提交你的表单而不按提交按钮。

view 视图

 {!! Form::open(['route'=>array('agencyNewPlatform',$influencer->getUser()->user_type_id, '1'), 'method' => 'get' 'id' => 'form']) !!}

       <input type="text" name="handle" placeholder="Profile Name" />

        <p style="padding-top:25px;padding-bottom:5px">
            <button type="submit" class="btn btn-success plat_add">Save</button>
        </p>
{!! Form::close() !!}

After here the script i often use to send an ajax request: 在这之后,我经常使用脚本发送ajax请求:

javascript JavaScript的

$("#form").submit( function (event) {
    event.preventdefault();

    var url = $(this).attr('action'); //here you have to options
    //get the url from the action on the form
    //or declare an <a href="{{route(your.route)}}"> and get it from the href
    var data = $(this).serialize();

    $.get(url, data, function(result) {
         //do if result is ok
    }).fail(function (){
         //do if fails
    });;
});

Edit: 编辑:

i se you have a var date = new Date(); 我有一个var date = new Date(); and you want to put it on your vars, first, the url even if is a get request dont contain your data info. 并且你想把它放在你的vars上,首先,url即使是get请求也不包含你的数据信息。 You need to pass it into your data var. 您需要将其传递给数据var。

lets learn a default get url: 让我们学习默认的获取网址:

myurl.com?var=value&var2=value2

When you do an ajax request this url is divided in two pieces the url and the data 当你执行ajax请求时,这个url分为两部分urldata

var url = "myurl.com";
var data = "var=value&var2=value2";

the jquery will gonna merge that two variables after. jquery会在之后合并这两个变量。

So, lets learn how .serialize() works, when you call this method, the result will be in the data format. 因此,让我们了解.serialize()工作原理,当您调用此方法时,结果将采用数据格式。

so if you want to add another variable its simple: 所以如果你想添加另一个变量,那就简单了:

data+="&newvar="+var;

now data contain: 现在数据包含:

data = "var=value&var2=value2&newvar=valuefromvar"

so your code will be like: 所以你的代码就像:

$("#form").submit( function (event) {
    event.preventdefault();
    var date = new Date();

    var url = $(this).attr('action'); //here you have to options
    //get the url from the action on the form
    //or declare an <a href="{{route(your.route)}}"> and get it from the href
    var data = $(this).serialize();
    data+="&noche="+date.getTime(); //here the change

    $.get(url, data, function(result) {
         //do if result is ok
    }).fail(function (){
         //do if fails
    });;
});

Another recomendation if you work with route names , the correct form to put it is separating words with . 如果你使用路由名称 ,另一个推荐,正确的形式是用它来分隔单词. not in camelcase format, and build with a subject after and action (if its necesary) like: 不是在camelcase格式中,并且使用主题和动作(如果必要的话)构建如下:

user.show
user.update
agency.create.platform

In the controller , I know maybe its too late to make big changes on your application, but in another projects why you dont try to use eloquent and orm relationships instead of fluent DB , this will gonna make your code more flexible, and your controller logic maybe will not take more than 10 lines. 控制器中 ,我知道对你的应用程序进行大的改动可能为时已晚,但在另一个项目中你为什么不尝试使用雄辩和orm关系而不是流畅的DB ,这将使你的代码更加灵活,并且你的控制器逻辑也许不会超过10行。

I may have not fully understood your question so please make a comment if I didn't address something properly. 我可能还没有完全理解你的问题,所以如果我没有正确解决问题,请发表评论。

As a side note, formatting your code (indentation) and using consistency throughout your code (such as declaring an array, ie use array() or [] not both) will go a long way in making your code readable when you or someone else returns to it, see the changes I made in terms of formatting. 作为旁注,格式化代码(缩进)并在整个代码中使用一致性(例如声明一个数组,即使用array()[]不是两者)将在您或其他人的代码中使代码可读返回它,看到我在格式化方面所做的更改。

view 视图

I have added an id myForm to the form here, see second argument of form open() function. 我在这里向表单添加了一个id myForm ,请参见表单open()函数的第二个参数。 Your route is get so I changed the form method to get also. 你的路线是这样的,所以我改变了形式方法也得到了。 Default for forms is post you can of course change that depending on your needs. 表单的默认值是帖子,您当然可以根据您的需要更改它。

<p style="padding:10px">Add your Facebook Account</p>

{!! Form::open(['route' => ['agencyNewPlatform', $influencer->getUser()->user_type_id, '1'], 'method' => 'get',  'id' => 'myForm']) !!}

    <input type="text" name="handle" placeholder="Profile Name" />

    <!-- this looks much easier to read on three lines -->
    <p style="padding-top:25px;padding-bottom:5px">
        <button type="submit" class="btn btn-success plat_add">Save</button>
    </p>

{!! Form::close() !!}

javascript JavaScript的

This listens for the form submit event and then you can get the url from the form action attribute 这会侦听表单提交事件,然后您可以从表单操作属性中获取URL

$('#myForm').submit(function(event) {
  event.preventDefault();

  var $myForm = $(this);

  $.get($myForm.attr('action'),
    $myForm.serialize,
    function(data) {
      // your success code
    }
  ).fail(function(data) {
    var errors = data.responseJSON;
    // show the errors to user
  });

});

routes.php routes.php文件

This looks much easier to read on four lines, with indentation. 通过缩进,这看起来更容易阅读四行。 See controller function is getPlatform I changed that because route type is get - it doesn't HAVE to be but you should make them the same so your code is easy to understand. 看到控制器函数是getPlatform我改变了,因为路由类型是get - 它不是必须但你应该使它们相同,所以你的代码很容易理解。

Route::get('influencer/update/{user_type_id}/add_plat/{platform_id}', [
    'as'   =>'agencyNewPlatform',
    'uses' =>'AgentController@getPlatform'
]);

controller 调节器

public function getPlatform(InfluencerAddPlatformRequest $request, $user_type_id, $platform_id) 
{
    $user       = Auth::user();
    $agent      = $user->getTypeModel();
    $influencer = $this->influencer->findById($user_type_id);
    $handle     = $request->input('handle');

    $result = DB::table('influencers_platforms')
        ->insert([
            'influencer_id'=>$user_type_id, 
            'platform_id'=>$platform_id, 
            'platform_handle'=>$handle
        ]);

    $plat_name = DB::table('platforms')
        ->where('id', $platform_id)
        ->first()
        ->name;

   if($request->ajax()) {
    return response()
        ->json([
            'responsecode' => '1',
            'action'       => 'add',
            'plat_name'    => $plat_name,
            'handle'       => $handle,
            'link'         => route('agencyDeletePlatform', [$influencer->getUser()->user_type_id, $platform->id]),
            'result'       => $result,
            'platform_id'  => $platform_id
        ]);
    }

}

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

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