javascript - Datatable showing only on row from jquery ajax response ← (PHP, JavaScript, JQuery, HTML)

I wrote two different functions using jquery, the first function(table()) loop through an object from JSON response in jquery ajax success. Then call the second function(column()) called column with a parameter an element of the array from the object in the first loop. to make it short i expect the result to be rows, with columns of data from the database.

search();

function search(query){
  
  $.ajax({
        type:'GET',
        url:'/getmsg',
        data:{
                "_token":"{{ csrf_token() }}",
                query:query,
              },
        success:function(response){
          table = row(response);
          $("#content").html(table);
          console.log(response);
        },
});
}

//ROWS
function row(response){
  //  LOOP TROUGH THE OBJECTS
  //  DISPLAY THE ROWS
  
  columns = "";
 
  for(i = 0; i<response.length; i++){
    //columns = "<tr>";
    object = response[i];
    columns += column(object);
  }
  console.log(columns);
  return columns;
}

//COLUMN
function column(object){
  // return object["id"];
  // output = "<td>"+object['id']+"</td><td>"+object['name']+"</td><td>"+object['email']+"</td>";
  obj = Object.values(object);
  output = "<tr>";
  for(i=0; i<obj.length; i++){
    output +="<td>"+obj[i]+"</td>";
  }
  output += "</tr>";
  return output;
}

Answer



Solution:

This is how I was able to fix this error. STEP 1 1. I tried for figure out the where the logical error occurred by trying to display count for of loops in the first function table and it works correctly, which means the error is within the column() function 2. I tried the same way in the second function column() and I figured out it only loops once. this means I point of concentration. Still, it doesn't show any syntax error.

STEP 2 I started suspecting scoping issues I decided to copy the script in the column() function and paste it in the table() withing the loop. This way i'm exacuting the code directly, but you notice the outer loop and the inner loop are having a pointer variable with the same declaration ( i ) which will cause a syntax error. i changed the inner loop pointer declaration to ( j ) IT STARTED WORKING PROPERLY. The error i have been battling with was scoping error. unlike JAVA and PHP that i know, i believe js has the most complicated scoping logical errors, so watch out. CONCLUTION In JavaScript there are two types of scope: 1. Local scope 1. Global scope

According to https://www.w3schools.com/js/js_scope.asp Local JavaScript Variables

Variables declared within a JavaScript function, become LOCAL to the function.

Local variables have Function scope: They can only be accessed from within the function. Example

// code here can NOT use carName

function myFunction() {
  var carName = "Volvo";

  // code here CAN use carName

}

Source