Is there a way to retrieve two separate route details using jQuery simultaneously?

Clicking the checkbox should display the Full Name:

      input type="text" id="demonum" size="05">
      <button type="button" onclick="load_doc()">click</button><br><br>

      <input type="checkbox" id ="check" >

The route results are as follows:

function load_doc(){
    $(document).ready(function(){
      var stId = document.getElementById('demonum').value;
//
      URL1 = `http://localhost:8082/students/${stId}`;
      URL2 = `http://localhost:8082/getFullStudentDetails/${stId}`;

      $.get(URL2,function(responseText){

            $("#indexno").text(responseText.ID);//this came from URL1
            $("#pname").text(responseText.Name);//this came from URL1
            $("#pgrade").text(responseText.Grade);//this came from URL1
            $("#fullname").text(responseText.pName); //this came from URL2
        });
      });
    }

- Here is how it works!

  • "demonum" is a textbox where the ID number is entered and stored in the stID variable.
  • It then combines with URL1 & URL2.
  • The results are displayed based on the entered ID number.
  • The details are linked using the following IDs,
  • $("#indexno")
  • $("#pname")
  • $("#pgrade")
  • $("#fullname")

When entering ID number 1, it displays ID, Name, Grade based on $.get(URL,function(responseText) if the URL was changed to URL2, it would display ID, Name, Grade, and Full name.

  • I now want to achieve this...I believe I need to use URL2 because it contains ID, Name, Grade, and Full Name. Can you confirm based on the example provided?

For example, if I receive URL1, it should display ID, Name, and Grade. When I click the checkbox, it should then display the Full Name.

Answer №1

If you want to implement this functionality using JQuery, you can utilize the $.when method.

$(document).ready(function(){
  $("button[type=button]").on('click', function(){
    var isChecked = $("input[type=checkbox]").prop('checked')==true;
    var stId      = $("#demonum").val();
    var URL1      = `http://jsonplaceholder.typicode.com/users/${stId}`;
    var URL2      = `http://jsonplaceholder.typicode.com/posts/${stId}`; 

    $.when(
      $.get(URL1),
      // if checked then call second url
      (isChecked?($.get(URL2)):null)
    )
    .then(function(responseURL1, responseURL2) { 
      console.log('responseURL1', responseURL1)
      console.log('responseURL2', responseURL2)

      $("#indexno").text(responseURL1[0].id);//this came from URL1
      $("#pname").text(responseURL1[0].username);//this came from URL1
      $("#pgrade").text(responseURL1[0].phone);//this came from URL1

      if (responseURL2)
      {
        $("#fullname").text(responseURL2[0].title); //this came from URL2
      }
    });
  }); 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="text" id="demonum" size="05">
<button type="button">click</button><br><br>
<input type="checkbox" id ="check"> 

<table border="1">
  <thead>
    <tr>
      <th>ID</th>
      <th>Name</th>
      <th>Phone</th>
      <th>Post Title</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td id="indexno">-</td>
      <td id="pname">-</td>
      <td id="pgrade">-</td>
      <td id="fullname">-</td>
    </tr>
  </tbody>
</table>

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

Completing a form and saving data to a document

I have a form that successfully writes to a text file using PHP. However, after submitting the form, the page reloads and shows a blank page. Currently, there is a message that appears using jQuery after the form is submitted. My goal is to prevent the pa ...

The alignment of the Slick slider item appears off-center when viewed on a mobile device

https://i.stack.imgur.com/kwxaX.png When viewing the items on a mobile device, they are not centered as desired. The issue lies with the first item not being displayed in the center. How can this problem be addressed? Here is the code snippet: slickOptio ...

Adapting software for use with Panasonic Viera

We are in the process of transferring our current HTML/JavaScript/CSS application to the Panasonic platform. Our current setup involves using JavaScript for generating HTML and CSS for styling the application. The programming language used in the Panasoni ...

Having difficulty uploading an image to Facebook through the graph API

I have a requirement to upload a photo to Facebook using the Javascript SDK, but I am experiencing some difficulties: Firstly, FB.login(function (response) { if (response.authResponse) { va ...

Unable to update Discord due to opus installation issue

I recently encountered an issue with my Discord bot that was working perfectly fine yesterday. After attempting to host it on Heroku, I ran into some errors. To find a solution, I followed advice from an online post and executed the command npm cache cle ...

Experiencing challenges with ng-repeat and the concept of 'distinct'

I'm facing a perplexing issue. When utilizing ng-repeat to iterate through my data and create checkboxes, I encounter unexpected behavior. The result is multiple duplicate items being displayed instead of unique ones. Here's an example: <lab ...

The express-handlebars module is having trouble parsing HTML within the main layout file in an Express.js application

Hello, I am facing an issue with handlebars as it is not reading the HTML in my file. Here is a screenshot highlighting the problem along with the provided code. The folder structure is as follows: views layouts main-layout.hbs home.hbs https://i ...

Tips on displaying substitute text in Angular when an Iframe fails to load the content located at the src

Currently, I am working on an Angular 12 application and have a requirement to fetch content from an external site and display it within a modal popup. To achieve this, I am using the <iframe src="url"> tag to retrieve the content from a se ...

Tips on executing npm commands on Azure app service following a successful deployment via VSTS?

While I've successfully deployed from VSTS to Azure, I'm facing an issue with running npm after the deploy is complete. The current process involves running npm install for branch files, zipping them, copying to Azure, and deploying. However, I ...

Issues with visuals in jQuery.animate

I have nearly finished implementing a slide down drawer using jQuery. The functionality I am working on involves expanding the drawer downwards to reveal its content when the handle labeled "show" is clicked, and then sliding the drawer back up when the ha ...

Utilizing ReactJs refs to set focus on an input element

Exploring the use of refs in ReactJs to focus a textbox from a button click. Encountering the following error message: bundle.js:114 Uncaught TypeError: Cannot read property 'focus' of undefined Check out the Source Code below: class FocusTex ...

Ways to make a jsonp request without including the 'callback' in the URL

I've been working on retrieving information from an Icecast Radio station using their API, which offers the status-json.xsl endpoint to access this data. Despite the format being in xsl, I suspect it returns a JSON file. However, I've encountere ...

Is it possible to establish role-based access permissions once logged in using Angular 6?

Upon logging in, the system should verify the admin type and redirect them to a specific component. For example, an HOD should access the admi dashboard, CICT should access admin2 dashboard, etc. Below is my mongoose schema: const mongoose = require(&apo ...

Detect errors in the `valueChanges` subscription of Firestore and attempt a retry if an error occurs

My Angular app utilizes Firestore for storing data. I have a service set up to retrieve data in the following way: fetchCollectionColors(name) { this.db.collectionGroup('collection-colors', ref => ref.where('product', '==&ap ...

What is the best method for combining numerous tiles within a level in Kaboom JS?

Creating a level in kaboomJS with a extensive tile map collisions can sometimes result in slower performance. I'm exploring options to optimize this process, such as potentially merging multiple tiles together so that a whole row of blocks could funct ...

What is the best way to display div elements based on a selected option?

Here is the code for a select list that contains the number of guests for a room: <select name="txtHotelGuestNO" id="txtHotelGuestNO" class="hotels" onchange="show_room_choose()"> <?php for($i=1;$i<=100;$i++) echo "<option value=$i>$ ...

What is the best way to enable import and require support for npm modules?

Recently, I successfully published my debut module on npm using Javascript. Now, I am eager to ensure that it can support both import and require functions. Can someone guide me on how to achieve this? For reference, the module in question is available at ...

Issue: The plugin 0 mentioned in the file "/my dir/node_modules/babel-preset-php/src/index.js" contains an invalid property called "default"

While attempting to convert a PHP script to JavaScript using babel-preset-php, I encountered the following error: Error: Plugin 0 specified in "/media/deep/5738c180-2397-451b-b0b5-df09b7ad951e1/deepx/Documents/TestingAll/node_modules/babel-preset-php/ ...

Trigger a Redux action with the following action as the payload in order to display a Material UI snackbar or dialog

Currently, my project involves using React along with Redux and Material UI to develop a web application. The web app consists of numerous pages and components. It is common practice to have a snackbar or dialog interact directly with the user's actio ...

Form validation using jQuery and AJAX

I've implemented validation in my ResetPassword function and it seems to be working fine. However, I'm facing an issue where the ResetPassword function stops working once the validation is added. Can someone guide me on how to resolve this issue? ...