Tips for displaying data using AJAX with a variable

I am currently working with AJAX code:

 <script type="text/javascript">

    $(".monitor").click(function(){

        $("#list-format").html("");
        let facility_name = $(this).data('nama');
        let facility_id = $(this).data('id');
        let number = $(this).data('nomor');
        let base_url = '<?php echo base_url();?>'
        

        $.ajax({
            url     : 'get_data',
            method  : 'post',
            dataType: 'json',
            data    : {id_puskesmas:id_puskesmas},
            success : function(response){

                $.each(response, function(i, obj){
                    $("#list-format").append("<li>"+obj.format+"</li>");
                });

                $("#title-modal").html(facility_name);
                $("#exampleModalCenter").modal('show');
                $("#button-submit").html(`<a href="${base_url}dinas/view_monitor/${facility_id}" id="submit_modal" class="btn btn-primary">View Data</a>`)
                $("#button-submit2").html(`<a href="https://wa.me/${number}?text=Incomplete%20Report%20Details:%20Below%20is%20the%20List." id="submit_modal" class="btn btn-primary">Send Message</a>`)

               
            }


            
        })      

    })
</script>

When executed, the program will display the following data:

Data that has not been uploaded yet:
1. Form Lap PTM
2. Form Lap Posbindu
3. Form Lap IVA
4. Form Lap Jiwa
5. Form Lap Indera dan Gimul
6. Form Lap Diare
7. Form Lap LROA
8. Form Lap Thypoid
9. Form Lap Laporan Hiv Aids dan IMS
10. Form Laporan Hepatitis

I intend to pass this data to another function through an echo statement.

Is there a way to store this data as a variable?

 $.each(response, function(i, obj){
                    $("#list-format").append("<li>"+obj.format+"</li>");
                });

To display it using this code:

$("#button-submit2").html(`<a href="https://wa.me/${number}?text=Incomplete%20Report%20Details:%20Below%20is%20the%20List." id="submit_modal" class="btn btn-primary">Send Message</a>`)

Alternatively, can I replace the content of #button-submit2 by echoing the data?

Answer №1

<script type="text/javascript">
// A newly created element, not yet added to the DOM, is stored in this variable
var $receivedItems = $('<div></div>');
$(".monitor").click(function(){

    $("#list-format").html("");
    let clinic_name = $(this).data('nama');
    let clinic_id = $(this).data('id');
    let number = $(this).data('nomor');
    let base_url = '<?php echo base_url();?>'


    $.ajax({
        url     : 'get_data',
        method  : 'post',
        dataType: 'json',
        data    : {id_puskesmas:clinic_id},
        success : function(response){
            $.each(response, function(i, obj){
                // Instead of directly appending it to the DOM, store your list items in a hidden or unappended element within your variable
                $receivedItems.append("<li>"+obj.format+"</li>");
                $("#list-format").append("<li>"+obj.format+"</li>");
            });

            // ... other actions go here

            var buttonHtml = `<a href="https://wa.me/${number}?text=Laporan%20Yang%20Masih%20Belum%20Lengkap%20Adalah%20Sebagai%20Berikut%20Ini" id="submit_modal" class="btn btn-primary">Kirim Pesan</a>`;
            var $button2 = $(buttonHtml);

            $button2.on('click', function(e) {
                 e.preventDefault();
                // On click, you can append the list items stored in $receivedItems
                $("#list-format").append($receivedItems.children());
            });
           
            $("#button-submit2").append($button2);

        }

    })      

})
</script>

Comments have been added to explain the code. By following this approach, you can save all received items in a jQuery object and trigger the on-click event when adding them to the submit2 button.

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

What is the best way to prevent an HTML table from having columns that adjust their width dynamically based on the content in the <td>?

Is there a way to create a table with equal column sizes that do not change based on the length of the data within the table? https://i.sstatic.net/Gyt4P.png In the image provided, the data under the heading "Title" seems to shift the second column to th ...

Enhancing Element Generation and Data Association through jQuery

Currently, I am seeking a more streamlined approach to generate DOM alterations and update the object within .data(). At the moment, data is being supplied in an array of objects. I construct strings piecemeal, appending them to the table body, and affixi ...

Is it possible for a single field to validate and accept multiple types of data?

As a newcomer to Yup, I am attempting to validate a field that can be either a string following a specific regular expression or an array of such strings. Below is a functional example of validating a string that matches the regex: { field: yup.string(). ...

Preventing Internet Explorer browsers from accessing

Looking for the most efficient method to restrict access only to Chrome, Firefox, and Safari browsers on my web app. There are numerous approaches available for blocking browsers, but I want to find the best solution. Any suggestions? Appreciate any help! ...

Concealing a Div element without the use of Jquery or JavaScript

I have an Upper and Lower div in my HTML code. I am trying to display the Lower div only if the Upper div is present, otherwise hide it. Is there a way to achieve this using CSS without using Jquery or Javascript? Note: No modifications should be made t ...

The putImageData function in HTML5, CSS, and JS does not automatically resize or adjust the video/image to fit within the canvas

I am facing an issue with resizing an image and it doesn't recognize the new size even when I set it: To better explain my problem, I have created a fiddle to show what I'm trying to achieve: https://jsfiddle.net/lightblue/w7tq3yrc/7/ Despite s ...

Scroll to make the div slide in from the bottom

I'm trying to achieve a similar effect like the one shown in this website (you need to scroll down a bit to see the divs sliding in). Although I'm not very proficient in JS, I was able to create a code that makes the divs fade in from 0 opacity ...

AngularJS implemented a header authorization feature

I've been attempting to include an authorization header in my requests, but I'm facing some issues. Here is the code I am using: var config = {headers: { 'Authorization': token } }; return $http.get('http://localhost:3000/api ...

The React component fails to update upon pressing the button

Currently, I am in the process of learning React. I have successfully created a layout page and incorporated a feature to display images using a component. Each image within the component includes a button that triggers the deletion of the image from the A ...

ErrorPlacement in jQuery validation is causing an issue where errors cannot be removed even after they have been corrected

Can you assist me in resolving an issue? I am struggling with removing an error message once a user has corrected their mistake, particularly when it comes to validating an email field. The error keeps getting added multiple times until validation is succe ...

Adjusting the filter location in React-admin

This is the common method of implementing filters in react-admin https://i.stack.imgur.com/M8yq7.png However, in my particular scenario, I require the filters to be inside each column heading. For example: https://i.stack.imgur.com/GU2Pz.png The filter ...

Retrieving information from dynamically created elements with JQuery

Encountering a similar issue to finding dynamically added HTML elements with jQuery, but my goal is to access the new element's data rather than its event. The element is inserted via AJAX request using jQuery. Despite not being missing from the DOM ...

Obtaining the previous element with aria-selected using Jquery Selector rather than the current one

I am currently utilizing Semantic UI React to design a dropdown menu for selecting countries. To access the values that are passed as attributes to a <div role=option />, I use the following method: handleSelectCountry = (e, props) => { con ...

trouble with v-for in Vue.js causing data not to show on page

Whenever I use console.log(e.data), I am able to retrieve values, but when attempting to display them using v-for, the data does not show up. Can someone please explain why this issue is occurring? Below is the HTML code intended to display the values: & ...

Ensure the browser only reloads a single file

In the midst of my project, I realized that the CSS and JS files are being loaded separately onto the webpage with query strings like .css?1234 to ensure the browsers refresh the files on load. However, upon returning to the project, I discovered that one ...

Does assigning a value to the localStorage count as a side effect?

I am currently developing a React+Redux application that needs to store specific values from the store in localStorage. I have a utility function that securely saves values to localStorage, along with an action (thunk) and reducer. const wallet = (state = ...

There seems to be an issue with the bootstrap datepicker as it is throwing an error stating that $(

Currently in the process of developing a web application using AngularJS with MVC, I have integrated Bootstrap's datepicker into my project, Here is the code snippet: <div class="container"> <div class="row"> <div class=& ...

How can I populate a dropdown list in JavaScript with JSON data from a file?

I am experiencing difficulties when it comes to parsing JSON files for use in a dropdown list. JSON: { "BD": "Bangladesh", "BE": "Belgium", "BF": "Burkina Faso", "BG": "Bulgaria", "BA": "Bosnia and Herzegovina" } The goal is to populate the dropdownlist ...

Utilize AJAX to upload files to Blobstore in Google App Engine

I'm currently developing a project using Go for Google App Engine. I've encountered an issue with uploading files/images to blobstore without requiring a site reload. Here is the HTML form: <form id="file-form" action="{{.UploadUrl}}" method ...

Tips for deleting a duplicate identifier within an li element that possesses a particular class through javascript

I need help removing duplicate IDs from list items with a specific class. For example, in the following list, there are duplicates IDs (small, medium) and I want to remove the IDs with the class "size". How can I achieve this? <ul id="bulk"> ...