简体   繁体   English

如何通过ajax发送错误/成功消息,而无需单击laravel中的表单(如果没有表单)中的提交按钮?

[英]How to send error/success message through ajax without click submit button in form (if there isn't form) laravel?

How to send error/success message through ajax without click submit button in form (if there isn't form)? 如何通过ajax发送错误/成功消息,而无需单击表单中的提交按钮(如果没有表单)?

I'm doing a laravel project in there I've used the method when user submit the form the form goes to controller (through form's action attribute) and inside the controller function it can return view with data and redirect the page so the error/success message will be shown and page will be refreshed. 我在这里做一个laravel项目,当用户将表单提交给控制器时(通过表单的action属性),我使用了该方法,并且在控制器函数内部,它可以返回带有数据的视图并重定向页面,因此错误/将显示成功消息,并刷新页面。

return redirect()->back()->with('success', 'Successfully Added!'); 

But the case is I want to click a button and same thing happen if there are no form. 但是情况是我想单击一个按钮,如果没有表单,也会发生同样的事情。 I added onclick to button and run a js function to call controller via ajax. 我在按钮上添加了onclick并运行js函数以通过ajax调用控制器。 But after call to controller the above code doesn't work like before. 但是在调用控制器之后,上面的代码无法像以前那样工作。 No error either. 也没有错误。

<button type="button"  onclick="submit()" class="btn btn-primary"
>Submit</button> 

<script>
//when click submit button
    function submit(){
        var _token = $('input[name="_token"]').val();
        $.ajax({
            url: "{{ route('RecipeController.submit') }}",
            type: "POST",               
            data: { _token:_token                                     
            }
        })   
    }
</script>

Can anyone give me a solution? 谁能给我解决方案?

Below I added message code if you want that. 如果需要,我在下面添加了消息代码。

@if(count($errors)>0)
@foreach($errors->all() as $error)
    <div class="alert alert-danger">    
        {{$error}}
    </div>    
@endforeach
@endif

@if(session('success'))
<div class="alert alert-success">
    {{session('success')}}        
</div>    
@endif

@if(session('error'))
<div class="alert alert-danger">
    {{session('error')}}        
</div>    
@endif

Ajax normally expects JSON, so a normal redirect or view wont work. Ajax通常期望使用JSON,因此无法正常进行重定向或查看。

I can show you an example: 我可以举一个例子:

    return response()->json(['error' => 'there was an error...'], 200);

The 1st parameter is an array with the data. 第一个参数是包含数据的数组。 The second is the http status. 第二个是http状态。

Hope it helps with your problem. 希望对您的问题有所帮助。 :) :)

Edit: Now that i have your message code. 编辑:现在我有您的消息代码。

You just have to add a div dynamically with js on ajax success. 您只需在ajax成功的情况下使用js动态添加div。

 $(document).ready(function() {
               $(".removeproduct").click(function(){

                   $.ajax({
                       headers: {
                           'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                       },
                       type : 'DELETE',
                       url  : '/user/'+report_id+'/removefromcart',
                       data  : {report_id : report_id},
                       success:function(data)
                       {
                           console.log(data);
                      },
                       error : function(data)
                       {
                           console.log(data);
                       }
                     });


                   });
               }) ;

And route should be defined like 和路线应定义为

Route::get('/user/{id}/removefromcart','YOURCONTROLLERNAME@MethodName');
public function removeFromCart(Request $request, $report_id)
{

    $return = array();


        $check = DB::delete("DELETE FROM carts WHERE user_id='" . Auth::user()->user_id . "' AND report_id='" . $report_id . "'");
        if ($check) 
        {

            $count = Cart::where('user_id', Auth::user()->user_id)->count('id');
            $return = array('success' => true, 'message' => 'Item removed to cart', 'data' => $count);
            return response()->json($return);
        }

    } 


}

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

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