Include criteria in my ajax call (conditional statements)

Is there a way to add conditions to my ajax request? Whenever I include the code below, it only seems to work for one item at a time.

$.ajax({
  type: 'GET',
  url: urlPost,
  success: function (data) {
    $.each(data, function (key, value) {
      createPostItem(value.name, value.image, value.size);
      if (value.size == 'post') {
        $('#img-size').addClass("img-post")
      } else {
        $('#img-size').addClass("img-story")
      }
    });
  }
});

Answer №1

It appears that the element being manipulated (with id img-size) is the same for every data point received from the server. This results in all data points affecting the same element, which may not be the desired outcome. It seems like you might want to manipulate a different element for each data point, although this is not explicitly stated in the question.

UPDATE (after receiving clarification):

I recommend making changes to the function createPostItem:

var urlPost = "assets/js/imgStock.json"
$.ajax({
    type: 'GET',
    url: urlPost,
    success: function (data) {
        $.each(data, function (key, value) {
            createPostItem(value.name, value.image, value.madeFor, value.size);
        });
    }
});

function createPostItem(name, image, madeFor, size) {
    var width, height;

    if (size == 'story') {
        height = '472px';
        width = '270px';
    }
    else {
        height = '270px';
        width = '270px';
    }

    var html = '<div class="imgStock w-full border-4 my-auto border-blue-500 lg:mx-2 mt-4 mx-auto">' +
        '<div class="flex post text-gray-200 animate__animated animate__fadeIn">' +
        '<div class="img-size mx-auto relative transition duration-300 ease-in transform hover:-translate-y-2" style="width: ' + width + '; height: ' + height + ';">' +
        '<img class="rounded shadow-2xl" src="' + image + '" alt="' + name + '"' +
        '<div class="btn-i absolute ">' +
        '<div class="btn-i absolute text-center pt-2 animate__animated animate__fadeInLeft pl-2">' + name + '</div>' +
        '<span class="flex absolute font-semibold tracking-wide justify-center absolute-pill px-1 text-xxs bg-yellow-400 text-gray-900 rounded-full text-xs">' + madeFor + '</span>' +
        '</div>' +
        '</div>' +
        '</div>' +
        '</div>';

    $(".images-array").append(html);
}

Answer №2

(Utilizing Tailwind CSS)

Executing my AJAX request:

var urlPost = "assets/js/imgStock.json"
$.ajax({
type: 'GET',
url: urlPost,
success: function (data) {
    $.each(data, function (key, value) {
        createPostItem(value.name, value.image, value.madeFor, value.size);
        if(value.size == 'story'){
            $('.img-size').css("height", "472")
            $('.img-size').css("height", "270")

        } else {
            $('.img-size').css("height", "270px")

            $('.img-size').css("width", "270px")

        }
        // $('#'+value.size).addClass("img-post")
    });
}

});

Function to generate HTML elements:

function createPostItem(name,image, madeFor, size) {
var html = '<div class="imgStock w-full border-4 my-auto border-blue-500 lg:mx-2 mt-4 mx-auto">' +
    '<div class="flex post text-gray-200 animate__animated animate__fadeIn">' +
    '<div class="img-size mx-auto relative transition duration-300 ease-in transform hover:-translate-y-2">' +
    '<img class="rounded shadow-2xl" src="' + image + '" alt="' + name + '"' +
    '<div class="btn-i absolute ">' +
    '<div class="btn-i absolute text-center pt-2 animate__animated animate__fadeInLeft pl-2">' + name + '</div>' +
    '<span class="flex absolute font-semibold tracking-wide justify-center absolute-pill px-1 text-xxs bg-yellow-400 text-gray-900 rounded-full text-xs">' + madeFor + '</span>' +
    '</div>' +
    '</div>' +
    '</div>' +
    '</div>';

$(".images-array").append(html);

}

Document JSON:

[
  {
    "name": "Calendrier Sofiane Boufal",
    "image": "img/Boufal_Story.jpg",
    "size": "story",
    "madeFor": "Asala Finances"
  },
  {
    "name": "Cover fictive rap",
    "image": "img/Roshi_Cover.jpg",
    "size": "post",
    "madeFor": "Captain Roshi"
  },
  {
    "name": "Calendrier Jean-Pierre Nsame",
    "image": "img/mars_nsame.jpg",
    "size":  "story",
    "madeFor": "Asala Finances"
  },
  {
    "name": "Anniveraire Houboulang Mendes",
    "image": "img/Mendes-Birthday.jpg",
    "size":  "story",
    "madeFor": "Asala Finances"
  }
]

I have adjusted my conditions (if, else) to apply the CSS classes accordingly. Although I encountered issues with identical IDs for multiple images, I am still troubleshooting.

Displayed result: (Images with value.size == "story" are the larger ones - namely: Calendrier Southampton, Calendrier Young Boys, and Happy Birthday)

View image description here

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

Selenium Python Slider Button Element Visibility Issue

Currently, I am developing a parser to automate the process of clicking buttons on a website. However, I am encountering difficulties in clicking two specific buttons. The buttons I am aiming to click are "Elija el imports a financiar" and "Elija la mensu ...

What could possibly be the reason for this not returning null?

Consider this JavaScript snippet: var value = parseInt(""); console.log(value != Number.NaN ? value : null); Why does the console output Nan instead of null? Is there a way to modify the code so that it actually returns a null value? I attempted to wra ...

Phonegap on iOS Simulator experiencing issues with executing cross-domain ajax requests

As I embark on my journey with Phonegap and mobile development, I am encountering a roadblock when trying to make a call to $.ajax(...) from the iOS simulator or an iOS device. Surprisingly, everything works perfectly when running the app from a browser or ...

Angular popup window can't access DOM elements

Hey there, currently experimenting with an angular modal instance and running into a bit of a hurdle. When attempting to declare a querySelector in the modal controller, I'm encountering a console error stating 'Cannot read property 'queryS ...

Unable to navigate through bootstrap dropdown items using keyboard shortcuts

I am currently working on a bootstrap dropdown menu that is filled with time zone details. Everything seems to be in order as the dropdown gets populated correctly. However, when I click on it and try to select an item by pressing a key on the keyboard (fo ...

Avoid consistently updating information

I am experiencing a strange issue in my project. I have 2 tabs, and in one tab, there are checkboxes and a submit button. The user selects items from the checkboxes, and upon clicking the button, they should see their selections in the other tab. This fu ...

Struggling to set the value for a variable within an Angular factory?

When dealing with a variable as an array, I have no trouble pushing objects inside and retrieving the values within the controller. However, when trying to directly assign an object to that variable, I run into issues. If anyone can assist me in achieving ...

Loading dynamic images in HTML using Javascript and Django templates

Attempting to load a specific image using javascript within a django template has presented challenges due to the formatting of django tags. The standard django static asset source in an img tag looks like this: {% load static %} <img src="{% static & ...

Is it possible to display a combination of images and text data using JQUERY/AJAX, when the data is sent as objects or arrays?

I'm struggling to figure out how to handle an object or array sent from a server that contains binary picture and text data using JQUERY/AJAX Here is the server-side setup: const url= require('url'), express = require('express&ap ...

Aborting ASP.net page's SQL query

For the past week, I've been working on solving a problem that involves creating 2 buttons - "Execute" and "Cancel". Clicking "Execute" triggers a lengthy SQL query, while clicking "Cancel" should stop the query. The issue arises when two ajax queries ...

Unable to scroll following an ajax request

I am encountering an issue where I need to make an ajax call that populates a DIV and the content becomes as long as 2 web pages. However, I am unable to scroll unless I resize the window. How can I instruct the browser to recalculate the page content size ...

Using a pool.query with async/await in a for-of loop for PostgreSQL

While browsing another online forum thread, I came across a discussion on using async/await with loops. I attempted to implement something similar in my code but am facing difficulties in identifying the error. The array stored in the groups variable is f ...

What is causing this issue with the ajax call not functioning correctly?

$(document).ready(function(){ $('.clickthetext').click(function(){ $.post("submit.php", $("#formbox").serialize(), function(response) { $('#content').html(response); }); return false; }); ...

Display HTML code within a data attribute

I have a function that modifies an element from OpenLayers. In the official documentation, it mentions that the property label accepts either HTML or a string. methods: { onUpdatePosition (coordinate) { this.deviceCoordinate = coordinat ...

Regular expression patterns for authenticating and verifying passwords

Currently, I am working on a JavaScript program to validate passwords using regex. Here are the requirements: The password must consist of at least seven characters. It should include at least one of the following: an uppercase letter (A-Z) a lowercas ...

The art of sketching precise lines encircling a circular shape through the

What is the best way to use a for loop in JavaScript to draw lines around a circle, similar to those on a clock face? ...

What is the best way to maintain the index of a for loop when incorporating AJAX to insert PHP data into an object?

Hey there, I'm diving into the world of AJAX and PHP implementation. I've hit a bit of a roadblock lately as I feel like I might be missing a simple solution. Currently, my code fetches data from a trove API using PHP, and for each item it appen ...

Is there a way for me to convert this JSON object back into a string?

Presently, I possess this specific JSON object "name": "Luke Skywalker", "height": "172", "mass": "77", "hair_color": "blond", "skin_color": "fair", "eye_color": "blue", "birth_year": "19BBY", "homeworld": "Tatooine", "films": [ "A N ...

Defining the signature of an unnamed function in TypeScript

Within my Express code, I have an anonymous function set up like this: app.use((err, req, res, next) => { // ... }); I am looking to specify the type of the function as ErrorRequestHandler (not the return type). One way to achieve this is by defining ...

Closures are like the "use" keyword in PHP or the capture list in C++, but they play a similar role in JavaScript and other transpiler languages

PHP has a useful feature with the use keyword, which allows for the usage of 'external' variables in closures. For example: $tax = 10; $totalPrice = function ($quantity, $price) use ($tax){ //mandatory 'use' return ($price * $quan ...