Arama butonu
Bu konudaki kullanıcılar: 1 misafir, 1 mobil kullanıcı
3
Cevap
152
Tıklama
0
Öne Çıkarma
AJAX Multi Level / çok seviyeli JSON istek gönderme
F
10 ay
Er
Konu Sahibi

Selamlar,

Sipariş formu için birden fazla ürün bilgisini json formatta API'ye göndermeye çalışıyorum. Aşağıdaki form örneğini kullanıyorum. Bir türlü istenen formatta json istek gönderemedim. Son çare bir konu oluşturmak işi bilenlerden akıl almak kaldı :)

Form:
<form class="sendRequestForm mt-4" enctype="multipart/form-data">
<div class="row">
<div class="col-lg-6 col-md-6 col-xs-12 form-group">
<div class="form-item">
<input type="text" name="title" class="form-control" placeholder="Başlık" value="">
</div>
</div>
</div>

<div class="row">
<div class="col-md-6">
<div class="form-item">
<input type="text" name="title[]" class="form-control" placeholder="Ürün Adı">
</div>
</div>
<div class="col-md-2">
<div class="form-item">
<input type="text" name="quantity[]" class="form-control" placeholder="Adet">
</div>
</div>
<div class="col-md-2">
<div class="form-item">
<input type="text" name="unitPrice[]" class="form-control" placeholder="Birim Fiyat">
</div>
</div>
<div class="col-md-2">
<div class="form-item">
<input type="text" name="totalPrice[]" class="form-control" placeholder="Toplam Fiyat">
</div>
</div>
</div>

<div class="row">
<div class="col-md-6">
<div class="form-item">
<input type="text" name="title[]" class="form-control" placeholder="Ürün Adı">
</div>
</div>
<div class="col-md-2">
<div class="form-item">
<input type="text" name="quantity[]" class="form-control" placeholder="Adet">
</div>
</div>
<div class="col-md-2">
<div class="form-item">
<input type="text" name="unitPrice[]" class="form-control" placeholder="Birim Fiyat">
</div>
</div>
<div class="col-md-2">
<div class="form-item">
<input type="text" name="totalPrice[]" class="form-control" placeholder="Toplam Fiyat">
</div>
</div>
</div>

<div class="row">
<div class="col-md-12 mt-4">
<div class="form-item">
<button type="button" class="btn btn-primary sendRequest" trnForm="sendRequestForm" trnAction="/requests/" trnMethod="POST">
Kaydet
</button>
</div>
</div>
</div>

</form>

İletmem gereken JSON Veri örneği:

var data =
{
 "title":"Teklif Başlık",
 "products":
{
 "items": 
 [
 {
"title": "Salatalık",
"quantity": "65",
"unitPrice": "65",
"totalPrice": "65"
 },
 {
"title": "Sivri Biber",
"quantity": "45",
"unitPrice": "45",
"totalPrice": "45"
 },
 {
"title": "Salkım Domates",
"quantity": "75",
"unitPrice": "75",
"totalPrice": "75"
 }
 ]
}
};


<script>
$(document).ready(function()
{

$("body").on( "click", ".sendRequest", function()
{
var trnForm = $(this).attr('trnForm');
var trnAction = $(this).attr('trnAction');
var trnMethod = $(this).attr('trnMethod');

if(typeof trnForm === "undefined" || trnForm=="")
{
alert("Hata! Form bulunamadı.");
}
else
{
trnForm = "."+trnForm;
$.ajax({
url: trnAction,
type: trnMethod,
data: JSON.stringify($(trnForm).serializeArray()),
dataType: "json",
contentType: "application/json",
success: function (trnData)
{
console.log(trnData);
}
});
}


});
});
</script>




C
10 ay
Binbaşı

StackExchange ağına baktınız, sorduuz mu?

https://stackexchange.com/sites#



D
10 ay
Yarbay

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Product Form</title>
</head>
<body>
  <form id="productForm">
    <div id="productContainer"></div>
    <button type="button" onclick="addProduct()">Add Product</button>
    <button type="submit">Submit</button>
  </form>

  <script>
    let productCount = 0;

    // Function to dynamically add product fields
    function addProduct() {
      productCount++;
      const productContainer = document.getElementById('productContainer');

      // Create a new product form group
      const productGroup = document.createElement('div');
      productGroup.innerHTML = `
        <div>
          <label for="product_name_${productCount}">Product Name:</label>
          <input type="text" id="product_name_${productCount}" name="product_name_${productCount}" required>
        </div>
        <div>
          <label for="quantity_${productCount}">Quantity:</label>
          <input type="number" id="quantity_${productCount}" name="quantity_${productCount}" required>
        </div>
        <div>
          <label for="unit_price_${productCount}">Unit Price:</label>
          <input type="number" step="0.01" id="unit_price_${productCount}" name="unit_price_${productCount}" required>
        </div>
        

      `;
      productContainer.appendChild(productGroup);
    }

    // Handle form submission
    document.getElementById('productForm').addEventListener('submit', function(event) {
      event.preventDefault(); // Prevent default form submission

      const formData = new FormData(event.target);
      const products = [];

      for (let i = 1; i <= productCount; i++) {
        const product = {
          product_name: formData.get(`product_name_${i}`),
          quantity: formData.get(`quantity_${i}`),
          unit_price: formData.get(`unit_price_${i}`)
        };
        products.push(product);
      }

      // Convert the product data to JSON
      const data = {
        products: products
      };

      // Send the JSON data via POST request
      fetch('YOUR_API_ENDPOINT_HERE', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
      })
      .then(response => response.json())
      .then(result => {
        console.log('Success:', result);
      })
      .catch(error => {
        console.error('Error:', error);
      });
    });
  </script>
</body>
</html>
quote:






D
10 ay
Yarbay

Bu kod sen ürün ekledikçe forma yeni ürün formu ekleyip sonra submit ettiğinde hepsini bir araya getiriyor. Tabi senin spesifik json formatın için azıcık kurcalaman lazım. Oda seni koda daha aşina yapar.

tarih öncesi kodlama teknikleri ile olmaz.



DH Mobil uygulaması ile devam edin. Mobil tarayıcınız ile mümkün olanların yanı sıra, birçok yeni ve faydalı özelliğe erişin. Gizle ve güncelleme çıkana kadar tekrar gösterme.