1

I am using an Ajax (POST) request to update the current user profile. So far I can successfully update the user fields (like fullName) but I cannot seem to update custom fields.

I have tried adding the custom fields within the fields array (just like when using an HTML form), but this doesn't seem to work.

Below my code:

$('.js-update-profile').click(function() {
    var id = $(this).data('id');
    var fields = [];
    fields['nickname'] = 'Nickname';
    const params = {
        CRAFT_CSRF_TOKEN: csrfTokenValue,
        userId: player.id,
        fields: fields,
    };
    $.ajax({
        url: '/actions/users/save-user',
        type: 'POST',
        data: params,
        headers: {
            'Accept': 'application/json',
            'X-Requested-With': 'XMLHttpRequest',
        },
        dataType: 'json',
        success: function (params) {
            console.log(params);
        }
    });
});

When I excute this code I'm getting a successfull message User saved, but the custom fields are not updated.

Am I doing something wrong with setting up the params?

1 Answer 1

2

I wager this is the problem:

var fields = [];
fields['nickname'] = 'Nickname';

JavaScript doesn't have associative arrays like PHP. The fact that this works at all is only a quirk in JavaScript – Arrays are objects, so you can assign properties to them. So you're adding a fields.nickname property, but that's not part of the array. So jQuery can't really pick up the property, as the array itself is still empty.

Use an object instead, then it should work:

const fields = {
    nickname: 'Nickname',
};

If you need to add properties dynamically:

const fields = {};
fields.nickname = 'Nickname';

// for element fields, use an array of IDs
fields.category = [42, 50]

To debug a problem like this, open up the Network tab in your browser's devtools. There you can see and inspect the payload for the AJAX request. Check the request payload to see if you data is actually getting transmitted.

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.