Tips for displaying a popup modal when a link is clicked with ajax technology

I am facing an issue with my popup modal. When a user clicks on a link, the modal appears but without any content. I am new to ajax and feeling a bit confused about what steps to take next. Below is the HTML code snippet:

<div class="modal fade" id="answerModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
  <div class="modal-header">
    <h4 class="modal-title">ANSWER</h4>
    <button type="button" class="close" data-dismiss="modal">&times;</button>
  </div>
<div class="modal-body">
</div>
  <div class="modal-footer">
   <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
  </div>
</div>
</div>
</div>
<a data-toggle="modal" class="btn" href=#link1 data-target="#answerModal"> VIEW ANSWER → </a>
<a data-toggle="modal" class="btn" href=#link2 data-target="#answerModal"> VIEW ANSWER → </a>
<a data-toggle="modal" class="btn" href=#link3 data-target="#answerModal"> VIEW ANSWER → </a>

Here is the script I have been using:

$(document).ready(function(){
$('.btn').click(function(){
  var link = $(this).data('url');
  console.log(ok);
  // AJAX request
  $.ajax({
    url: link,
    type: 'get',
    data: link,
    success: function(response){ 
    // Add response in Modal body
      $('.modal-body').html(response);
    // Display Modal
    $('#answerModal').modal('show'); 
    }
  });
});});});

Check out how my modal looks like here.

Answer №1

I made some modifications to your code, which you can review below. I have also added a condition where if the API doesn't respond with success or the link is blank, an error modal will be displayed.

You have included an extra closing bracket at the end of your JavaScript code "});".

<!DOCTYPE html>
<html lang="en">

  <head>
    <title>Demo</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4b2924243f383f392a3b0b7f657e6578">[email protected]</a>/dist/css/bootstrap.min.css" />

    <script src="https://code.jquery.com/jquery-3.5.1.js" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="086a67667d7a7d7b686944706a61786bee636f6468622a676bec696fecfb525a51585c639988abe4">[email protected]</a>/dist/js/bootstrap.bundle.min.js"></script>
  </head>

  <body>
    <div class="modal fade" id="answerModal" role="dialog">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h4 class="modal-title">ANSWER</h4>
            <button type="button" class="close" data-dismiss="modal"> &times; </button>
          </div>
          <div class="modal-body"></div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal"> Close </button>
          </div>
        </div>
      </div>
    </div>
    <a class="btn" href="javascript:void(0)" data-url="https://jsonplaceholder.typicode.com/todos/1"> VIEW ANSWER → </a>
    <a class="btn" href="javascript:void(0)" data-url="https://jsonplaceholder.typicode.com/todos/2"> VIEW ANSWER → </a>
    <a class="btn" href="javascript:void(0)" data-url=""> VIEW ANSWER → </a>
    <a class="btn" href="javascript:void(0)" data-url="https://jsonplaceholder.typicode.com/abcd"> VIEW ANSWER → </a>
    <script>
      $(document).ready(function() {
        $(".btn").click(function() {
          var link = $(this).data("url");
          console.log(link);
          // AJAX request
          if (link == undefined || link == '') {
            $(".modal-body").html("<p>if link is not available then Your error message display here!!!</p>");
            $("#answerModal").modal("show");
          } else {
            $.ajax({
              url: link,
              type: "get",
              data: link,
              success: function(response) {
                console.log(response)
                console.log("api successful");
                $(".modal-body").html(JSON.stringify(response));
                $("#answerModal").modal("show");
              },
              error: function(response) {
                $(".modal-body").html("<p>Please try after some time...</p>");
                $("#answerModal").modal("show");
              },
            });
          }
        });
      });
    </script>
  </body>

</html>

Answer №2

Here are some necessary changes and verifications that must be conducted.

  1. Eliminate data-toggle and data-target attributes from your <a> tags, as they cause the modal to open regardless of the success or failure of the API call. In the event of an API failure, there will be no content to display in the modal.

  2. Add a console.log statement within the success function of your API call to verify if the call was successful.

  3. Ensure that the variable link = $(this).data("url"); is not undefined.

I have also included a functional code snippet below for your reference using placeholder API calls; make sure to replace them with the actual URLs you wish to access.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
        <link
            rel="stylesheet"
            href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="52303d3d26212620332212667c677c61">[email protected]</a>/dist/css/bootstrap.min.css"
            integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2"
            crossorigin="anonymous"
        />
    </head>
    <body>
        <div class="modal fade" id="answerModal" role="dialog">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h4 class="modal-title">ANSWER</h4>
                        <button
                            type="button"
                            class="close"
                            data-dismiss="modal"
                        >
                            &times;
                        </button>
                    </div>
                    <div class="modal-body"></div>
                    <div class="modal-footer">
                        <button
                            type="button"
                            class="btn btn-default"
                            data-dismiss="modal"
                        >
                            Close
                        </button>
                    </div>
                </div>
            </div>
        </div>
        <a class="btn" href="javascript:void(0)" data-url="https://pokeapi.co/api/v2/language/5"> VIEW ANSWER → </a>
        <a class="btn" href="javascript:void(0)" data-url="https://pokeapi.co/api/v2/language/6"> VIEW ANSWER → </a>
        <a class="btn" href="javascript:void(0)" data-url="https://pokeapi.co/api/v2/language/7"> VIEW ANSWER → </a>
        <script
            src="https://code.jquery.com/jquery-3.5.1.js"
            integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
            crossorigin="anonymous"
        ></script>
        <script
            src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="26444949525552544756661208130815">[email protected]</a>/dist/js/bootstrap.bundle.min.js"
            integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx"
            crossorigin="anonymous"
        ></script>
        <script>
            $(document).ready(function () {
                $(".btn").click(function () {
                    var link = $(this).data("url");
                    console.log(link);
                    if(!link || (link === '')){
                        $(".modal-body").html("<p>Invalid link!</p>");
                        $("#answerModal").modal("show");
                        return;
                    }
                    // AJAX request
                    $.ajax({
                        url: link,
                        type: "get",
                        data: link,
                        success: function (response) {
                            // Add response in Modal body
                            console.log(response)
                            console.log("api successful");
                            $(".modal-body").html(JSON.stringify(response));
                            // Display Modal
                            $("#answerModal").modal("show");
                        },
                        error: function(err){
                            $(".modal-body").html(err.responseText);
                            $("#answerModal").modal("show");
                        }
                    });
                });
            });
        </script>
    </body>
</html>

Answer №3

If you're looking to add a modal popup to your website, consider using Sweet Alert 2. This library makes managing modals easy for you. Simply implement the link like this:

<a href="YOUR LINK" onclick="popup()">This is a link!</a>

Here's some basic JavaScript code to get you started (feel free to customize it):

function popup(){
    Swal.fire(){
        title: "Hey you clicked the link!"
    }
}

To learn more about Sweet Alert 2 and explore additional examples, check out their website

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

Combining multiple storageStates in a playwright context for efficient loading

I am trying to load multiple storageStates into a single context in playwright, but I am facing some issues. When using the following code: const context = await browser.newContext({ storageState: "telegram.json",storageState: "google. ...

I keep encountering the error message "$(".dropdown-toggle").dropdown is not a function" while attempting to use Dropdowns with Jade and Bootstrap

I am attempting to implement a Bootstrap dropdown in my Jade layout. However, I keep encountering an error when trying to run $(".dropdown-toggle").dropdown in my Jade file: $ is undefined $(".dropdown-toggle").dropdown is not a function What could be ...

Adjust the opacity of a MeshBasicMaterial in real-time

<script type="importmap"> { "imports": { "three": "https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="384c504a5d5d784e0816090e0a1608">[email p ...

The Angular 9 custom directive is malfunctioning on mobile devices

I recently created a custom directive in Angular 9 that allows users to input only digits and one decimal point. While the directive works perfectly on desktop, it seems not to function at all on mobile devices - almost as if it doesn't exist within t ...

Extra spaces within the source code visible after the page has been processed by Angular

Within my angular application, I am retrieving a list of addresses from a service that provides an object structured like this: { Flat: "10B", BuildingName: "Some Building", Line: "10B Some Building Road Town POST CODE", Postcode: "POST CODE", ...

Guide on navigating through various HTML pages with distinct parameters using Node.js (Express server)

Seeking assistance with a Node.js server that receives an ID as a query parameter. Each time a client connects with different parameters, I aim to serve them a unique HTML page containing a simple UI with 2 dynamic arrays. Everything seems to be working co ...

Managing a significant volume of form data transmission to PHP backend

I have a moderately large HTML form with Javascript functionality to dynamically create additional 'records' within certain sections of the form. There could potentially be over 50 INPUT elements in total. I am contemplating the most effective a ...

After the update to the page, the DOM retains the previous element

I'm currently developing a Chrome Extension (no prior knowledge needed for this inquiry...) and I have encountered an issue. Whenever I navigate to a page with a specific domain, a script is executed. This script simply retrieves the value of the attr ...

Encountered an error with the opcode during deployment of migrations

Encountering an error while running the truffle migration command, despite trying several solutions without success. PS C:\Users\Jatin\OneDrive - nsut.ac.in\Desktop\Truffle\web> truffle migration Compiling your contracts... ...

What is the best way to ensure that a navbar dropdown appears above all other elements on

I'm having trouble creating a navbar dropdown with material design. The dropdown is working fine, but the issue I'm facing is that other elements are floating above it. https://i.stack.imgur.com/aJ0BH.png What I want is for the dropdown to floa ...

What is the best way to update a collection item while maintaining non-existing values in the query?

Consider this straightforward example, where an item is saved as: { "test": { "a1": "a1" } } When collection.updateOne is called with $set and the following object: await collection.updateOne(doc, {$set: {"test&q ...

Maintain Open State of Toggle Drop Down Menu

Having an issue with the toggle down menu or list on my webpage. The problem is that the menu is constantly open (the #text_box) when the page loads. My intention was for it to be closed initially, and then open only when the user clicks on the 'Ope ...

Retrieving and submitting text in a NodeJS environment

I'm attempting to retrieve text from an API that only provides a string of text ((here)), but I am encountering difficulties in displaying it accurately. When I try to post it, the output shows as [object Response], and the console.log is not showing ...

Stopping Default Behavior or Button Click Event in JavaScript During Ajax Request

I've utilized e.preventDefault() previously to stop a click event, but I'm struggling to understand why it's not functioning in this particular case. I've assigned all anchor tags in a column a classname, then obtained references to the ...

What steps can I take to ensure that a JavaScript function does not execute when a DOM element from an array has already been chosen?

I am facing an issue with a script that dynamically changes the header based on the selected bubble in an array. The problem arises when the user clicks on the same bubble that is already selected, causing the JavaScript function to run and temporarily cha ...

"The Vue.js/JavaScript object updates, but the changes are not being displayed in the document object model (DOM

Currently, I am endeavoring to iterate through an array of objects and display them as list items. There is a click listener that introduces a custom property to the object, and a class binding depends on the value of that property. Would you mind reviewin ...

Comparing Canvas and CSS3 for Website Development

Many discussions focus on comparing games with high levels of interaction, but my project involves a web application that manipulates objects individually. These objects can be images or text, and they can be replaced, resized, rotated, zoomed in, and dele ...

Using a boolean checkbox with Spring MVC and implementing ajax

On my HTML page, I have a boolean checkbox that looks like this: <input type="checkbox" id="pnrCheckbox" name="includesPnr" value="true"/> <!-- This field is generated by Spring as a workaround for something --> <input type="hidden" name="_ ...

The process of uploading a file through ajax results in it being sent to php://input

---Resolved By making the following adjustment: var request = new XMLHttpRequest(); request.open("POST", $(this).attr('action')); request.send(formData); The issue is now fixed, but I am unsure of the underlying reason. I have not found an exp ...

Unable to import a Module in React without curly braces, even when using 'export default'

I recently stumbled upon a question regarding module imports in React. Some sources mentioned that using curly braces around imports can increase the bundle size by importing the entire library. However, I had been successfully importing modules without cu ...