简体   繁体   English

Ajax 后空 [Laravel]

[英]Ajax post empty [Laravel]

so i want to create a page that will create a category, but it says that im using method GET to create a new category while the form is using POST, i realize that there might be an error with an ajax, because if i didn't use it, i can create a new category normally.所以我想创建一个页面来创建一个类别,但它说我在表单使用 POST 时使用方法 GET 创建一个新类别,我意识到 ajax 可能会出错,因为如果我没有'不使用它,我可以正常创建一个新类别。 this is the routes :这是路线:

Route::group(['prefix' => 'category'], function(){
    Route::get('/', 'HomeController@category')->name('category');
    Route::get('add', 'HomeController@addCategory');
    Route::post('add/go', 'HomeController@newCategory');
});

and the controller is like this :控制器是这样的:

public function newCategory(Request $request) {
    $category = new Category;
    $name = $request->catname;
    $url = $request->curl;
    $meta = $request->catmeta;
    $timestamp = date('Y-m-d H:i:s');
    $category->name = $name;
    $category->url = $url;
    $category->meta = $meta;
    $category->created_at = $timestamp;
    $category->updated_at = NULL;
    $addCat = $category->save();
    if($addCat) {
        return response()->json(array('status' => 200, 'message' => array('title' => 'Success', 'msg' => 'Category has been added')));
    } else {
        return response()->json(array('status' => 500, 'message' => array('title' => 'Failed', 'msg' => 'Failed adding Category, Try again later.')));
    }
}

this is the form :这是表格:

<form method="POST" id="catNew">
 @csrf
 <div class="row">
    <div class="col-md-2">
          <label for="title">Name:</label>
    </div>
  <div class="col-md-10">
    <input type="text" class="form-control" name="catname" placeholder="Category Name"/>
  </div>
  </div>
  <div class="row" style="margin-top: 10px;">
    <div class="col-md-2">
        <label for="title">url:</label>
    </div>
    <div class="col-md-10">
        <input type="text" class="form-control" name="curl"  placeholder="ex: lorem-ipsum"/>
    </div>
    </div>
    <div class="row" style="margin-top: 10px;">
    <div class="col-md-2">
        <label for="title">Meta:</label>
    </div>
    <div class="col-md-10">
        <input type="text" class="form-control" name="catmeta" placeholder="The Meta Description"/>
    </div>
    </div>
    <div class="row" style="margin-top: 10px">
<div class="col-md-12">
        <button type="submit" class="btn btn-success" style="margin-left: 20px; margin-right: 10px">Submit</button>
        <button onclick="window.location.href='/admin/category';" class="btn btn-danger">Cancel</button>
</div>
  </div>
</form>

this the ajax that i use for all the post request (creating and update), but i don't know why in this case, the script didn't work.这是我用于所有发布请求(创建和更新)的 ajax,但我不知道为什么在这种情况下,脚本不起作用。

<script>
window.onload = function() {
  function fetch_data() {
    $.ajax({
       url: "/admin/todo/get",
       method: "GET",
        success: function(data) {
          $('#notes').html(data);
           }
          });
        }
      fetch_data();
}
$(document).on('submit', '#catNew', function(e) {

  e.preventDefault();

    var fd = new FormData($('#catNew')[0]);

    $.ajax({

      url: '/admin/category/add/go/',
      type: 'POST',
      data: fd,
      processData: false,
      contentType: false,
      dataType: 'json',
      async: true,
      error: function(xhr, status, message){
      console.log(xhr.responseText);
      }}).done(function(data) {
       switch(data.status) {

       case 200:
    alertify.success(data.message.title, data.message.msg);
    window.location.href = '/admin/category';
    break;
       default:
    alert(data.message.title, data.message.msg);
       }
     });
   });
</script>

NB : while im using Route::any();注意:当我使用 Route::any(); for the process, i get this error (it only happens when im using ajax) :对于该过程,我收到此错误(仅在我使用 ajax 时才会发生):

{
    "message": "SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'name' cannot be null (SQL: insert into `category` (`name`, `url`, `meta`, `created_at`, `updated_at`) values (, , , 2019-03-21 07:32:08, ))",
    "exception": "Illuminate\\Database\\QueryException",
    "file": "D:\\xampp\\htdocs\\laravel4\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Connection.php",
    "line": 664,
    "trace": [
        {
            "file": "D:\\xampp\\htdocs\\laravel4\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Connection.php",
            "line": 624,
            "function": "runQueryCallback",
            "class": "Illuminate\\Database\\Connection",
            "type": "->"
        },
        {
            "file": "D:\\xampp\\htdocs\\laravel4\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Connection.php",
            "line": 459,
            "function": "run",
            "class": "Illuminate\\Database\\Connection",
            "type": "->"
        },
…

As you set your dataType json you need to use input() method to retrive the value.当您设置 dataType json 时,您需要使用input()方法来检索值。

$name = $request->input('catname');

https://laravel.com/docs/5.5/requests#retrieving-input https://laravel.com/docs/5.5/requests#retrieving-input

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

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