-1

I am trying to display an image on a webpage that I retrieved from the database using PHP and JavaScript in JSON format. I have tried looking for related questions with answers but I can't seem to comprehend anything. Please can someone help me in checking this out and provide some solution?

JavaScript/AJAX code

    function load_data(query = '', page_number = 1)
{
    var form_data = new FormData();

    form_data.append('query', query);

    form_data.append('page', page_number);

    var ajax_request = new XMLHttpRequest();

    ajax_request.open('POST', 'process_data.php');

    ajax_request.send(form_data);

    ajax_request.onreadystatechange = function()
    {
        if(ajax_request.readyState == 4 && ajax_request.status == 200)
        {
           

            var response = JSON.parse(ajax_request.responseText);

            var html = '';

            var serial_no = 1;

            if(response.data.length > 0)
            {
                for(var count = 0; count < response.data.length; count++)
                {
                    html += '<tr>';
                    html += '<td>'+"<img src='"+filename+"'>"+'</td>';
                    html += '<td>'+response.data[count].tag+'</td>';
                    html += '</tr>';
                    serial_no++;
                }
            }
            else
            {
                html += '<tr><td colspan="3" class="text-center">No Data Found</td></tr>';
            }

            document.getElementById('post_data').innerHTML = html;

            document.getElementById('total_data').innerHTML = response.total_data;

            document.getElementById('pagination_link').innerHTML = response.pagination;

        }

    }
}

    

Thats the javascript file that I am using to pass data to html page

I get this error when running it:

The requested URL was not found on this server

Here is the PROCESS_DATA.PHP file

if(isset($_POST["query"]))
{

    $a=1;
    $data = array();

    $limit = 5;

    $page = 1;

    if($_POST["page"] > 1)
    {
        $start = (($_POST["page"] - 1) * $limit);

        $page = $_POST["page"];
    }
    else
    {
        $start = 0;
    }

    if($_POST["query"] != '')
    {

        $condition = preg_replace('/[^A-Za-z0-9\- ]/', '', $_POST["query"]);

        $condition = trim($condition);

        $condition = str_replace(" ", "%", $condition);

        $sample_data = array(
            ':tag'          =>  '%' . $condition . '%',
        );

        $query = " SELECT filename, tag FROM tags WHERE tag LIKE :tag ";

        $filter_query = $query . ' LIMIT ' . $start . ', ' . $limit . '';

        $statement = $conn->prepare($query);

        $statement->execute($sample_data);

        $total_data = $statement->rowCount();

        $statement = $conn->prepare($filter_query);

        $statement->execute($sample_data);

        $result = $statement->fetchAll();

        $replace_array_1 = explode('%', $condition);

        foreach($replace_array_1 as $row_data)
        {
            $replace_array_2[] = '<span style="background-color:#'.rand(100000, 999999).'; color:#fff">'.$row_data.'</span>';
        }

        foreach($result as $row)
        {
            $data[] = array(
                'image'     =>  str_ireplace($replace_array_1, $replace_array_2, $row["filename"]),
                'tag'   =>  str_ireplace($replace_array_1, $replace_array_2, $row["tag"])
            );
        }

    }
    else
    {

        $query = "SELECT filename, tag FROM tags";

        $filter_query = $query . ' LIMIT ' . $start . ', ' . $limit . '';

        $statement = $conn->prepare($query);

        $statement->execute();

        $total_data = $statement->rowCount();

        $statement = $conn->prepare($filter_query);

        $statement->execute();

        $result = $statement->fetchAll();

        foreach($result as $row)
        {
            $data[] = array(
                'image'         =>  $row['filename'],
                'tag'       =>  $row['tag']
            );
        }

    }

    $pagination_html = '
    <div align="center">
        <ul class="pagination">
    ';

    $total_links = ceil($total_data/$limit);

    $previous_link = '';

    $next_link = '';

    $page_link = '';

    if($total_links > 4)
    {
        if($page < 5)
        {
            for($count = 1; $count <= 5; $count++)
            {
                $page_array[] = $count;
            }
            $page_array[] = '...';
            $page_array[] = $total_links;
        }
        else
        {
            $end_limit = $total_links - 5;

            if($page > $end_limit)
            {
                $page_array[] = 1;

                $page_array[] = '...';

                for($count = $end_limit; $count <= $total_links; $count++)
                {
                    $page_array[] = $count;
                }
            }
            else
            {
                $page_array[] = 1;

                $page_array[] = '...';

                for($count = $page - 1; $count <= $page + 1; $count++)
                {
                    $page_array[] = $count;
                }

                $page_array[] = '...';

                $page_array[] = $total_links;
            }
        }
    }
    else
    {
        for($count = 1; $count <= $total_links; $count++)
        {
            $page_array[] = $count;
        }
    }

    for($count = 0; $count < count($page_array); $count++)
    {
        if($page == $page_array[$count])
        {
            $page_link .= '
            <li class="page-item active">
                <a class="page-link" href="#">'.$page_array[$count].' <span class="sr-only">(current)</span></a>
            </li>
            ';

            $previous_id = $page_array[$count] - 1;

            if($previous_id > 0)
            {
                $previous_link = '<li class="page-item"><a class="page-link" href="javascript:load_data(`'.$_POST["query"].'`, '.$previous_id.')">Previous</a></li>';
            }
            else
            {
                $previous_link = '
                <li class="page-item disabled">
                    <a class="page-link" href="#">Previous</a>
                </li>
                ';
            }

            $next_id = $page_array[$count] + 1;

            if($next_id >= $total_links)
            {
                $next_link = '
                <li class="page-item disabled">
                    <a class="page-link" href="#">Next</a>
                </li>
                ';
            }
            else
            {
                $next_link = '
                <li class="page-item"><a class="page-link" href="javascript:load_data(`'.$_POST["query"].'`, '.$next_id.')">Next</a></li>
                ';
            }

        }
        else
        {
            if($page_array[$count] == '...')
            {
                $page_link .= '
                <li class="page-item disabled">
                    <a class="page-link" href="#">...</a>
                </li>
                ';
            }
            else
            {
                $page_link .= '
                <li class="page-item">
                    <a class="page-link" href="javascript:load_data(`'.$_POST["query"].'`, '.$page_array[$count].')">'.$page_array[$count].'</a>
                </li>
                ';
            }
        }
    }

    $pagination_html .= $previous_link . $page_link . $next_link;


    $pagination_html .= '
        </ul>
    </div>
    ';

    $output = array(
        'data'              =>  $data,
        'pagination'        =>  $pagination_html,
        'total_data'        =>  $total_data
    );
    echo json_encode($output);

    }
David Thomas
  • 249,100
  • 51
  • 377
  • 410
  • The error you see is because filename is undefined. We don't know what it should be because we can't see the response you're getting from process_data.php. You'll need to dig in to the response and figure out what is the property that contains the filename or image data. – James Apr 19 '23 at 19:43
  • do you mean we should write full filename or just the database table column? – Juma Ijesun Apr 19 '23 at 19:50
  • There's no way to answer that without seeing what process_data.php returns. – James Apr 19 '23 at 19:56
  • @James check out the process_data.php file – Juma Ijesun Apr 19 '23 at 20:01
  • You can try `""` if the images are stored in the same folder as the html, otherwise you'll also need to add the path to the image folder as part of the src. – James Apr 19 '23 at 20:20
  • This is what I get Forbidden You don't have permission to access this resource. – Juma Ijesun Apr 19 '23 at 20:26
  • @James what else can I do to solve this?? – Juma Ijesun Apr 19 '23 at 20:35
  • 2
    It sounds like you are now processing the data returned by the php correctly. Whether the src attribute is a valid image URL is a separate matter. I can't see what data you have in your database nor do I know the structure of your website. – James Apr 19 '23 at 20:48
  • @James should I send here the Jason raw result for you to see? – Juma Ijesun Apr 19 '23 at 20:54
  • @James your answer was right. I had messed up something. Instead using filename in the process_data.php I was using image which is a column that doesnt exist in my table. I have just replaced that now and images have been passed. Thanks a lot – Juma Ijesun Apr 20 '23 at 04:20

1 Answers1

0

I'm not seeing where the "filename" variable is defined here:

html += '<td>'+"<img src='"+filename+"'>"+'</td>';

Javascript is probably evaluating this to "undefined" so the image tag ends up looking like this in HTML:

<img src='undefined'>

You need to get the data in base64-encoded format and form the <img> tag similar to this: https://www.w3docs.com/snippets/html/how-to-display-base64-images-in-html.html

So your code would look something like this:

html += '<td><img src="data:image/png;base64,' + response.data [count].imagedata + '"></td>';

Where imagedata would be the base64-encoded image data (originally in PNG format in this case). Hopefully this helps!