skip to Main Content

I have such results and I need to append them in my view:

val: {email: Array(1), first_name: Array(1)}
    email: Array(1)
        0: "The email field is required."
        length: 1
        __proto__: Array(0)
    first_name: Array(1)
        0: "The first name field is required."
        length: 1
        __proto__: Array(0)
        __proto__: Object

code

$('#submitRegister').on('click', function(e) {
    e.preventDefault();
    $.ajaxSetup({
        headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') }
    });

    var formData = {};
    $('#registerForm').find("input[name]").each(function (index, node) {
        formData[node.name] = node.value;
    });

    $.ajax({
        url: '{{route('frontend.register.validate')}}',
        type: "POST",
        data: {
            "_token": "{{ csrf_token() }}",
            formData,
        },
        dataType: "json",
        success:function(data) {
            $(data.errors).each(function (index, value) {
                console.log('val: ', value);
            });
        }
    });
});

html

<div id="errors"></div>

any idea?

2

Answers


  1. You can use document.getElementById() to find the element you want to append things to, then you can use document.createElement() to create an element to append, and then you can use append() to append it to the div. So, all together:

    var errors = document.getElementById('errors'); // Getting the div we want to append to
    var newElement = document.createElement('h1'); // Creating the element we want to append to the errors div
    newElement.textContent = value; // Setting the text value of the new element to the information we want to display
    errors.append(newElement); // Appending the new element to the errors div
    

    You should be able to put this in your .each() function, after the console.log().

    Login or Signup to reply.
  2. You need to use Object.keys then check and loop inside each array

    val  = {email: ["The email field is required."], first_name: ["The first name field is required."] };
    
    
    var errs = []
    
    keys = Object.keys(val)
    
    for(var i=0; i<keys.length;i++)
    {
     
      if(Array.isArray(val[keys[i]]))
      {
        for(var j=0; j<val[keys[i]].length; j++)
          errs.push(val[keys[i]][j])
      }
      else
          errs.push(val[i])
    }
    
    var str = '';
    $.each(errs, function( index, value ) {
      str += '<li>' + value + '</li>';
    });
    
    $('#msgs').html(str);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <div id="msgs"></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search