0

I am creating a WordPress website that utilises a search bar. The user's search would search through an array saved in a separate file (called allcompanies.php) but I keep getting a 404 error saying the allcompanies.php can't be found.

I have used the example from here: https://www.w3schools.com/php/php_ajax_php.asp

Both header.php and allcompanies.php files are stored in the /public_html/wp-content/twentytwentyone folder so how do I reference the allcompanies.php file from the header.php (or from the functions.php) file

<input type="text" id="fname" name="fname" onkeyup="showHint(this.value)">

<script> 
    
    function showHint(str) {
      if (str.length == 0) {
        document.getElementById("txtHint").innerHTML = ""; 
        return;
      } else {
        const xmlhttp = new XMLHttpRequest();
        xmlhttp.onload = function() {
            document.getElementById("txtHint").innerHTML = this.responseText;
        }
      xmlhttp.open("GET", "allcompanies.php?q=" + str);
      xmlhttp.send();
      }
        
    }
    
    
</script>
6ix
  • 1
  • Look at your browser's Network tool while you're running this, and see if the AJAX request is being sent to the exact URL you expected – ADyson May 16 '23 at 12:18
  • It doesn't matter where is header.php, what matters is where is the file that does the `include` or `require` that loads it ([see here](https://stackoverflow.com/questions/1954750/php-with-require-once-include-require-the-path-is-relative-to-what#1954761)). You can use PHP's `getcwd()` to check "where you are". You can try to inject the good path with PHP like this `"=__DIR__?>/allcompanies.php?q="` (path relative to included file) or better in a WP context `"=get_template_directory()?>/allcompanies.php?q="` as your file is in the template folder. Both should work – Kaddath May 16 '23 at 12:40
  • 1
    You should rather not be making requests to "custom files" you just dropped into some folder, in the first place. There is a _proper_ way to handle AJAX in WordPress: https://codex.wordpress.org/AJAX_in_Plugins – CBroe May 16 '23 at 12:54
  • 1
    _"so how do I reference the allcompanies.php file from the header.php (or from the functions.php) file"_ - you don't want to refer it "from" either of those places; you are trying to access it via HTTP from the client side. The `/public_html/` directory is most likely what your web root is set to here, so the path you should be using on the client side is `/wp-content/twentytwentyone/allcompanies.php` - with the leading slash it will always refer to the domain root, no matter what the "path depth" of the actual HTML document this runs in, is. – CBroe May 16 '23 at 12:56

0 Answers0