Building a dynamic webpage using AJAX, MVC, and web APIs to generate a div element filled

I'm currently working with a restful API, MVC, and ajax. My goal is to retrieve data from the backend and then display images within certain div elements. The expected outcome should resemble this example: https://i.stack.imgur.com/BFqWL.png

This snippet showcases my backend code:

  /*route:api/images*/
  [HttpGet]
 public IEnumerable<DTO> GetData(string Id) {
        /*Do something*/
        return Dto;/*the dto has an imgurl property*/           
    }

Here's a glimpse of my frontend implementation:

<div id="mydiv></div>

    <script>
    $(document).ready(function () {
        $.ajax({
            url: "http://localhost:59245/api/api/images",
            type: "Get",
            success: function (data) {                 
                for (var i = 0; i < data.length - 1; i++) {
                    $('<div class="col-lg-4 col-sm-6"><div class="thumbnail">'+
            '<h3 class="centrar">' + data[i].Titulo + '</h3><a href="'+
            data[i].ImagenUrl+'</a><p>'+data[i].Paragraph+'</p></div>'
            ).appendTo("#mydiv");
                }
            },
            error: function (msg) { alert(msg); }
        });
    });
</script>

My issue arises when attempting to display images within #mydiv, resulting in undesired output like this: https://i.stack.imgur.com/il5vz.png

The image shows that the anchor tag wraps around the paragraph text, which was not intended in my ajax code. How can I resolve this issue? Thank you

Answer №1

You're missing the img tag. Give this a try:

<script>
$(document).ready(function () {
    $.ajax({
        url: "http://localhost:59245/api/api/images",
        type: "Get",
        success: function (data) {                 
            for (var i = 0; i < data.length - 1; i++) {
                $('<div class="col-lg-4 col-sm-6"><div class="thumbnail">'+
        '<h3 class="center">' + data[i].Title + '</h3><a href="'+
        data[i].ImageUrl+'"><img src="'+data[i].ImageUrl+'"/></a><p>'+data[i].Description+'</p></div>'
        ).appendTo("#mydiv");
            }
        },
        error: function (msg) { alert(msg); }
    });
});

Answer №2

There appears to be a mistake here - the <a> tag is not properly closed:

$('<div class="col-lg-4 col-sm-6"><div class="thumbnail">'+
        '<h3 class="centrar">' + data[i].Titulo + '</h3><a href="'+
        data[i].ImagenUrl+'"><img src="'+
        data[i].ImagenUrl+'"></a></div>'
        ).appendTo("#mydiv");

This code snippet will display the image and turn it into a clickable link. It seems like you may need to adjust the markup to achieve the desired outcome.

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

Encountered an error: "switch/mergeAll/flatten is not a valid function" when working with the http driver

As I delve into learning CycleJS, one thing that has caught my attention is the usage of Cycle's HTTP Driver. It seems that in order to reach the stream level, merging the response stream stream with RxJS switch/mergeAll is essential. However, when at ...

attempting to refine an array of objects using another array within it

I am currently filtering a group of objects in the following manner: [ { "Username":"00d9a7f4-0f0b-448b-91fc-fa5aef314d06", "Attributes":[ { "Name":"custom:organization", "Valu ...

Using an external script to modify or call a Vue.js method

My Vue app is constructed using Webpack and includes a few basic computed properties, such as calculating the sum amount from input values. However, I now require the capability to replace the summation function with one stored in a separate file that is n ...

Tips for ensuring all images are the same size within a div element

https://i.stack.imgur.com/EkmWq.jpg Is there a way to make sure all the images fit perfectly inside their respective border boxes without appearing stretched? I've tried setting fixed height and width within a div, but they always end up looking off. ...

Utilize HTML or JavaScript to make a POST request with Express

Recently, I decided to dip my toes into the world of back-end development using express for the first time. I came across a situation where I needed to make a POST request from an html/js file, and initially used Jquery to accomplish this task. However, I ...

Safari/Webkit executing function prematurely following ajax:complete event

I am currently working on an AJAX call which is functioning properly. However, I am facing an issue regarding the dimensions of an image. Since the images are dynamically resized, I cannot declare their dimensions in HTML. When I try to fetch these dimensi ...

Issue encountered when attempting to retrieve elements within an HTA's IFrame

We are currently working on automating an Intranet site using HTA and JavaScript. To bypass the browser security settings, we have implemented an Iframe within the HTA itself instead of opening the site in a browser. Despite being able to successfully logi ...

Error: The value of "$tweetId" cannot be parsed as it is set to "undefined". Please ensure that string values are properly enclosed

I am utilizing sanity, and if you require more details, I will furnish it promptly. When I try to access http://localhost:3000/api/getComments, I encounter the following error message: ClientError: Unable to process value of "$tweetId=undefined". Kindly ...

Tips for modifying the href attribute when a user clicks

Is there a way to dynamically change the value of this link <a href="/Countries/388/10">next</a> without having to refresh the page? For example, if a user clicks on the link, it should update to <a href="/Countries/388/20">next</a&g ...

In react-native, both the parent and child components are rendered at the same time

One of my components, the parent one, goes through an array of chapters and for each item found, renders a child component called 'ExercisesList' and passes an array of exercises to it. class ExercisesScreen extends Component { displaySelected ...

Validation of forms on the client side using Angular in a Rails application

I'm facing an issue with implementing client-side validations for a devise registration form using Angular. Although I am able to add the "invalid" class to the fields as expected, I am struggling to get any output when using ng-show. There are no oth ...

Which specific html container or element can be found on the mymsn pages?

When accessing mymsn, users have the ability to personalize the content and layout of their webpage. I am curious about what type of container is being utilized for this customization - does it involve an html element, or perhaps javascript, or something e ...

Implementing character limits in VueJS fields

new Vue({ el: '#app', data() { return { terms: false, fullname:'', maxfullname: 10, mobile: '', maxmobile: 10, area: '', maxarea: 12, city: '', ...

Transform the MUI Typescript Autocomplete component to output singular values of a specific property rather than a complete object

When utilizing MUI Autocomplete, the generic value specified in onChange / value is determined by the interface of the object set in the options property. For instance, consider an autocomplete with the following setup: <Autocomplete options={top ...

Is it possible to resend an AJAX request using a hyperlink?

Is it possible to refresh only the AJAX request and update the content fetched from an external site in the code provided below? $(document).ready(function () { var mySearch = $('input#id_search').quicksearch('#content table', ...

Incorporate React into current Node express application by utilizing a content delivery network (CD

I'm currently in the process of developing a web application utilizing both Node and React. Instead of having separate Node and React applications, I decided to integrate React directly into my existing setup. To achieve this, I attempted importing th ...

Utilizing the default event object in ag-Grid's event methods with JavaScript

I am a newcomer to ag-grid and I need help with calling event.preventDefault() in the "cellEditingStopped" grid event. Unfortunately, I am struggling to pass the default JavaScript event object into it. Is there a way to make this work? Additionally, I al ...

How can I showcase array elements using checkboxes in an Ionic framework?

Having a simple issue where I am fetching data from firebase into an array list and need to display it with checkboxes. Can you assist me in this? The 'tasks' array fetched from firebase is available, just looking to show it within checkboxes. Th ...

What is the standard size for PHP files, or the suggested maximum limit?

I created a tool at where users can upload a .php file with comments and spaces, and it will compress it for a smaller file size. It functions similar to but is web-based and provides instant results. Once you click upload, you receive a prompt to downl ...

"Unlocking the secret to fetching the id of the clicked element within a Highchart context menu

Is it possible to retrieve the id of a clicked button on the highchart context menu? Alternatively, is there a way to execute the click function twice? const contextButtonArray = []; contextButtonArray.push({ { text: 'TEST BUTTON&ap ...