1

I am trying to take an array of strings from a PHP file so that I can use it within my javascript file. I was able to get access to it ($namelist) in my javascript, but whenever I try to print it, the strings in the array get printed out as separate letters, like as if each letter of each word was given its own index.

I do not want this. I want to print the entire word on a single line. In this model, there should only be two words printed out. (hakim and henry)

var letters = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
const dir = "./submissions/";
// const fs = require('fs');
var extensions = [".jpg",".png"];
    for( var i = 0; i < letters.length;i++){
      var node = document.createElement("li");
      var button = document.createElement("input");
      var textnode = document.createTextNode(letters[i]);
      button.type = "button";
      button.className = letters[i];
      button.value = letters[i];
      button.setAttribute('onclick',"thisfunction(this,'one')");
      button.appendChild(textnode);
      node.appendChild(button);
      document.getElementById('letters').appendChild(node);
    }

    function thisfunction(obj,abc){
      var letterclass = obj.className;
      $.post('php/loadnames.php',{postname:letterclass},
      function(data){
        for(const child of data){
          var node = document.createElement("li");
          var link = document.createElement("a");
          var textnode = document.createTextNode(child);
          link.href = '#';
          link.appendChild(textnode);
          node.appendChild(link);
          document.getElementById('buddy_load').appendChild(node);
        }

PHP/loadnames:

<?php
$namelist = array();
$name = $_POST['postname'];
$path = '../submissions';
$files=scandir($path);
foreach($files as &$value){
  if(strtolower(substr($value,0,1)) == strtolower($name)){
    array_push($namelist, strtolower(strtok($value,'_')));
  }
  // echo strtolower(substr($value,0,1));
}
$namelist = array_unique($namelist);
// echo count($namelist);
// $namelist = sort($namelist);
$keys = implode($namelist );
  // echo implode(',',$namelist);
  echo $keys;
?>

End Result

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
pk pulse fall
  • 88
  • 1
  • 6

1 Answers1

2

You are returning a string-type value to your ajax call. Therefore, your for loop is iterating the offsets/characters of the lone string. What I recommend is to pass flat array data to the ajax call as a json encoded string so that it can iterate each element and display the first names as separate links.

Furthermore, I have a few tips to share.

  1. You are not writing any data to your server/database (you are just fetching data), so it is more appropriate to use get instead of post. This means using $.get or $.ajax.
  2. Validate the incoming value before using it in your php. If it is invalid, return something unsatisfactory.
  3. I typically use glob() to search my filesystem. It is very versatile and has a useful feature for this task in that you can use its brace syntax to dynamically filter the search. Anyhow, scandir() is not necessarily bad for this task because you are trimming the leading substring from the filenames anyhow. (For the record, I might use a combination of glob() then iterated calls of strstr().)
  4. preg_filter() is a function that I seldom have a use for, but seems appropriate for this task. It not only attempts to mutate each value that it encounters, it also discards values which it cannot mutate (because the pattern is not satisfied).

Code: (Demo)

$files = [
    'Hakim_123.txt',
    'Mick_MacKusa.jpg',
    'henry_rollins.gif',
    'Z_zzz_zzz_zzz.csv'
];
$_GET['postname'] = 'H';

if (!preg_match('~^[A-Z]$~', $_GET['postname'] ?? '')) {
    exit('[]');
}

exit(
    json_encode(
        array_values(
            array_unique(
                preg_filter(
                    '~^' . lcfirst($_GET['postname']) . '[^_]*\K_.*~',
                    '',
                    array_map('strtolower', $files)
                )
            )
        )
    )
);

Output:

["hakim","henry"]

To use this json string in your jquery, follow the recommendations at Parse JSON from JQuery.ajax success data.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136