Introduction to AJAX: Conditional Statements

Within the menu.html file, there are various menu items (a href links) called menu_1, menu_2, and so on.

The map.js file is responsible for displaying map content by utilizing an API to showcase different layers and maps. Even though there are many maps to display, the goal is to only call the API once.

I'm curious if it's feasible to use AJAX in my JavaScript code to create a scenario where when a specific menu item like menu_1 is clicked, then map_1 is implemented without requiring the page to reload. One potential approach I considered involves using post/get methods, such that when menu_1 is selected, it redirects to page.php?page_id=1. JavaScript can then interpret this information and showcase the corresponding map.

As someone who is new to JS and AJAX, I am open to constructive criticism and guidance.

Answer №1

A great way to enhance your website is by utilizing jQuery. By simply adding a click event handler to each link, you can easily customize the behavior of your elements:

For example, jQuery("#my_menu_item").click( function(){ // Add your custom action here... } );

Additionally, consider using jQuery.post or jQuery.get methods for fetching data and updating your webpage seamlessly.

Answer №2

DEMO: http://jsbin.com/ohaxa/4/edit

$(function() {
  $('#menu li > a').click(function(e) {
  e.preventDefault();

  var my_id = $(this).attr('id'); // grab id from link

$.ajax({
   type: "POST",
   url: "ajax_call.php",
   data: "action=do_something&my_id=" + my_id,
   success: function(data){

     my_function(my_id); //execute outside function...

    //OR use the returned "data" value and add it to DOM 
    // $(#ajax_call_back).append(data); 

   },
  complete: function(data){
     //execute something when request is complete..
   },
  error: function(data){
     //handle errors in this demo pseudo ajax call instead!
     my_function(my_id);

   },
 }); 

});
});

function my_function(id) {
  alert(id);
  var map = '';

  switch(id)
{
case 1:
map = id;  //map_1
  break;
case 2:
map = id;  //map_2
  break;
case 3:
map = id;  //map_3
  break;
default:
map = id;  //map_0
}

 $('#application').text('map_' + map);  

};

     <ul id="menu">
           <li><a href="#" id="1">menu_1</a></li>
           <li><a href="#" id="2">menu_2</a></li>
           <li><a href="#" id="3">menu_3</a></li>
           <li><a href="#" id="4">menu_4</a></li>
           <li><a href="#" id="5">menu_5</a></li>
        </ul>

     <div id="application"></div>
  <div id="ajax_call_back"></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

The error message "No native build was found for M2 MacBook" appeared while using npm with Node

I encountered this issue while working on my M2 MacBook, which ran smoothly on my older Intel MacBook. Any insights on what might be causing the problem? Using bun, but even running npm run dev (node 18) results in the same error. The same error has also ...

Authentication Failure: Passport azure-ad Verify Callback Is Not Triggered

When utilizing passport (with the passport-azure-ad strategy) for request authentication, I have encountered an issue. The initial request to Azure Active Directory proceeds smoothly, allowing me to log in with my credentials. However, I anticipate that th ...

Style the div element with CSS

Is there a way to style a div element within an HTML document using Sencha framework? I have specific CSS properties that I would like to apply to my div. #logo{ position:absolute; top:20%; left:0%; } Below is a snippet of my Sencha code: Ex ...

What is the purpose of using Array.prototype.slice.call(nodeList) for handling DOM elements?

Many JavaScript libraries like jQuery and Zepto frequently use Array.prototype.slice.call on querySelectorAll(), getElementsByTag, or ClassName results. Despite browsing numerous questions and answers on StackOverflow about this topic, I understand that it ...

What is the best way to modify the styling of my CSS attributes?

I'm currently working with this CSS code: input:checked + .selectablelabel .check { visibility: hidden; } Now, I want to change the visibility property to "visible" using JavaScript. I attempted the following: $(document).on('click', & ...

Why is my Ajax post request to the CodeIgniter controller resulted in a 404 error, even though it successfully reached the

We are encountering a strange issue where our code works perfectly on our local machines, but once we deploy it to the live server, we get a 404 error. Despite the error, the response from the login function in the controller is still displayed. We have sp ...

Is it possible to change the hover highlight rotation on a link without affecting the surrounding elements?

Is it possible to rotate the highlight on a link when hovered? I'm new at this, so apologies if this question seems basic. This is how my css/html is currently structured: .links { display: block; } .links a { color: #000000; text-decoratio ...

Storing form data in a file using React

I am trying to create a feature in my react component where instead of submitting a form and sending the data, I want to write this data to a file for later use. Is it achievable using vanilla JS or should I consider using a library? This is how my handl ...

Is it possible to dynamically create input fields in AngularJS by clicking a button?

I'm currently working on a project that involves adding an input field and a button each time a user clicks on the button. Is there a way to retrieve the text from the input field when the new button, which is displayed alongside the input field, is ...

Encountering an issue while attempting to utilize the .find() method in Mongoose

Currently, I am in the process of setting up a database using MongoDB and integrating the Mongoose ODM with Node.js. After running the code multiple times without any issues, I encountered an unexpected error when adding the last block to utilize the .find ...

Issue with dynamically generated modal popup not registering jQuery 'on' event handler

Originally, I believed that jQuery's on event handler had the capability to 'listen' for dynamically generated elements and that it was meant to replace the functionality of live. However, in practice, when using on, I found that it was not ...

Trouble with executing Mongoose find within an asynchronous function

Even after referring to this stack overflow solution, I still couldn't resolve my issue. The find method works perfectly when used inside a controller but not within an async function. Here is the cron job where I'm calling this function in my ...

Navigating to the present child state with modified parameters can be achieved using the following steps

Check out this demo: https://jsfiddle.net/explorer/622qzqsc/ In the platform I'm working on, we have an advanced concept of state management, specifically for building timelines. In the template of this system, there's a code snippet (which is c ...

The name field in the request body is currently undefined

Currently, I am working on developing a basic blog page using technologies such as ejs, JavaScript, Node.js, Express, and body-parser. While working on passing inputs to the command line, specifically for the title, I encountered an issue. When I used req ...

How to effortlessly convert a JSON string into a JavaScript object

Hello everyone, I am working with DynamoDB and need to parse the JSON Object that is returned from a call in order to retrieve the password hash field. jsonString = JSON.stringify(data) console.log(jsonString) This is what the output looks like: {"Count ...

What steps can I take to avoid Vue.js overriding jQuery bindings within components?

After incorporating vue.js into an existing project and attaching the vue instance to the body tag with an ID of "app," everything seemed to be running smoothly. jQuery and Vue.js were cooperating well together. However, as soon as I started creating compo ...

Retrieving the class ID when clicked

In my PHP while loop, I am generating multiple classes to display information (such as user posts) along with two buttons at the bottom of each post. One button increments and the other decrements a numerical value. I am trying to figure out how to retri ...

Best Practices for Closing MySQL Connections in Node.js

Currently, I am working on a project using Node.js in combination with Express and MySQL. My main concern at the moment is regarding the closing of the connection to MySQL. The code snippet for this operation is provided below: iniciarSesion(correo_el ...

The Vue/Vuetify wrapper component does not automatically pass on the `hide-details` parameter to the input component

I recently crafted a custom wrapper for the v-select input using Vuetify. Along with custom properties, I utilized the v-bind="$props"attribute to inherit all props. Upon testing, I observed that while this method applies to most props, it doesn ...

Receive immediate updates of the text input in real-time using the onkeydown event handler in Javascript

I attempted to display the content of the input box in a message div simultaneously, however, the output always seems to be one step behind. function showWhatsWritten(){ var tempText; tempText = document.getElementById("text").value; document.getEle ...