-1

This involves PHP, AJAX, JQuery. Hopefully this is an easy question.

I have a dynamic dropdown menu that displays content when the dropdown is selected. The content i am trying to display is an image. I am using two tables - One is my table for teams, and the other table is for my logos.

team

|id|name |
|--| --- |
|1 | MTL |
|2 | BOS |
|3 | CGY |
|4 | EDM |

gallery

|id|name      |**filename**  |
|--| ---      |              |
|1 | Montreal |habs-svg.svg  |
|2 | Boston   |bruins-svg.svg|
|3 | Calgary  |flames-svg.svg|
|4 | Edmonton |oilers-svg.svg|

It works perfectly. When I select MTL in dropdown menu from 'team' for example, it will display the corresponding file name in text format which is 'habs-svg.svg'. So all my Jquery and AJAX is working great.

How can i get the actual image to display instead of the image name? Please see code below for my index.php, getJS.js & getlogo.php:

**index.php**
<div class="container">
    <h2>Drop-down Selection Data Load with ajax, PHP & MySQL</h2>       
    <div class="page-header">
        <h3>
            <select id="employee" class="form-control" >
                <option value="" selected="selected">Select Employee Name</option>
                <?php
                $sql = "SELECT id, name FROM team";
                $resultset = mysqli_query($conn, $sql);
                while( $rows = mysqli_fetch_assoc($resultset) ) { 
                ?>
                <option value="<?php echo $rows["id"]; ?>"><?php echo $rows["name"]; ?></option><?php } ?>
            </select>
        </h3>   
    </div>  
    <div class="hidden" id="errorMassage"></div>
    <table class="table table-striped hidden" id="recordListing">
        <thead>
          <tr>
            <th>Team Name</th>
            <th>Logo</th>
          </tr>
        </thead>
        <tbody>
          <tr> //My images that are dynamically printing will show here 
            <td id="empName"></td>
            <td id="empFileName"></td>
          </tr>
        </tbody>            
    </table>       
</div>

**getJS.js**
$(document).ready(function () {
  $("#employee").change(function () {
    var id = $(this).find(":selected").val();
    var dataString = "empid=" + id;
    $.ajax({
      url: "getlogo.php",
      dataType: "json",
      data: dataString,
      cache: false,
      success: function (empData) {
        if (empData) {
          $("#errorMassage").addClass("hidden").text("");
          $("#recordListing").removeClass("hidden");
          $("#empId").text(empData.id);
          $("#empName").text(empData.name);
          $("#empFileName").text(empData.filename);
        } else {
          $("#recordListing").addClass("hidden");
          $("#errorMassage").removeClass("hidden").text("No record found!");
        }
      },
    });
  });
});

**getlogo.php**
<?php
include_once("db_connect.php");
if($_REQUEST['empid']) {
    $sql = "SELECT name, filename 
    FROM gallery 
    WHERE id='".$_REQUEST['empid']."'";
    $resultSet = mysqli_query($conn, $sql); 
    $empData = array();
    while( $emp = mysqli_fetch_assoc($resultSet) ) {
        $empData = $emp;
    }
    echo json_encode($empData);
} else {
    echo 0; 
}
?>

I know how to insert images using PHP, but I feel it has something to do with my AJAX specifically on this line:

$("#empFileName").text(empData.filename);

So far it seems as if I need to use 'attr' instead of 'text'? I tried this below but did not seem to work:

$("#empFileName").attr("filename", empData.filename);

Thank you in advance!

ADyson
  • 57,178
  • 14
  • 51
  • 63
JahIsGucci
  • 17
  • 5
  • 2
    **Warning:** Your code is vulnerable to SQL Injection attacks. You should use parameterised queries and prepared statements to help prevent attackers from compromising your database by using malicious input values. http://bobby-tables.com gives an explanation of the risks, as well as some examples of how to write your queries safely using PHP / mysqli. **Never** insert unparameterised data directly into your SQL. The way your code is written now, someone could easily steal, incorrectly change, or even delete your data. – ADyson Mar 31 '23 at 20:43
  • https://phpdelusions.net/mysqli also contains good examples of writing safe SQL using mysqli. See also the [mysqli documentation](https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php) and this: [How can I prevent SQL injection in PHP?](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) . Parameterising your queries will also greatly reduce the risk of accidental syntax errors as a result of un-escaped or incorrectly quoted input values. If you learnt your current technique from a tutorial or book, please don't use that resource again. – ADyson Mar 31 '23 at 20:43
  • `I am using two tables - One is my table for teams, and the other table is for my logos`...since there appears to be a 1 <-> 1 relationship between team and logo, there is no need for two tables really. The name and filename can just be columns in the teams table. – ADyson Mar 31 '23 at 20:46

1 Answers1

0

You display an image in a HTML document using an <img tag with the URL of the image file as its src. So

$("#empFileName").html('<img src="' + empData.filename + '" />');

should put the image inside the table cell you wanted (assuming the image file is stored in the same folder on the website as the page you're loading it into).

Documentation: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img

ADyson
  • 57,178
  • 14
  • 51
  • 63
  • This goes into my ajax file correct? I did try that and it seems to be half-working because it is now displaying a broken image file. Not sure what i'm doing wrong. – JahIsGucci Mar 31 '23 at 21:03
  • Yes it goes into replace the exact line you identified. As for what might be wrong...note the assumption I spoke about in my answer... :-) – ADyson Mar 31 '23 at 21:05
  • To investigate this further, you can open your browser's Network tool while you're running this code. As soon as the img tag is added to the DOM you should see a HTTP request go out to load the image. Check what URL it points to, and check what status code the request returns. You may need to adjust the URL so it finds the images in the right folder relative to your web page. – ADyson Mar 31 '23 at 21:06
  • hey thanks for the help i really appreciate it. I am a back end noobie so i'm still learning. First time learning about the DOM errors. I do in fact see it popping up as an error. I think it has to do with the URL as you say, but the URL on network tab looks fine to me: http://localhost/employee/empData.filename, Status Code: 404 not found Your other link you shared said the URL should not be the same as current URL, but what other URL is there to use? – JahIsGucci Mar 31 '23 at 21:16
  • Sorry that is my mistake, I forgot to make the empData.filename back into a variable properly. As you can see it's used the variable name as a literal string, instead of its value. See the edited answer, I should have concatenated it properly. Serves me right for typing too quickly. – ADyson Mar 31 '23 at 21:18
  • 1
    SORRY i am a fool! I forgot to move the images over to my folder......air head mistake! ADyson - i cannot thank you enough for taking the time to help out a noob. It is working now :) Thank you SO SO MUCH and hope you have a great weekend – JahIsGucci Mar 31 '23 at 21:38
  • No worries, you too – ADyson Mar 31 '23 at 21:40