1

I have a project that was initially built in Craft 3 and I'm upgrading it to Craft 4. I leverage ajax on one of the pages to save data to a user in the CMS. The following code worked in Craft 3 but no longer works in Craft 4. The ajax request submits correctly and the data is saved to the CMS but data.success no longer returns true. What's the ideal way to handle an ajax pass/fail in Craft 4?

$.ajax({
    contentType: false,
    processData: false,
    method: "POST",
    url: '',
    dataType: "json",
    data: formData
}).done(function(data) {
    if (data.success == true) {
        console.log(data, 'success')
    } else {
        console.log(data, 'fail')
    }
}).fail(function(data) {
    console.log(data, 'fail')
});

1 Answer 1

1

Controllers in Craft 4 generally use the asSuccess and asFailure methods, which return 200 and 400 status codes respectively, in response to JSON requests.

Both methods also send a message parameter in their response, in case there's something to report, so the following should work.

$.ajax({...})
    .done(function(data) {
        console.log('success: ' + data.message);
    })
    .fail(function(data) {
        console.log('fail: ' + data.message);
    });
1
  • This worked, thank ya sir! Jun 24 at 16:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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