Fetch image from database using Ajax when image name is clicked in CodeIgniter

I am currently working on creating a gallery using CodeIgniter. I have successfully retrieved a list of image names from the database and displayed them on the view page. Now, I would like to implement a feature where users can click on an image name and retrieve the corresponding image through AJAX. Since I am not very experienced with coding, I need assistance with the fetch gallery function. Any help would be greatly appreciated. Thank you in advance. Below is the code snippet for fetching image names:

          <?php
                      //$i=1;
                      foreach($data as $row)
                      {
                        ?>
                        <img class="img-circle img-bordered-sm" src='<?php echo base_url();?>assets/uploads/<?php echo $row->imagefiles;?>' height='30px' width='30px'>
                        <span class="username">
                            <a id="view_gallery" class="view_gallery" href="javascript:void(0);" id="<?php echo $row->id;?>"><?php echo $row->name; ?></a>
                        </span>
                        <hr>
                      <?php }
                    ?>

And here is the script that requires further code assistance :

    <script type="text/javascript">
    $( ".view_gallery" ).click(function() {

        id = $(this).attr('id');
    /*    alert(userid);*/
           $.ajax({
                url     : '<?php  echo base_url('fetch_gallery_data') ;?>',
                method  : 'post',
                data    : {id : id},
                success : function(res){
                  $('.disp_gallery').html(res);
                }
              })

    });
    </script>

Displayed below is the fetch gallery function within the controller:

  public function fetch_gallery_data()
    {
        $id = $this->input->post('id');
        $where = $id;
        $result = $this->App_model->gallery_model('gallery','id',$where);
        $data = '';
        if(count($result) > 0)
        {
            foreach ($result as $key => $value) 
            {
                $files = json_decode($value->imagefile);
                if($value->id > 0)
                {
                    $data .= "<div class='col-md-3' style='border:1px solid gray; margin:20px; padding:20px; ' id='".$id."''>";
                    $data .= "<a >";
                    $data .= "<img src='".base_url()."assets\uploads/seo-business-quotes-6.jpg' height='150' width='150'><br>";

                    $data .= "</div>";
                }
                else
                {
                    foreach ($files as $key => $value) 
                    {
                        $data .= "<div class='col-md-3' style='border:1px solid gray; margin:20px; padding:20px; '>";
                        $data .= "<img src=".base_url()."assets\uploads/".$value." height='150' width='150'><br>";
                        $data .= "</div>";
                    }
                }
            }
        }
        else
        {
            $data .= 'No Records.';
        }
        echo $data;

    }

Answer №1

Modify the forward slashes as mentioned in the controller and then test it out

$data .= "<img src='".base_url()."assets/uploads/seo-business-quotes-6.jpg' height='150' width='150'><br>";

Also, remember to change the slash and single quotes here too

$data .= "<img src='".base_url()."assets/uploads/".$value."' height='150' width='150'><br>";

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Finding the minimum value in a list and the maximum value in JavaScript

My current JavaScript list consists of dollar coin values: let x = [1.0, 2.5, 5.0, 20.0, 50.0, 100.0, 500.0, 2000.0, 5000.0] My challenge is finding an equation in JavaScript that will allow me to use the smallest number of coins to reach the desired max ...

Creating a canvas element within an iframe: A step-by-step guide

I have a unique situation where I have an iframe containing a DIV element named "pageContainer1". My goal is to insert a canvas element into that specific DIV and then be able to access it in order to draw something on it. Despite my attempts so far, this ...

A regular expression in Javascript that can be used to identify at least one word starting with a number among multiple words, with a

Currently, I am utilizing JavaScript Regex to validate an input field based on specific conditions: The value must consist of only alphabets and numbers There should be a minimum of two words (more than two are allowed) Only one word can start with a num ...

Struggling with Django relationships?

I am facing an issue with the data in my models and template. Here is an example of what I have: class Companies(models.Model): ComName = models.CharField(max_length=255) ComURL = models.CharField(max_length=1024,null=True) class Products(mod ...

Commitments shatter amidst constructing a website

Utilizing promise and http.get to retrieve data from a JSON API in Wordpress. Once the data is retrieved, it should be displayed on a page... However, an error occurs when attempting to build the page due to the data not being available. What steps can ...

Altering the "src" property of the <script> tag

Can the "src" attribute of a current <script> element be altered using Jquery.attr()? I believed it would be an easy method to enable JSONP functionality, however, I am encountering difficulties in making it operate effectively. ...

Organize your file dependencies efficiently using NPM

I'm currently part of a medium-sized team working on a large front-end application. Up until now, we have been using requirejs and AMD modules to manage our project with approximately 500 files. However, we recently decided to transition to commonjs a ...

Is it feasible to dynamically insert and delete elements in React?

I'm currently in the process of rebuilding a project, specifically a drag and drop website builder, using React after it was originally built with a heavy reliance on jQuery. My main challenge lies in being able to dynamically add and remove elements ...

Calculating the sum of all values in the database

In my database, I have a value called task_time. I want to add this value to itself so that the total time is calculated as totalTime = task_time + task_time + ... + task_time. This is how I retrieve the data: function getEndTasks() { $http.get(& ...

Ways to retrieve the innerHTML of a Script Tag

After spending what feels like an eternity searching, I still can't figure out how to get the innerHTML of a script tag. Here's where I'm at... <script type="text/javascript" src="http://www.google.com" id="externalScript"></script ...

Node.js is indicating that the certificate has expired

When using Mikeal's request library (https://github.com/mikeal/request) to send an https request to a server, I keep encountering an authorization error of CERT_HAS_EXPIRED. request({ url: 'https://www.domain.com/api/endpoint', ...

Dominating React Components with Unique CSS Styles

Currently, I have developed a NavBar component. I've implemented some JavaScript code that changes the navbar's background color once it reaches 50px. However, I am facing an issue in applying this scroll effect to only one specific file and not ...

Utilize the provided parameter within a JavaScript function

<script type="text/javascript"> function updateTrackName(trackNum) { document.form1.track_(track_number)_name.value=document.form1.track_(track_number)_parent_work.value; } </script> To modify the line inside of the parent_wor ...

JQuery form plugin - submitting a form automatically on onchange event

As a beginner in JQuery, I am looking to utilize the JQuery form plugin for file uploads and would like to trigger the form submission as soon as a file is selected. This should occur upon the onchange event of the input tag: myfile. <html> <body ...

Issue with .submit() not submitting form after setTimeout timer runs out

How can I add a delay after a user clicks submit on a form before it actually submits? I have an image that appears when the click event is triggered, but the form never actually submits... This is the HTML form in question: <form class='loginFor ...

Ways to verify the occurrence of a successful event following the execution of a save() operation on a model

Below is the snippet of code I am using to store extra properties in a model (specifically, the answer model) selectMedia: => # Post media to server @options.answer.id = @options.answer.get('_id') @options.answer.url = "/v1/answers/#{@o ...

What steps can be taken to stop the page from refreshing and losing its state when cancelling navigation using the back and forward browser buttons in React-router v4.3?

I'm currently facing an issue with a page in which user inputs are saved using a react context object. The problem arises when a user navigates away from the page without saving their entries. I want to prompt the user to either continue or cancel, wh ...

Determine the y-coordinate of terrain in Three.js

I have acquired a Collada model of terrain and now wish to incorporate other models onto this terrain. To achieve this, I believe I need to retrieve the height coordinate (y) of the terrain based on specific x and z coordinates. Can someone please guide ...

How about this: "Unveil the beauty of dynamically loaded

var request = new Request({ method: 'get', url: 'onlinestatusoutput.html.php', onComplete:function(response) { $('ajax-content').get('tween', {property: 'opacity', duration: 'long&apos ...

User-generated JSON Object with Date Information

I have created an API using Node.js/Express that receives input from a form including a date option in the request body. Currently, I am sending dates in the format YYYY-mm-dd, and I have also attempted using dd/mm/YYYY. However, when testing in Postman, ...