AJAX错误消息未显示(成功消息起作用)

时间:2019-02-16 02:11:34

标签: jquery ajax laravel-5.7

更新:我在下面的答案中发布了有效的代码。

我正在使用Laravel 5.7。
我正在使用JQUERY / AJAX设置添加/删除动态输入字段。

我是编码的初学者,这是我第一次使用JQUERY / AJAX。 除提交时未在输入字段中输入任何内容而不会显示的AJAX错误消息外,其他所有内容均正常。 (控制台中没有错误)

我已经看到很多类似的问题,并相应地检查/更改我的代码,但这无济于事:
-附加html
-成功讯息首先
-JSON标头存在
-已设置Type ='json'...

我在做什么错了?

视图create.blade.php:

<!DOCTYPE html>
<html>
<head>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
    <meta name="csrf-token" content="{{ csrf_token() }}">

</head>
<body>

    <div class="container">

        <div class="form-group">
            <form name="add_name" id="add_name">  


                <div class="alert alert-danger print-error-msg" style="display:none">
                    <ul></ul>
                </div>


                <div class="alert alert-success print-success-msg" style="display:none">
                    <ul></ul>
                </div>


                <div class="table-responsive">  
                    <table class="table table-bordered" id="dynamic_field">  
                        <tr>  
                            <td><input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list" /></td>  
                            <td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>  
                        </tr>  
                    </table>  
                    <input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" />  
                </div>


            </form>  
        </div> 
    </div>


    <script type="text/javascript">
        $(document).ready(function(){      
            var postURL = '/store';
            var i=1;  

            $('#add').click(function(){  
                i++;  
                $('#dynamic_field').append('<tr id="row'+i+'" class="dynamic-added"><td><input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list" /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');  
            });  


            $(document).on('click', '.btn_remove', function(){  
                var button_id = $(this).attr("id");   
                $('#row'+button_id+'').remove();  
            });  


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


            $('#submit').click(function(){            
                $.ajax({  
                    url:postURL,  
                    method:"POST",  
                    data:$('#add_name').serialize(),
                    type:'json',
                    success:function(data)  
                    {
                        if(data.error){
                            printErrorMsg(data.error);
                        }else{
                            i=1;
                            $('.dynamic-added').remove();
                            $('#add_name')[0].reset();
                            $(".print-success-msg").find("ul").html('');
                            $(".print-success-msg").css('display','block');
                            $(".print-error-msg").css('display','none');
                            $(".print-success-msg").find("ul").append('<li>Record Inserted Successfully.</li>');
                        }
                    }  
                });  
            });  


            function printErrorMsg (msg) {
                $(".print-error-msg").find("ul").html('');
                $(".print-error-msg").css('display','block');
                $(".print-success-msg").css('display','none');
                $.each( msg, function( key, value ) {
                $(".print-error-msg").find("ul").append('<li>'+value+'</li>');
                });
            }
        });  
    </script>
</body>
</html>

路线:

Route::get('/create','HomeController@create')->name('create');
Route::get('/index','HomeController@index')->name('index');
Route::post('/store','HomeController@store')->name('store');

控制器:

public function store(Request $request)
    {

        foreach($request->input('name') as $key => $value) {
            TagList::create(['name'=>$value]);
        }
        //return redirect ('index');
        //Javascript code (JQUERY-AJAX) is returning the create view with ajax messages
    }

感谢您的帮助

3 个答案:

答案 0 :(得分:1)

您缺少错误处理程序。

            $.ajax({  
                    url:postURL,  
                    method:"POST",  
                    data:$('#add_name').serialize(),
                    type:'json',
                    success:function(data) {
                      // your code here
                    },
                    error: function(err) {
                    });

或者更好的语法是使用done(),fail(),always()

$.ajax( "example.php" )
  .done(function() {
    alert( "success" );
  })
  .fail(function() {
    alert( "error" );
  })
  .always(function() {
    alert( "complete" );
  });

答案 1 :(得分:0)

您尝试过这样的事情吗?

$('#submit').click(function () {
    $.ajax({
        url: postURL,
        method: "POST",
        data: $('#add_name').serialize(),
        type: 'json',
        success: function (data) {
            $('.dynamic-added').remove();
            $('#add_name')[0].reset();
            $(".print-success-msg").find("ul").html('');
            $(".print-success-msg").css('display', 'block');
            $(".print-error-msg").css('display', 'none');
            $(".print-success-msg").find("ul").append('<li>Record Inserted Successfully.</li>');
        },
        error: function (request, status, error) {
            printErrorMsg(request.responseText);
        }
    });
});  

答案 2 :(得分:0)

基于此tuto,以下是更新的代码,该代码有效:

路线:

Route::get('/create','HomeController@create')->name('create');
Route::get('/index','HomeController@index')->name('index');
Route::post('/store','HomeController@store')->name('store');

家庭控制器(请注意验证器的使用:

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\TagList;
use Validator; //using the validator
class HomeController extends Controller
{
    public function create()
    {
        return view('create');
    }

    public function index()
    {
        $tags = TagList::all();
        return view ('index')->with('tags', $tags);
    }
    public function store(Request $request)
    {
        $rules = [];
        foreach($request->input('name') as $key => $value) {
            $rules["name.{$key}"] = 'required';
        }

        $validator = Validator::make($request->all(), $rules);
        if ($validator->passes()) {
            foreach($request->input('name') as $key => $value) {
                TagList::create(['name'=>$value]);
            }
            return response()->json(['success'=>'done']);
        }
        return response()->json(['error'=>$validator->errors()->all()]);
    }
}

创建视图:

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
    <meta name="csrf-token" content="{{ csrf_token() }}">
</head>
<body>
    <div class="container">  
        <div class="form-group">
             <form name="add_name" id="add_name">  
                <div class="alert alert-danger print-error-msg" style="display:none">
                <ul></ul>
                </div>

                <div class="alert alert-success print-success-msg" style="display:none">
                <ul></ul>
                </div>

                <div class="table-responsive">  
                    <table class="table table-bordered" id="dynamic_field">  
                        <tr>  
                            <td><input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list" /></td>  
                            <td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>  
                        </tr>  
                    </table>  
                    <input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" />  
                </div>
             </form>  
        </div> 
    </div>

    <script type="text/javascript">
        $(document).ready(function(){      
            var postURL = '/store';
            var i=1;  

            $('#add').click(function(){  
           i++;  
           $('#dynamic_field').append('<tr id="row'+i+'" class="dynamic-added"><td><input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list" /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');  
      });  

      $(document).on('click', '.btn_remove', function(){  
           var button_id = $(this).attr("id");   
           $('#row'+button_id+'').remove();  
      });  

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

      $('#submit').click(function(){            
           $.ajax({  
                url:postURL,  
                method:"POST",  
                data:$('#add_name').serialize(),
                type:'json',
                success:function(data)  
                {
                    if(data.error){
                        printErrorMsg(data.error);
                    }else{
                        i=1;
                        $('.dynamic-added').remove();
                        $('#add_name')[0].reset();
                        $(".print-success-msg").find("ul").html('');
                        $(".print-success-msg").css('display','block');
                        $(".print-error-msg").css('display','none');
                        $(".print-success-msg").find("ul").append('<li>Record Inserted Successfully.</li>');
                    }
                }  
           });  
      });  

      function printErrorMsg (msg) {
         $(".print-error-msg").find("ul").html('');
         $(".print-error-msg").css('display','block');
         $(".print-success-msg").css('display','none');
         $.each( msg, function( key, value ) {
            $(".print-error-msg").find("ul").append('<li>'+value+'</li>');
         });
      }
    });  
</script>
</body>
</html>

型号:

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class TagList extends Model
{
    public $table = "tagslist";
    public $fillable = ['name'];
}

迁移:

<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateTagslistTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('tagslist', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('tagslist');
    }
}