skip to Main Content

I have this function for validation with server, posting collected fields data and getting validation response. The problem is the object I send with data is not getting through, probably because of the bad format, any idea how I can format it right? (when I copy/paste the object datas got in console.log it works fine)

This is the function

function validateCalculator() {
    const objectProperties = calculatorElements();
    console.log(...objectProperties);
    $.ajax({
        method: 'POST',
        url: API,
        data: {
            id: productID,
            ...objectProperties,
        },
    }).done(function (data) {
        console.log(data);
    });
}

The log of the spread objectProperties

{RolledType[material]: "1"} {RolledType[size]: ""} {RolledType[magnet]: ""} {RolledType[lamination]: ""} {RolledType[ring]: ""} {RolledType[blindFrame]: ""} {RolledType[shadowFrame]: ""} {RolledType[hanger]: ""} {RolledType[edgeProtector]: ""} {RolledType[foil]: ""} {RolledType[rollup]: ""} {RolledType[quantity]: "1"} {RolledType[variant]: "1"}

2

Answers


  1. Chosen as BEST ANSWER

    The problem was a bit manyfold, but working upon @Barmar answer I reworked the function to this:

    function validateCalculator() {
        let objectProperties = calculatorElements();
        objectProperties = Object.fromEntries(
            objectProperties.map((obj) => [Object.keys(obj)[0].toString(), Object.values(obj)[0]]),
        );
    
        const objectPropertiesFull = {
            id: activeProductID,
            ...objectProperties,
        };
    
        if (objectPropertiesFull) {
            $.ajax({
                method: 'POST',
                url: rolledTypeAPI,
                data: objectPropertiesFull,
            }).done(function (data) {
                console.log(data);
            });
        }
    }
    

    So, one problem was the format of the response, had to convert it to key/value pairs, then constructed a new object with the added product ID and the properties spread in, and delayed the $.ajax, until the object is available (it was also firing too early, before the object properties existed)


  2. objectProperties should be a single object, not an array of objects. If you’re getting an array like that, you need to convert it to an object

    let objectProperties = calculatorElements();
    objectProperties = Object.fromEntries(objectProperties.map(obj => 
        [Object.keys(obj)[0], Object.values(obj)[0]]));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search