如何在Laravel 5.2中发送多个参数AJAX

时间:2022-10-18 14:59:54

How do I send multiple values for AJAX Laravel. for Example:

如何为AJAX Laravel发送多个值。例如:

$('#submit_').on('click', function (e) {
     e.preventDefault();
     var form_data = $('#create').serialize();
     var form_taxonomy = 'category';
     $.ajax({
          headers: {
              'X-CSRF-Token': $('input[name="_token"]').val()
          },
                type: 'post',
                url: '{!! URL::route('category') !!}',
                data: {formData:form_data,formTaxonomy: form_taxonomy},
                success: function () {
                    $('#append').load('{!! URL::route('loadCat') !!}');
                },
                error: function (xhr, status, errorThrown) {
                    alert(JSON.parse(xhr.responseText).category[0]);
                }
            });
            jQuery("#create").val('');
        });

controller code:

public function create(messageRequest $request)
{
    if($request->ajax()) {
        $name = Input::get('formData');
        $taxonomy = Input::get('formTaxonomy');
        return response()->json($name, $taxonomy);
    }
}

html code:

<div class="col-sm-6">
<form method="POST" action="http://localhost:8000/category" accept-charset="UTF-8"><input name="_token"
                                                                                          value="IzByO9fU5yeanaVCudCQpkL5bXGzUh9B4jb400iU"
                                                                                          type="hidden">

    <div class="form-group">
        <div class="form-group">
            <input class="form-control text-right" id="create" name="category" type="text">
        </div>
        <div id="submit_"><input name="createSub" id="submit" class="btn btn-primary" value="submit" type="submit">
        </div>
    </div>
</form>

message request validate:

消息请求验证:

    public function rules()
{
    return array(
    'category'=>'required|alpha|unique:taxonomies,name',
    );
}
public function messages(){
    return [

        'category.required'=>'fill',
        'category.alpha'=>'only charecter',
        'category.unique'=>'dublicate'
    ];
}

This code not work . I used my other examples, but no one was not responsive to the problem is that I don't know only parameter data in laravel how to call the amount that would not be faced with an error and stored in the database .

这段代码不起作用。我使用了我的其他示例,但没有人没有响应问题是我不知道laravel中的参数数据如何调用不会遇到错误并存储在数据库中的数量。

3 个解决方案

#1


1  

You are using FormRequests to act as validation for that controller method. In this case, your FormRequest is: MessageRequest - which includes a validation parameter by the name of category.

您正在使用FormRequests充当该控制器方法的验证。在这种情况下,您的FormRequest是:MessageRequest - 其中包含类别名称的验证参数。

When your ajax submission takes place, it is not providing the category field, and therefore failing validation.

当您的ajax提交发生时,它没有提供类别字段,因此未通过验证。

To test, try supplying category data to the ajax data:

要进行测试,请尝试向ajax数据提供类别数据:

data: {formData:form_data,formTaxonomy: form_taxonomy, category: 'somevalue-unique-to-your-taxonomies'},

#2


3  

You've already serialized the form, which generates the name=value&name=value query string format. It looks like you then want to add data to this query string for submission. You will need to do this somewhat manually, but it can be done like this:

您已经序列化了表单,该表单生成name = value&name = value查询字符串格式。您似乎想要将数据添加到此查询字符串以进行提交。您需要手动执行此操作,但可以这样做:

$('#submit_').on('click', function (e) {
    e.preventDefault();
    var form_data = $('#create').serialize();
    var form_taxonomy = 'category';
    $.ajax({
        headers: {
            'X-CSRF-Token': $('input[name="_token"]').val()
        },
        type: 'post',
        url: '{!! URL::route('category') !!}',
        // manually combine your form data and your additional post data
        // into one query string
        data: form_data + '&' + $.param({formTaxonomy: form_taxonomy}),
        success: function () {
            $('#append').load('{!! URL::route('loadCat') !!}');
        },
        error: function (xhr, status, errorThrown) {
            alert(JSON.parse(xhr.responseText).category[0]);
        }
    });
    jQuery("#create").val('');
});

Edit

With your existing code, the issue that you're having is that your messageRequest validation says that the category field is required, but your request data does not have a category field. Because of this, your validation is failing, and will return a 422 response with a JSON object containing your validation errors.

使用现有代码,您遇到的问题是您的messageRequest验证表明类别字段是必需的,但您的请求数据没有类别字段。因此,您的验证失败,并将返回包含验证错误的JSON对象的422响应。

With the updated code above, your request data now has a category field, so validation is passing, but you have some other error in your code that is generating a 500 error. You need to track this down and fix it, which may require another question.

使用上面的更新代码,您的请求数据现在有一个类别字段,因此验证正在通过,但您的代码中还有一些其他错误,产生500错误。你需要跟踪它并修复它,这可能需要另一个问题。

#3


0  

Change your data part like this :

像这样更改您的数据部分:

data: {'formData':form_data,'formTaxonomy': form_taxonomy},

#1


1  

You are using FormRequests to act as validation for that controller method. In this case, your FormRequest is: MessageRequest - which includes a validation parameter by the name of category.

您正在使用FormRequests充当该控制器方法的验证。在这种情况下,您的FormRequest是:MessageRequest - 其中包含类别名称的验证参数。

When your ajax submission takes place, it is not providing the category field, and therefore failing validation.

当您的ajax提交发生时,它没有提供类别字段,因此未通过验证。

To test, try supplying category data to the ajax data:

要进行测试,请尝试向ajax数据提供类别数据:

data: {formData:form_data,formTaxonomy: form_taxonomy, category: 'somevalue-unique-to-your-taxonomies'},

#2


3  

You've already serialized the form, which generates the name=value&name=value query string format. It looks like you then want to add data to this query string for submission. You will need to do this somewhat manually, but it can be done like this:

您已经序列化了表单,该表单生成name = value&name = value查询字符串格式。您似乎想要将数据添加到此查询字符串以进行提交。您需要手动执行此操作,但可以这样做:

$('#submit_').on('click', function (e) {
    e.preventDefault();
    var form_data = $('#create').serialize();
    var form_taxonomy = 'category';
    $.ajax({
        headers: {
            'X-CSRF-Token': $('input[name="_token"]').val()
        },
        type: 'post',
        url: '{!! URL::route('category') !!}',
        // manually combine your form data and your additional post data
        // into one query string
        data: form_data + '&' + $.param({formTaxonomy: form_taxonomy}),
        success: function () {
            $('#append').load('{!! URL::route('loadCat') !!}');
        },
        error: function (xhr, status, errorThrown) {
            alert(JSON.parse(xhr.responseText).category[0]);
        }
    });
    jQuery("#create").val('');
});

Edit

With your existing code, the issue that you're having is that your messageRequest validation says that the category field is required, but your request data does not have a category field. Because of this, your validation is failing, and will return a 422 response with a JSON object containing your validation errors.

使用现有代码,您遇到的问题是您的messageRequest验证表明类别字段是必需的,但您的请求数据没有类别字段。因此,您的验证失败,并将返回包含验证错误的JSON对象的422响应。

With the updated code above, your request data now has a category field, so validation is passing, but you have some other error in your code that is generating a 500 error. You need to track this down and fix it, which may require another question.

使用上面的更新代码,您的请求数据现在有一个类别字段,因此验证正在通过,但您的代码中还有一些其他错误,产生500错误。你需要跟踪它并修复它,这可能需要另一个问题。

#3


0  

Change your data part like this :

像这样更改您的数据部分:

data: {'formData':form_data,'formTaxonomy': form_taxonomy},