How can I use Ajax to populate a div with data from a php script?

Is there a straightforward method to populate a div by fetching a PHP script (and sending data like POST or GET) to determine what data should be returned?

I'm searching for a solution that doesn't rely on a library... All I seem to come across are examples using prototype and jquery.

Has anyone accomplished this without using a library?

Answer №1

let request;

function displayUser() {
    request = createHttpRequestObject();

    if (request == null) {
        alert("Your browser does not support HTTP requests");
        return;
    }
    
    let url = "yourpage.php";
    url = url + "?q=" + str;
    
    request.onreadystatechange = handleStateChange;
    request.open("GET", url, true);
    request.send(null);
}

function handleStateChange() {
    if (request.readyState == 4) {
        document.getElementById("yourdiv_id").innerHTML = request.responseText;
    }   
}

function createHttpRequestObject() {
    if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
    }
    if (window.ActiveXObject) {
        // code for IE6, IE5
        return new ActiveXObject("Microsoft.XMLHTTP");
    }
    return null;
}   

Answer №2

Check out this code for a great example of how to manage XHR objects with some helpful syntax.

This "library" is less than one hundred lines long and does exactly what you need it to without any unnecessary extras.

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

Displaying AJAX data in a table format, showcasing 10 rows of information

I am currently working on an ajax function that retrieves data from a database based on the entered information. My goal is to display this information in a table with the following format: System Id | Last Name | First Name | Middle Name | Address Below ...

I'm looking for a simple calendar widget that can be clicked on using only plain JavaScript/jQuery and is compatible with Bootstrap

I'm in search of a simple clickable calendar widget to integrate into my website. I am using a combination of HTML, CSS, Bootstrap 5, and jQuery 3.6 for development. The functionality I require is for the calendar days to be clickable so that I can di ...

Understanding the Difference Between WARN and ERR in npm Peer Dependency Resolution

I encountered a puzzling situation where two projects faced the same issue, yet npm resolved them differently: https://github.com/Sairyss/domain-driven-hexagon npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! W ...

Updating items within a nested list in Redux can be achieved by carefully managing the state and implementing actions to add or remove

My current state is set up like this: Fruits: { 34: { FruitsID: 34, FruitsList:{apple, pineapple, banana} } } I want to update my fruit list by adding 'peach' and 'pear', while also removing 'apple&apos ...

Javascript function to deselect all items

One of my functions is designed to reset all checkbox values and then trigger an AJAX request. However, there are instances when the function initiates before the checkboxes have been unchecked. function clear() { $("#a").prop("checked", false); $("#b ...

issue regarding h:commandButton and AJAX

My page contains the following code: <h:form id="qw"> <h:panelGrid columns="3" > <h:outputLabel for="username" value="Login:"/> <h:inputText id="username" value="#{userManager.userName}" required="true"> ...

Tips for implementing a handler on a DOM element

$(document).ready(function(){ var ColorBars = document.getElementsByClassName("color-bar"); var number = 0; ColorBars[0].onclick = hideLine(0); function hideLine(index){ var charts = $("#line-container").highcharts(); v ...

Use three.js to drag and drop an obj file

I am currently experimenting with a Three.js example that involves draggable cubes. You can find the example here. My goal is to replace the default internally created cubes with obj files. Here's what I've done so far. I have included an obj m ...

What are the different ways for GWT to communicate with C++?

I need help finding a way for GWT to communicate with C++. I am currently exploring how to utilize WSDL in GWT, but I have minimal experience with both WSDL and GWT. My main question is whether it is feasible to work with WSDL in GWT (and if so, how?) or ...

Cautionary alert while displaying a data binding from a controller in AngularJS

Adding a numerical value to the controller: this.myValue = Number(elem.toFixed(2)); Then placing it inside an input form: <input class="my-input" type="number" value={{$ctrl.myValue}} ... > Although the value ...

Retrieve specifically chosen values from the dropdown menu and eliminate any values that have not been selected

Within my two multiple dropdowns, the first contains all available fields with their corresponding values. The second dropdown displays the selected value along with all other values that were not selected. However, I only want to show the three values tha ...

Getting JSON key and value using ajax is a simple process that involves sending a request

There is a JSON data structure: [{"name":"dhamar","address":"malang"}] I want to know how to extract the key and value pairs from this JSON using AJAX. I attempted the following code: <script type="text/javascript> $(document).ready(function(){ $ ...

Using jSLint in combination with Angular leads to an unexpected error regarding the variable "$scope"

When performing a jSLint check on my Angular-based app, I encountered an "Unexpected '$scope'" error. To replicate the issue, you can try inputting the code snippet below into jslint.com. I'm puzzled as to why the first function declaration ...

What's the most effective method for updating the title of the date header on MUI Date Picker?

Does anyone know how to customize the title of the Calendar in MUI Date Picker? I want to add a specific string to the display that shows the month and year, like "August 2014." https://i.stack.imgur.com/qgMun.png I've searched the API but couldn&ap ...

Mastering the map() function in Vue.js 2

As I start learning vue.js, I am facing some challenges. I need to implement a dictionary analog in JavaScript, known as a map. However, I'm unsure of where to define it. The map should be utilized in both the checkDevices() method and within the HTML ...

Angular.js controller unable to receive object array from $http.get in factory

I am fairly new to Angular development and I've hit a roadblock that's been holding me back for a while. My factory is successfully creating an array filled with objects, specifically RSS feed data, and I can see it loading in the console. Howev ...

What could be the reason for incorrect data being sent when using multi-select values with jQuery/A

I implemented a multi-select dropdown menu where users can select values. Whenever a user selects a value, a jQuery/AJAX request is sent to the server. Check out the code snippet below: $("#send").on("click", function() { var elem$ = $("#cars"), el ...

Using jQuery: How can we manipulate the data returned by sortable('serialize') on a list?

Using jQuery, I have successfully retrieved the positions of a sortable list by using 'serialize' as shown below: var order = $('ul').sortable('serialize'); The variable 'order' now contains this data: id[]=2& ...

The Spring controller receives only the initial index of the stringified array from Ajax

Below is the complete JS code snippet: function getPoolsData(){ $.getJSON('../json/data.json', function(data) { var date_from = new Date(); console.log(date_from); var pools_hashrates = [{"date_from" : date_from}]; data.pools.forEach(function( ...

Exploring Next.js dynamic imports using object destructuring

import { UDFCompatibleDatafeed } from "./datafeeds/udf/src/udf-compatible-datafeed.js"; I'm facing a challenge in converting the above import to a dynamic import in Next.js. My attempt was as follows: const UDFCompatibleDatafeed = dynamic(( ...