合并两个laravel AJAX功能,在一条路线中

问题描述 投票:0回答:1

我正在尝试将数据插入数据库,我的两个功能都在工作,但是当我尝试缩短它并放置一些常见内容时,它就不起作用了,我认为问题出在我的第一个功能中,我正在使用图像,并且对于该 contentType 和所有细节都不同,这就是它不起作用的原因

这是我的第一个功能,用于单一输入表单

<script>
         // for insert event into database
         function insertEvent(){
          $.ajaxSetup({
            headers: {
            'X-CSRF-TOKEN': '{{ csrf_token() }}'
            }
            });
            var image = $('#image').prop('files')[0]; 
            var formData = new FormData();
            formData.append('eventName', $('#eventName').val());
            formData.append('image', image);
            formData.append('price',$('#price').val());
            formData.append('location',$('#location').val());
            formData.append('desc',$('#desc').val());
                $.ajax({
                        type: 'POST',
                        dataType: 'json',
                        url: '{{ url('/inputForm') }}',
                        data: 
                          formData,
                        contentType: false,
                        processData: false, 
                        success: function(response) {
                            console.log(response);
                            var successDiv = document.getElementById('successMessage');
                            successDiv.innerHTML = response.message;
                            successDiv.classList.add('alert', 'alert-success');
                        } 
                    });
        }
    </script>

这是我的第二个功能,它是插入多个表单数据

{{-- for insert custom inpputs into database --}}
<script>
function insertCustomFields() {
  const forms = document.querySelectorAll('form[name="addCustomField"]');
  const formDataArray = [];

  forms.forEach((form, index) => {
    const customInputName = form.querySelector('[name="customInputName[]"]').value;
    const inputType = form.querySelector('[name="inputType[]"]').value;
    const checkboxes = form.querySelectorAll('[name="validation[]"]:checked');
    const checkedValues = Array.from(checkboxes).map(checkbox => checkbox.value);

    formDataArray.push({
      customInputName: customInputName,
      inputType: inputType,
      checkedValues: checkedValues
    });
  });

  $.ajaxSetup({
    headers: {
      'X-CSRF-TOKEN': '{{ csrf_token() }}'
    }
  });

  $.ajax({
    type: 'POST',
    dataType: 'json',
    url: '{{ url(' / inputForm ') }}',
    data: JSON.stringify(formDataArray), // Convert data to JSON string
    contentType: 'application/json', // Set content type to JSON
    success: function(response) {
      console.log(response);
      var successDiv = document.getElementById('successMessage');
      successDiv.innerHTML = response.message;
      successDiv.classList.add('alert', 'alert-success');
    }
  });

  console.log(formDataArray);
} 

第一个表单是单个表单,第二个表单我正在使用克隆制作副本

 <form  method="POST" enctype="multipart/form-data" id="addEventForm">
                @csrf
                <div class="row mb-3">
                  <label class="col-sm-2 col-form-label" for="basic-icon-default-fullname">Event Name</label>
                  <div class="col-sm-10">
                    <div class="input-group input-group-merge">
                      <span id="basic-icon-default-fullname2" class="input-group-text"
                        ><i class="bx bx-notepad"></i
                      ></span>
                      <input
                        type="text"
                        class="form-control"
                        id="eventName"
                        name="eventName"
                        data-parsley-pattern="[a-zA-Z\s]+$" data-parsley-trigger="keyup" required
                        data-parsley-errors-container="#eventNameError"
                        placeholder="Pool Party"
                        aria-label="Pool Party"
                        aria-describedby="basic-icon-default-fullname2"
                      />
                    </div>
                    <div id="eventNameError" class="error-container"></div>
                    @error('eventName')
                    <div class="text-danger">
                    {{$message}}
                    </div>
                @enderror
                  </div>
                </div>
                <div class="row mb-3">
                  <label class="col-sm-2 col-form-label" for="basic-icon-default-company">Price</label>
                  <div class="col-sm-10">
                    <div class="input-group input-group-merge">
                      <span id="basic-icon-default-company2" class="input-group-text"
                        ><i class="bx bx-money"></i
                      ></span>
                      <input
                        type="number"
                        id="price"
                        name="price"
                        data-parsley-trigger="keyup" required
                        data-parsley-errors-container="#priceError"
                        class="form-control"
                        placeholder="In Rs."
                        aria-label="In Rs."
                        aria-describedby="basic-icon-default-company2"
                      />
                    </div>
                    <div id="priceError" class="error-container"></div>
                    @error('price')
                    <div class="text-danger">
                    {{$message}}
                    </div>
                @enderror
                  </div>
                </div>
                <div class="row mb-3">
                  <label class="col-sm-2 col-form-label" for="basic-icon-default-email">Location</label>
                  <div class="col-sm-10">
                    <div class="input-group input-group-merge">
                      <span class="input-group-text"><i class="bx bx-map"></i></span>
                      <input
                        type="text"
                        id="location"
                        name="location"
                        data-parsley-trigger="keyup" required
                        data-parsley-errors-container="#locationError"
                        class="form-control"
                        placeholder="India , Gujarat"
                        aria-label="India , Gujarat"
                        aria-describedby="basic-icon-default-email2"
                      />
                    </div>
                    <div id="locationError" class="error-container"></div>
                    @error('location')
                    <div class="text-danger">
                    {{$message}}
                    </div>
                @enderror
                  </div>
                </div>
                
                <div class="row mb-3">
                  <label class="col-sm-2 form-label" for="basic-icon-default-message">Description</label>
                  <div class="col-sm-10">
                    <div class="input-group input-group-merge">
                      <span id="basic-icon-default-message2" class="input-group-text"
                        ><i class="bx bx-comment"></i
                      ></span>
                      <textarea
                        id="desc"
                        name="desc"
                        data-parsley-trigger="keyup" required
                        data-parsley-errors-container="#descError"
                        class="form-control"
                        placeholder="Write event details"
                        aria-label="Write event details"
                        aria-describedby="basic-icon-default-message2"
                      ></textarea>
                    </div>
                    <div id="descError" class="error-container"></div>
                    @error('desc')
                    <div class="text-danger">
                    {{$message}}
                    </div>
                @enderror
                  </div>
                </div>

            
                      <div class="row mb-3">
                        <label class="col-sm-2 form-label" for="basic-icon-default-message">Select an Image</label>
                        <div class="col-sm-10">
                            <div class="input-group input-group-merge">
                              <span id="basic-icon-default-message2" class="input-group-text"
                                ><i class="bx bxs-image"></i
                              ></span>
                              <input class="form-control" 
                              type="file" id="image" name="image"
                              data-parsley-trigger="keyup" required
                              data-parsley-errors-container="#imageError"
                              accept="image/png,image/jpeg,image/jpg" />
                            </div>
                            <div id="imageError" class="error-container"></div>
                            @error('image')
                    <div class="text-danger">
                    {{$message}}
                    </div>
                @enderror
                <div id="preview"></div>
                <style>
                  .center-image {
                      display: left;
                      margin-left: auto;
                      margin-right: auto;
                      margin-top: 15px;
                  }
              </style>
                          </div>
                      </div>
                    </form>       
                <div class="row justify-content-end text-end">
                  <div class="col-sm-10">
                    <a href="#" class="btn btn-primary" onclick="duplicateForm()" name="add_field" id="add_field">Add Custom Field</a>
                  </div>
                </div>
                <div id="customField"></div>
              {{-- custom field form starts--}}
              <form action="" method="POST" enctype="multipart/form-data" id="addCustomField" name="addCustomField">
                <div class="card-body">
                  <div class="row">
                    <div class="justify-content-end text-end">
                      <button class="remove-form" type="button" onclick="removeLastElem()">Remove</button>
                      </div>
                      <div class="col-md-6 mb-3">
                          <label class="form-label" for="customInputName">Custom Input Name</label>
                          <div class="input-group">
                              <span class="input-group-text">
                                  <i class="bx bx-notepad"></i>
                              </span>
                              <input
                                  type="text"
                                  class="form-control"
                                  required
                                  id="customInputName"
                                  name="customInputName[]"
                                  placeholder="Pool Party"
                                  aria-label="Pool Party"
                              />
                          </div>
                      </div>
              
                      <div class="col-md-6 mb-3">
                          <label class="form-label" for="inputType">Input Type</label>
                          <div class="input-group">
                              <span class="input-group-text">
                                  <i class="bx bx-notepad"></i>
                              </span>
                              <select id="inputType" class="form-select" name="inputType[]" required>
                                  <option value="text">Text</option>
                                  <option value="number">Number</option>
                                  <option value="email">Email</option>
                                  <option value="file">File</option>
                                  <option value="hidden">Hidden</option>
                              </select>
                          </div>
                      </div>
                  </div>
              
                  <div class="row">
                      <label class="col-md-2 col-form-label" for="basic-icon-default-fullname">Validation</label>
                      <div class="col-md-10">
                          <div class="form-check mb-2">
                              <input class="form-check-input" type="checkbox" value="required" id="required" name="validation[]" checked />
                              <label class="form-check-label" for="required">Required</label>
                          </div>
                          <div class="form-check mb-2">
                              <input class="form-check-input" type="checkbox" value="alpha" id="alpha" name="validation[]" />
                              <label class="form-check-label" for="alpha">Alphabets Only</label>
                          </div>
                          <div class="form-check mb-2">
                              <input class="form-check-input" type="checkbox" value="/^[a-zA-Z\s]+$/" id="alphaSpace" name="validation[]" />
                              <label class="form-check-label" for="alphaSpace">Alphabets with Space</label>
                          </div>
                          <div class="form-check mb-2">
                              <input class="form-check-input" type="checkbox" value="number" id="number" name="validation[]" />
                              <label class="form-check-label" for="number">Number Only</label>
                          </div>
                      </div>
                  </div>
              </div>
              </form>```
ajax laravel forms function merge
1个回答
0
投票

首先使用单个

form
标签合并表单,保留该表单中的所有元素,然后合并
ajax
调用,对单个
Ajax
调用使用单个提交事件,这样您就可以使其与单个 ajax 调用。

© www.soinside.com 2019 - 2024. All rights reserved.