Tips for transferring a dynamic ID from AJAX data to a modal

How can I pass a dynamic ID obtained from an ajax POST request to a bootstrap modal?

var id = $(this).data('id');

$.ajax({
    type: 'POST',
    url: "{{ url('/pos/createSubCategory') }}",
    data: {id: id},
    success: function (data) {

    var html = '';

    if(!$.trim(data))
    {
        html = '<div>' + '<h3>' + 'Empty!' + '</h3>' +'</div>';
    }
    else
    {
         $.each(data, function () {            
         html += '<div class="card subCategoryClass" data-target="#subcategory_product_modal" data-toggle="modal" aria-hidden="true" data-dismiss="modal" data-id="@this.id">' + '<p>' + '<button>' + this.name + '</button>' + '</p>' +'</div>';

         });
     }

    },
    error: function (data) {
    console.log(data);
    }
});

Why is data-id="@this.id" not working as expected?

Answer №1

Here is the solution that you should implement:

To handle its variability, you must parse it using the + operator.

var data = [{id: "1",name :"michael"},{id: "2",name :"Alice"}]

var content = "";
$.each(data, function () {            
     content += '<div class="card subCategoryClass" data-target="#subcategory_product_modal" data-toggle="modal" aria-hidden="true" data-dismiss="modal" data-id="'+this.id+'">' + '<p>' + '<button>' + this.name + '</button>' + '</p>' +'</div>';

     });
         
console.log(content);
$("#output").append(content)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<div id="output"></div>

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

Utilizing AJAX to determine if a specific phrase includes the queried terms

Currently, I am working on an AJAX search bar. At the moment, it only allows me to search for exact words in my table. ID|Skillset|Description| 1|game|i love game 2|photography|i love to take photo 3|game|game is my forte My current query searches for ex ...

It is imperative that the HTML div element remains within the boundaries of the page

Let me begin by providing some context. I am currently developing a responsive page that uses percentages to position my divs, allowing users to drag and drop items wherever they please. However, a problem arises when the user positions an object too close ...

Form using Ajax technology, including two drop-down menus sourced externally

Is there a way to automatically populate a second drop-down list with all models once a selection is made in the first drop-down on a form? Below is the code snippet: <form> <div class="landing_quote_left"> ...

use angular to dynamically add attributes to html components

When I need to insert attributes into a component that I plan to reuse, I receive different attributes as strings. For example, if I want to add an element in my component: <input type="text" maxlength="10" placeholder="enter your name"/> I will re ...

Struggling to get the Ant design button to launch an external link in a new tab using React and NextJS

I have an Ant button set up like this: <Button style={{ borderRadius: '0.5rem' }} type="default" target="_blank" ...

Optimizing rest service calls with $resource

I am currently learning about the $resource to utilize RESTful Web Services. For my first attempt, I created a factory like this : 'use strict'; angular.module('BalrogApp').factory('Req', ['$resource', function($r ...

What is the best way to sort and organize JSON data?

Upon successful ajax call, I receive JSON data structured like this: var videolist = [ { "video_id": 0, "video_name": "Guerrero Beard", "timelength": 15 }, { "video_id": 1, "video_name": "Hallie Key", "timelength": 8 }, { ...

Is it possible to manage asynchronous data using MySQL and PHP?

I have a code that displays the number of data entries in a database. I am looking for a way to send this information to the browser in real-time or within a few seconds using ajax or another method... This is my current code: $db = mysql_connect($db_hos ...

AngularJS remove a row from a table disrupts the formatting

Hello! I am attempting to delete rows from a table in Angular. I want the first two rows to have a red background and the rest to have a white background. If I try to delete the last row, it gets deleted but the color remains for the first row only (it sh ...

Learn how to showcase video information in a vue.js template

I am having difficulty displaying a saved media (video) file on another page after collecting it using the ckeditor5 media option. The data is stored along with HTML tags generated by ckeditor, so I'm using v-html to display other content like <p&g ...

How to retrieve a subobject using AngularJS

From my perspective : <span data-ng-init="fillEditForm['titi']='toto'" ></span> In my Angular controller : console.log($scope.fillEditForm); console.log($scope.fillEditForm['titi']); The outcome : Object { ti ...

Mobile devices do not support HTML5 Video playback

Here is the HTML5 Video code I am using: <div id="lightBox1" class="lightBox"> <video id="video" controls preload="metadata"> <source width="100%" height="470" src="/ImageworkzAsia/video/iworkzvid.mp4" type="video/mp4"> ...

Issue: The module 'xdl' cannot be located while executing the command "npm start" in React Native

Recently, I delved into learning React Native through an online Udemy course. Everything was going smoothly until a few days back when I encountered an error message after running the simple "npm start" command. Despite trying various solutions like reinst ...

ThreeJS: Is CSG the missing wrapper?

I have been utilizing ThreeCSG.js independently to generate various shapes, but I am encountering errors when attempting to create certain shapes: Maximum call stack exceeded. It appears that the repository is not being updated, so I experimented with the ...

Obtaining an array from within an object in Angular 2 using Typescript

Upon performing a console.log of the following: console.log(this.categories); The resulting structure is displayed below: https://i.sstatic.net/8Wt65.jpg This structure was generated from the JSON retrieved from the API: [ { "id":"dff0bb3e-889f-43 ...

Display PDF blob in browser using an aesthetically pleasing URL in JavaScript

Using Node, I am retrieving a PDF from the server and sending it to my React frontend. My goal is to display the PDF in the browser within a new tab. The functionality works well, but the URL of the new tab containing the PDF is not ideal. Currently, the U ...

What is the proper way to define the routes for an ajax button_to?

I have successfully integrated an ajax-powered button to manage adding and removing a calendar event from a user's "wish list". The button performs as a toggle-switch, allowing users to add events if they are not already on the wish list, and remove t ...

Maintain original pitch of HTML video content (preservesPitch, mozPreservesPitch, webkitPreservesPitch)

I am attempting to turn off the preservesPitch feature on a video element that is playing in slow motion by adjusting the video's playbackRate. In Chrome, video.webkitPreservesPitch is not defined, and changing it to false or true doesn't affect ...

Encountering an unexpected token error while attempting to incorporate JQuery into a React JS project

I am currently diving into the world of React.js and attempting to incorporate a side navigation bar on my homepage. However, I encountered an eslint error when trying to implement the sidebar using jQuery code. Below you will find the code snippet for the ...

Oops! Looks like there's a problem with the helper called "if_equal" in Handlebars

I attempted to incorporate handlebars into my express node application, but it appears to be malfunctioning. const express = require('express'); const hbs = require('hbs'); const expressHbs = require('express-handlebars'); c ...