skip to Main Content

I wanted to send 3 objects to my server. 2 payment response objects and one object contains my form input field values. But if i send it together like i shown below, the formData is treated as string in server side which i cant access. If i only send the formData there are no issues. There is no issue if i only send other 2 objects. How can i get it as an json object on server side?

const formData = $('#checkoutForm').serialize();

this function is called after the response from razorpay. Payment and order are the responses from razorpay


function verifyPayment(payment, order) {
  $.ajax({
    url: '/verify-payment',
    type: 'POST',
    data: {
      payment,
      order,
      formData,
    },
    success: function (response) {
      console.log('payment status', response);
    },
    error: function (error) {
      console.log(error);
    },
  });
}

console for req.body in server:

form data from verify patment=== {
  payment: {
    razorpay_payment_id: 'pay_NQKts6UWsReLkf',
    razorpay_order_id: 'order_NQKtkMV1mv3AiT',
    razorpay_signature:
      'beb2eac3df927dd1901da8f79140be832bb6f662135ed04a3f23ded32ab80e9f',
  },
  order: {
    id: 'order_NQKtkMV1mv3AiT',
    entity: 'order',
    amount: '129900',
    amount_paid: '0',
    amount_due: '129900',
    currency: 'INR',
    receipt: '8774a2511705637831834',
    offer_id: '',
    status: 'created',
    attempts: '0',
    created_at: '1705637832',
  },
  formData:
    'fullName=&phoneNUmber=&email=&house=&landMark=&city=&district=&state=&pincode=&selectedAddress=Ahammed+Zulaikh%0D%0AManthadathil(H)%0D%0AChalilpara%0D%0AMALAPPURAM%0D%0A676508%0D%0AMalappuram%0D%0AKERALA%0D%0A919605633278&deliveryInstruction=&totalPrice=1299&paymentMethod=Online+Payment&productId=6 593d05163f67fb7dd7b3182&productPrice=1299&orderProductQty=1',
};

console.log(typeOf req.body.formData) gives a string.

2

Answers


  1. you can use this

    const formData = JSON.stringify($(‘#checkoutForm’).serializeArray());

    function verifyPayment(payment, order) {
    $.ajax({
    url: ‘/verify-payment’,
    type: ‘POST’,
    contentType: ‘application/json’, // Set content type to JSON
    data: JSON.stringify({
    payment,
    order,
    formData
    }),
    success: function(response) {
    console.log(‘payment status’, response);
    },
    error: function(error) {
    console.log(error);
    }
    });
    }

    Login or Signup to reply.
  2. jQuery’s .serialize() returns an application/x-www-form-urlencoded string.

    Given the object structures of your existing payment and order properties, I would recommend sending the request payload as JSON.

    You certainly don’t need jQuery for any of this.

    First, capture the form data as a plain object

    const formData = Object.fromEntries(
      new FormData(document.getElementById("checkoutForm")),
    );
    

    Then send a request to your API

    async function verifyPayment(payment, order) {
      try {
        const res = await fetch("/verify-payment", {
          method: "POST",
          headers: { "content-type": "application/json" },
          body: JSON.stringify({ payment, order, formData }),
        });
    
        if (!res.ok) {
          throw new Error(`${res.statusText} ${res.status}: ${await res.text()}`);
        }
    
        console.log("payment status", await res.text()); // or res.json()
      } catch (err) {
        console.error(err);
      }
    }
    

    On the server-side, you’d just need to ensure you were able to handle JSON request bodies using the appropriate middleware

    app.use(express.json());
    

    If you really still wanted to use jQuery to send the request, it would look like this

    $.ajax({
      url: '/verify-payment',
      method: 'POST',
      contentType: 'application/json',
      data: JSON.stringify({ payment, order, formData }),
      success: function(response) {
        console.log('payment status', response);
      },
      error: function(_, ...err) {
        console.error(...err);
      }
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search