What is the best way to close an ajax page within the main page using a button?

I am dealing with a situation where I have 2 pages. The first page contains a div called 'ajaxicall', which loads another page inside it.

The challenge I am facing is figuring out how to close the second page when I click on the "close" button within that page, and then display the containers of my first div again. Any insights on this would be greatly appreciated. Thank you.

<!doctype html>
<html>
<head>
 <meta charset="utf-8">
</head>

<body>
  <div class="ajaxicall">
    <span id="addtobasketspan">First Div</span>
    <img src="images/shopping-cart-xxl.png"/>
  </div>

<script>
  $("#addtobasketspan").click(function(e) {
    $.ajax({
       url:'secondpage.html',
       type:'get',
       data: 'lid=1',
       success:function(data){
          $("ajaxicall").load('secondpage`enter code here`.html');
       }
  });
});
</script>

</body>
</html>

Answer №1

Check out the code snippet on jsFiddle: https://jsfiddle.net/acc33fm3/

This code uses jQuery to dynamically add a button to a page retrieved through AJAX, allowing you to easily hide the content when needed:

$("#addtobasketspan").click(function(e) {
  $.ajax({
    //url: 'secondpage.html',
    type: 'get',
    data: 'lid=1',
    success: function(data) {
      //$(".second-div").load('secondpage`enter code here`.html');
      $(".second-div").append('<button class="close-div">X</button>');
    }
  });
});

$(document).on("click", ".close-div", function() {
  $(this).closest('div').hide();
});

To implement this functionality in your project, just remember to append a button and use it to hide the loaded content.

Answer №2

For the second page, it's recommended to include an element such as a close button to easily exit and return to the default view of the first page. Here is an example of how you can achieve this:

<a href="#" id="closeButton">Close</a>

To add functionality to the close button, you can use the following code snippet:

$("#closeButton").click(function(){
    $('#ajaxCall', window.parent.document).html('
        <span id="addToBasketSpan">First Div</span>
        <img src="images/shopping-cart-xxl.png"/>
    ');
});

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

fancy box appears when double-clicking on a div element

Help needed: How can I open a div in fancybox on double clicking another div using jQuery with Rails 3.1? Here is the function I have inside document.ready() $("#a1").dblclick(function () { $.get("/projects/edit/"+this.id,{ u:$('#user').val ...

JSON does not transmit data via post requests

I have a question regarding JSON. Initially, I created this jQuery code: <script> $('#buy').click(function(){ var items=[]; var item={ firstname:'blabla' ...

Can we split the PHP Photo Gallery into a second page after displaying 12 images?

I recently developed a simple PHP photo gallery for my website that pulls data from a MySQL database. By using a while loop, I am able to display three images (from ID 1 to 3) in a single row, continuing this pattern until a total of 12 images are shown. ...

In Vue3, have you ever wondered why the $emit function seems to work fine before a promise fetch,

I have encountered an issue while attempting to pass the result of a promise fetch from a child component to a parent component using emit. Strangely, the emit function was working perfectly fine before the $fetch operation, allowing my parent component to ...

How to use AngularJS to collapse various panels with unique content

Hey everyone, I'm working on developing a collapsible panel using Angular. The panel should consist of a header and body to display the content. The desired behavior is that when a button is clicked, the content collapses down, and clicking the same b ...

Issue with jQuery: Android browser receiving XML instead of JSON from HTTP POST request

When attempting to make an HTTP POST request using jQuery in older Android browsers, I encounter a specific issue. The response received is: <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <application xmlns="http://wadl.dev.java.net/20 ...

What is the best way to identify the specific row and column that was clicked within a jQuery datatable

Scenario: When a user clicks on a cell in a datatable, a specific action should be triggered based on the row and column of that cell. How can I ensure that the user does not click on a certain column? If they do not click on that column, then I want to r ...

Steps to display an angled bracket to indicate a line break

I have a div that is editable, allowing me to display the entered text. To indicate each new line, I would like to show a ">" symbol at the beginning of the line. HTML <body> <div> <span> &gt; </span> ...

I am unable to retrieve dynamic data from the database

Storing data in a MySQL database has been successful for me. I've been utilizing PDO in PHP to fetch the data and then converting it to JavaScript using json_encode. However, I keep encountering the output NaN when implementing a specific scenario. It ...

Issue: Bidirectional binding functionality is not functioning properly within the user interface modal

I'm currently working on displaying data in a modal, but I'm facing issues with getting two-way binding to work properly. In my HTML code: <div class="cta-actions"> <div class="action"><a class="btn btn-lg btn-max">Send a pa ...

Adding text chips to a text field in Vuetify - A simple guide

I have successfully integrated a text field with vuetify and now I am looking to incorporate chips into it. Currently, chips are only added if the entered text matches a specific pattern (such as starting with '{' and ending with '}'). ...

What is the best way to distribute my rabbitMQ code among different components?

I am looking for a way to optimize my rabbitMQ connection code by creating it once and using it across multiple components. Currently, every time I need to pass data to my exchange and queue, I end up opening and closing the connection and channel multiple ...

Python code to generate a URL that opens in a new tab:

Currently, I am working on constructing a URL using Python 2.7 and have the following code snippet: link.append("<a href='" + tableLink + sysID[i] + " target='_blank'>" + ticketNumber[i] + "</a>") However, when the link is disp ...

Formatting Text in CSS and HTML

I need help aligning three images horizontally with text underneath, using CSS. Despite trying multiple methods, the images remain vertically aligned and the text does not align properly with the images. #img_cont { display: table; width: 90%; ...

Is your Cloud Functions task generating an Array when querying?

To access items and products in my database, I need to retrieve the "ean" field from the product and check if it matches the one in the request body. The structure of my database is as follows: "cart": { "items": { "0": {info here}, "1": {info ...

Utilizing Javascript Regular Expressions to extract specified parameters from URLs with specific patterns

I am facing a specific issue with pure vanilla javascript. My task is to extract the values of A, B & C from various URL patterns, excluding any instances where the value is "XX". A, B, and C are static words that can appear in different positions wit ...

Tips for effectively showcasing div elements

https://jsfiddle.net/qz8hL574/1/ for (var key in table) { if (table.hasOwnProperty(key)) { $('<div class="element"></div>').appendTo('#list'); document.getElementsByClassName("element")[key].innerHTML = ...

What is the most effective approach for preventing the inadvertent override of other bound functions on window.onresize?

As I delve deeper into JavaScript, I constantly find myself pondering various aspects of it. Take for instance the window.onresize event handler. If I were to use the following code: window.onresize = resize; function resize() { console.log("resize eve ...

What is the best way to display multiple Google Charts using various data tables within a single PHP document?

I am looking to create multiple charts using data from different sources. The data comes from queries within a PHP file named ajax.php. Below is the code snippet: //JOB POST BY SALARY function jobsalary(){ // Function logic here... } //JOB POST BY J ...

Resolving the active tab problem within Angular 2 tab components

Can anyone assist in resolving the active tab problem within an angular 2 application? Check out the Plunker link I am using JSON data to load tabs and their respective information. The JSON format is quite complex, but I have simplified it here for cla ...