One Versatile Ajax Function for Accessing Various PHP Pages

On my index.html, there are buttons displayed below:

<button value="about_us.php" onClick="fNt(value)">About Us</button>
<button value="faq.php" onClick="fNt(value)">FAQ</button>
<button value="contact_us.php" onClick="fNt(value)">Contact Us</button>

I want to use AJAX to fetch information from PHP pages based on the button clicked. Instead of creating separate AJAX functions for each page, I am looking for a more efficient solution to handle multiple buttons without consuming too much space.

Is it possible to achieve something like the following?

<script>
function fNt(value) {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", value, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200 {
document.getElementById("ajax").innerHTML = xmlhttp.responseText;}}}
</script>

I understand that the script above is not functional, but it illustrates what I'm trying to accomplish. Any suggestions on how to make this work? Your help would be greatly appreciated.

Answer №1

Feel free to give this a try, it might come in handy...

function fetchData(url) {
  request = new XMLHttpRequest();
  request.open("GET", url, true);
  request.send();
  request.onreadystatechange = function() {
    if (request.readyState == 4 && request.status == 200) {
      document.getElementById("ajax").innerHTML = request.responseText;
    }
  }
}
<button onClick="fetchData('about_us.php')">About Us</button>
<button onClick="fetchData('faq.php')">FAQ</button>
<button onClick="fetchData('contact_us.php')">ContactUs</button>

Enjoy your coding journey!

Answer №2

In any case, it is essential to create a distinct callback for each button, unless the intention is for all buttons to trigger the same action when clicked. To streamline this process, consider encapsulating the uniform ajax code within a function and passing a URL along with a separate callback function to it. If you need to verify the status of the request object, simply pass it directly to the callback:

function executeRequest(url, callback){
    var xhr = new XMLHttpRequest(),
        method = "GET",
        route = url; //Adjust the URL if necessary

    xhr.open(method, route, true);
    xhr.onreadystatechange = callback(xhr);
    xhr.send();
}

To use this function:

var url = "desiredroute.com";
var customCallback = function(xhrObject){
   if (xhrObject.readyState == 4 && xhrObject.status == 200{
       console.log("SUCCESS")
   }
}

Another Approach

If the goal is to have different actions for each link, you can modify the executeRequest function by including the route in the callback function:

function executeRequest(route){

    var xhr = new XMLHttpRequest(),
        method = "GET",
        url = route; //Adjust the URL if necessary

    var specificCallback = function(routeParam){
       if (xhr.readyState == 4 && xhr.status == 200{
           switch(routeParam){
              case "faq.php":{
                 //perform specific action for "faq.php"
              }
              break;
              //continue with similar logic for other URLs
           }
        }
    }

    xhr.open(method, url, true);
    xhr.onreadystatechange = specificCallback(route);
    xhr.send();
}

To call this function:

<button onClick="executeRequest('about_us.php')">About Us</button>
<button onClick="executeRequest('faq.php')">FAQ</button>
<button onClick="executeRequest('contact_us.php')">Contact Us</button>

Ultimately, there are various ways to structure this process efficiently and reduce the amount of code required. The approach taken will largely depend on post-request actions.

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

Incorporating visuals into dynamic circles that are in motion and interacting

I have a collection of bouncing balls that are colliding with each other within a confined space. Currently, the balls are just simple green circles. However, I would like to replace them with images. How can I accomplish this? Here is the render functio ...

Using Javascript to modify file permissions in Google Drive

I'm new to writing and seeking amazing solutions for all the issues I encounter. I have a website hosted on Google Drive, utilizing its SDK for Javascript. Everything functions exceptionally well, except for one problem. I need to adjust the permissi ...

The Gulp task is stuck in an endless cycle

I've set up a gulp task to copy all HTML files from a source folder to a destination folder. HTML Gulp Task var gulp = require('gulp'); module.exports = function() { return gulp.src('./client2/angularts/**/*.html') .pipe( ...

:host background color may be missing, but the font size has been boosted?

Check out this demo where the CSS is applied to the :host element or <hello>. The font size increases but the background color remains unchanged. What do you think? styles: [` :host { font-size: 2rem; background-color: yellow; }`] }) ...

What is the best way to make message properties accessible to the public while also being able to access them within a web

Situation Our company works with various clients, some using native apps such as iPad and Android, while others use web-based platforms like websites and SmartTVs. We have a central web project that houses common assets used by all clients, including ico ...

Tips for transforming a Vue 2 website into a progressive web application (PWA) were requested

As I explored the PWA functionality in Vue 3, I noticed that it is not available in Vue 2. If anyone has any insights on how to successfully convert a Vue 2 project into a PWA, I would greatly appreciate your input. Thank you! ...

Tips for showing chosen options in react-select multi component?

I am incorporating react-select with isMulti functionality, where a list of options is provided. My goal is to have certain options automatically selected by default if they match the values in a given array. import React, { useState } from "react"; imp ...

Would it be considered acceptable practice to implement a setTimeout on the loading state to ensure that the log in page does not momentarily appear before the user has completed the authentication process?

Currently, I am developing a React Native application and encountered a situation where the login page was flashing before the user authentication. To solve this issue, I added a setTimeout function as shown below: export default function App() { const [ ...

Ways to observe redux action flow within a component

I am currently developing a React application structured with the following elements: redux typesafe-actions redux-observable My query is: How can I trigger a UI action when a specific redux action occurs? For instance, if we have these asynchronous ac ...

Tips on gathering information from an HTML for:

After encountering countless programming obstacles, I believe that the solution to my current issue is likely a simple fix related to syntax. However, despite numerous attempts, I have been unable to resolve it thus far. I recently created a contact form ...

What are the steps to generate an npm package along with definition files?

Is it possible to create an NPM package with definition files containing only interfaces declared in *.ts files? Consider a scenario where we have two interfaces and one class definition: export interface A { id: number; } export interface B { name: s ...

Transform an array of arrays object with multiple depths into an array of objects

Having some difficulty with the conversion of an array of arrays-like object into an array of objects. The reduce method is being used, and it successfully converts the array data to an object for the first set of arrays. However, on the second iteration, ...

Can someone provide guidance on creating a calculator using the Switch statement in Javascript?

Introduction to HTML: <div id="content"> <div id="calculator-container"> <form name="calc"> <!-- The form is named "calc" --> <label for="output">A Simple Calculator</label> & ...

How can I retrieve the transformation matrix for a DOM element?

Is there a way to retrieve the transformation matrix of a DOM element similar to how we can do it with canvas context? Does the DOM provide a getTransform() method for this purpose? ...

Error in AngularJS and TypeScript: Property 'module' is undefined and cannot be read

I'm attempting to incorporate TypeScript into my AngularJS 1.x application. Currently, my application utilizes Webpack as a module loader. I configured it to handle the TypeScript compilation by renaming all *.js source files to *.ts, and managed to ...

What could be the issue with my interactive dropdown menu?

I am currently experiencing an issue with a drop down list that is supposed to fetch records from a column in another table, but no records are appearing. Additionally, I would like to add an option in the drop down list labeled "others" for users to inp ...

Appending a JSON object to an array does not result in the object being added to the

Can anyone help me with an issue I'm facing? I have a code snippet where I am trying to push a JSON Object into an array, but the array is not updating properly. It only shows the last pushed element. var myData = {}; var id = 0; $("a").on('cli ...

Tips for boosting the efficiency of nested ng-repeat in AngularJS

I'm currently working on incorporating infinite scrolling into my AngularJs project. I've been using nested ng-repeat and binding data through a JAVA API. The data returned by the service is quite large, which is causing a significant drop in per ...

Exploring the power of AJAX/XMLHttpRequest and the sweet simplicity of

When Set-Cookie headers are returned in response to an XMLHttpRequest, how do different user agents react? Is it necessary for JavaScript to validate or direct the user agent to recognize that header? ...

Experimenting with Chai in JavaScript to test an incorrect argument

Background: I recently delved into JavaScript and have been experimenting with it. It's possible that my question may sound silly, but I am eager to learn. I have developed a function called `getDayOfTheWeekFromDate` which returns the day of the week ...