Search code examples
jqueryajaxexpressionenginesafecracker

TypeError: field_errors.join is not a function


I am having a small issue with my ajax success call.

In the success call I have the following:

if (data.success) {
                window.location.href = "/account/submission-complete/"+data.entry_id;
            } else {
                var field_errors = '';
                for (field in data.field_errors) {
                    field_errors += data.field_errors[field]+"\n";
                }       

                var formErrors = 'Upload Failed<br>' + data.errors.join('<br>') + field_errors.join('<br>');

                var percentVal = '0%';
                bar.width(percentVal)
                percent.html(percentVal);
                $('#file-info').html(formErrors).slideDown('slow');
            }

The following error is being output in my JS console...

TypeError: field_errors.join is not a function

Can anyone explain to me why this is occuring, and how I can fix it? as I need to add a '
' after, which I only know how to use .join().

Thank you.


Solution

  • Instead of doing this:

    field_errors.join('<br>')
    

    do this:

    data.field_errors.join('<br/>')
    

    Since join is used to join all elements of an array into a string. Hence, it works on the array elements, not string, which is your field_errors is here.

    UPDATE

    // Add all the object data into the field_errors array
    var field_errors = [];
    for (field in data.field_errors) {
        field_errors.push(data.field_errors[field]);
    }
    
    // Check the console, if the array is correct or not
    console.log(field_errors);
    
    // Now join will work on the array element
    field_errors.join('<br/>')