【问题标题】:How to store data automatically after some seconds in laravel using ajax?如何使用ajax在laravel中几秒钟后自动存储数据?
【发布时间】:2020-02-28 22:00:33
【问题描述】:

我在我的项目中创建了文章发布部分。在发布文章中,我想将数据自动存储为我的文章表中的 drft。 在这里,我将刀片文件与表单和 ajax 代码一起放置。此 ajax 代码不起作用意味着后台没有发生任何事情。当我输入标题时,没有存储任何数据,当我打开控制台并检查它仅适用于字符串运行时。请查看此链接https://imgur.com/9MGxojj

<form action="{{ route('articles.store') }}" method="POST" enctype='multipart/form-data'>
  @csrf

  <div class="card shadow">
   <div class="card-body pt-3">
    <div class="row">
      <div class="col-xs-9 col-sm-9 col-md-9">
        <div class="form-group">
          <div >
            <input id="title" type="text" placeholder="Enter title here" class="form-control form--control{{ $errors->has('title') ? ' is-invalid' : '' }}" name="title" value="{{ old('title') }}">
            @if ($errors->has('title'))
            <span class="invalid-feedback" role="alert">
              <strong>{{ $errors->first('title') }}</strong>
            </span>
            @endif
          </div>
        </div>
        <div class="form-group">
          <div>
           <textarea name="description" id="mytextarea"  class="form-control textarea {{ $errors->has('description') ? ' is-invalid' : '' }}" placeholder="Description">{{old('description')}}</textarea>

           @if ($errors->has('description'))
           <span class="invalid-feedback" role="alert">
            <strong>{{ $errors->first('description') }}</strong>
          </span>
          @endif
        </div>
      </div>

    </div>    <div class="col-xs-3 col-sm-3 col-md-3">

      <div class="card">
       <div class="card-body">


         <div class="form-group">
          <label for="category_id">Choose category:</label>
          <select name="category_id" id="category_id" class="form-control @error('category_id') is-invalid @enderror"  value="{{ old('category_id') }}"   >
            <option value="0">Select Category</option>
            @foreach($category as $category)
            <option value="{{$category->id}}">{{$category->name}}</option>
            @endforeach
          </select>
          @error('category_id')
          <span class="invalid-feedback" role="alert">
            <strong>{{ $message }}</strong>
          </span>
          @enderror

        </div>
        <div class="form-group">
          <label for="subcategory_id">Sub category:</label>
          <select id="subcategory_id" name="subcategory_id" class="form-control">

          </select>

        </div> 



        <div class="form-group">
          <small>Publish Date</small>

          <div>
            <input id="datepicker" type="text" class=" py-2 form-control{{ $errors->has('show_date') ? ' is-invalid' : '' }}" name="show_date" value="@if(old('show_date')=="") {{date('Y-m-d')}} @else {{ old('show_date') }} @endif">
            @if ($errors->has('show_date'))
            <span class="invalid-feedback" role="alert">
              <strong>{{ $errors->first('show_date') }}</strong>
            </span>
            @endif
          </div>
        </div>


        <div class="form-group">
          <div>
            <small>Featured image</small>
            <input id="image"  name="image"  type="file" class="form-control {{ $errors->has('image') ? ' is-invalid' : '' }}" value="{{ old('image') }}">
            @if ($errors->has('image'))
            <span class="invalid-feedback" role="alert">
              <strong>{{ $errors->first('image') }}</strong>
            </span>
            @endif
          </div>
        </div>  



      </div>
    </div><!-- End Right Col -->


    <div class="card">
     <div class="card-body">
      <strong>Tag :</strong>
      <section id='outside-of-the-box'>

        <aside class='rightSide'>
          <input name='tags' class='tagify--outside form-control' value='' placeholder='write some tags'>
          <small>Tag's with comma separator</small>
        </aside>
      </section>
    </form>
  </div>
</div>
<a href="{{ route('articles.index') }}" class="btn btn-outline-secondary font-weight-normal mr-2">Cancel</a>
<input type="submit" class="btn btn-primary font-weight-normal px-3" name="publish" value="Publish">
<input type="submit" class="btn btn-outline-secondary font-weight-normal mx-2" name="save" value="Save as Draft">
</div>        

</div>

</div><!-- End Row -->
</div>
</form> 

这是脚本 ajax 代码...

<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>  
 $(document).ready(function(){  
      function autoSave()  
      {  
           var title = $('#title').val();  
           var description = $('#mytextarea').val();  
           // var category_id = $('#category_id').val();  
           if(title != '' && description != '')  
           {  
                $.ajax({  
                     url:"{{url('articles')}}",  
                     method:"POST",  
                     data:{title:title, description:description},  
                     dataType:"text",  
                     success:function(data)  
                     {  
                          // if(data != '')  
                          // {  
                          //      $('#category_id').val(data);  
                          // }  
                          $('#autoSave').text("Post save as draft");  
                          setInterval(function(){  
                               $('#autoSave').text('');  
                          }, 3000);  
                     },

                });  
           }            
      }  
      setInterval(function(){   
           autoSave();   
           }, 3000);  
 });  
 </script>

这是我的资源路线

This is my resource route
Route::resource('articles','ArticleController');

datatabel column fields are

title
description
category_id
show_date
slug
draft

【问题讨论】:

  • 大胆猜测 - 您显示的内容中只有 3 行 JS,最后一行包含看起来像语法错误的内容 - 一个额外的随机 datepicker。这可能意味着页面上没有其他 JS 工作或运行。如果不是这样,也许您可​​以澄清一下,例如 1) Here I have put the blade file with form and ajax code - 这里没有 AJAX 代码; 2) when I open console and check it only works string running - 这是什么意思?
  • @Don'tPanic 哦,对不起我的错误......我忘了粘贴 ajax......我的错......当我运行代码时控制台像这样运行?表示脚本何时运行..
  • 在 laravel 中,你必须在 ajax 调用 post 方法时使用令牌。
  • @AkhtarMunir 你能修复这个代码吗?
  • @NeerajTangariya 查看答案

标签: javascript php jquery ajax laravel-6


【解决方案1】:

我建议您对 ajax 部分进行一些更改,只需复制我的代码即可。

$.ajax({  
       method:"POST", 
       url:"{{ route('articles.store') }}",  //Here you are using just `articles` so which route ? You have to write something like mine. Because it's a resource route.
       data:{title:title, description:description,_token:@json(csrf_token())}, //You also need to pass token here as well, like I have done for you
       success:function(data)  
       {  
         console.log(data);  
       },
       error: function(data){
         console.log(data);
       }
    });

并且从控制器首先返回一个简单的问候消息以查看,例如return "Hello";,当您收到消息时,您可以继续进行其余的操作。

我想提一下重要的一点,你正在使用资源路由和控制器,所以你的路由名称应该是这样的。

  1. articles.index
  2. articles.store
  3. articles.create 等...

如果要查看资源路由的所有路由,请在项目目录中的cmd 中运行此命令

php artisan route:list --path=articles

【讨论】:

  • just copy my code - 为什么?您的代码有什么不同,它如何解决 OP 代码中的问题?这可能是答案,但如果你解释你做了什么以及为什么,你的答案会质量更高。对于 OP 或所有将来到这里的未来 SO 访问者来说,复制粘贴不是学习。
  • @Don'tPanic,如果你看到答案的评论你就会知道,为什么我写了这句话just copy my code,我也指出了几点。
  • 对不起,评论问题*
猜你喜欢
  • 1970-01-01
  • 2015-06-03
  • 2016-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-06
相关资源
最近更新 更多