【问题标题】:Laravel Submit Form Without Page Refresh Using AjaxLaravel 使用 Ajax 提交表单而不刷新页面
【发布时间】:2020-10-13 09:37:31
【问题描述】:

我想在我的模态弹出表单中发布电话号码。但不想在提交表单后点击“继续”按钮消失弹出窗口。这是我的 Blade.php 代码。

            <div id="modal-wrapper" class="modal">
  
              <form class="modal-content animate" id="addform">
               
                               
                    <input type="text" class="form-control" name="phone_number" placeholder="01**********">
                  </div> 
                  </div>
                  
                <div style="text-align: center; margin-top: 10px;padding-left:18px;">
                  <button type="submit"  style="background-color: #a5abb0;" class="mobile-login__button">CONTINUE
                </button>
              </div>

这是我的 ajax 部分代码的脚本部分。

 <script>
                
                  $("#addform").on('submit',function(e){
                    e.preventDefault();
              
                    $.ajax({
                      type:"post"
                      url: "/client-mobile-login"
                      data: $("addform").serialize(),
                      success:function(response){
                        
                      },
                      error:function(error){
                        console.log(error)
                        alert("not send");
                      }
              
                      )};
                    });
                  
                });
              
                </script>

这是我的控制器功能

     public function client_mobile_login(Request $request)
      {
       $client_phone1='88'.$request->input('phone_number');
    
    $result=DB::table('client')
            ->where('client_phone1',$client_phone1)
            ->first();
           {{ here is my otp sending code.... }}

            if($result)
            {       
                   $request->session()->put('client_title', $result->client_title);
                   

               // print_r($client_phone1);
               } 

【问题讨论】:

  • &lt;script&gt; 部分是否在 &lt;form&gt; 部分之后?

标签: javascript jquery ajax laravel laravel-blade


【解决方案1】:

使用 type=button

<button type="button" id="submitForm" ...>CONTINUE</button>

并在点击事件上触发您的 ajax

$("#submitForm").on('click',function(e){ ... }

【讨论】:

  • 它阻止了页面的重新加载。但是控制器内部的查询在这里不起作用,怎么办?
  • 你得到什么错误?另外,请确保在您的 post call 中使用 _token。
  • 我使用了 csrf 令牌。当我点击“继续”按钮时,什么也没有发生。页面保持原样。没有变化。
  • 检查您的网络控制台。您是否看到正在提出请求?如果是,那么在 ajax 成功或错误时......做一些事情
猜你喜欢
  • 1970-01-01
  • 2017-03-17
  • 1970-01-01
  • 2017-04-09
  • 1970-01-01
  • 2013-07-10
  • 2014-03-03
  • 1970-01-01
  • 2021-09-26
相关资源
最近更新 更多