Creating a dropdown menu with data loaded dynamically using ajax and json, all without relying on jquery

I am looking to populate a few select menus using JSON data retrieved from my PHP script. Each select menu should display different values based on the selections made in the other menus. While I understand how to clear and fill a select menu using JavaScript with an array, I am unsure how to utilize an AJAX call to retrieve the necessary JSON data for populating the menus.

It is important to note that I prefer not to use jQuery due to its size and complexity for this simple task.

Any advice or insights on this issue would be greatly appreciated.

Below is my test script for populating a menu:

var selectMenu = document.getElementById(foo);
selectMenu.options.length = 0;
for(var i=0; i<100; i++){
    selectMenu.options[i] = new Option(i + "Option text", i+"optionValue");
}

Thank you.

Answer №1

Zepto is a fantastic alternative to jQuery with its lightweight design and excellent JQ Ajax support. Its compact size can significantly increase efficiency in your development process.

Answer №2

If you are in control of the PHP script, one simple method to use is JSON-P.

Here's how it works on the server side:

<?php

$callback = $_GET['callback'];
$jsonData = json_encode($data);
print $callback . '(' . $jsonData . ');';

?>

And here's how it's done on the client side:

<script>

function fetchJSON() {
    var scriptElement = document.createElement('script');
    scriptElement.src = 'http://www.example.com/data.php?callback=handleResponse';
    document.getElementsByTagName('head')[0].appendChild(scriptElement);
}

function handleResponse(jsonData) {
    // process the JSON data accordingly
}

fetchJSON();

</script>

This code snippet demonstrates a basic GET request to a remote page. The page then sends back the JSON data wrapped in a callback function name specified by you, which immediately triggers the handleResponse function with the JSON object as an argument.

Answer №3

If I've understood your query correctly, you're seeking a way to send requests to the server and retrieve data in JSON format without relying on jQuery or any other libraries.

Let's travel back in time to the year 2000 before 'prototype', 'jQuery', and similar frameworks came into existence, when the term 'Ajax' hadn't even been coined (although the concept was already being used).

  1. XmlHttpRequest - An object that facilitates sending asynchronous HTTP requests and receiving responses. Originally designed for XML content by the creators of Microsoft Outlook Web Access, it now supports various MIME types, including JSON. Initially an ActiveX available only in IE, it is now a sub-object of the 'window' top-level object and is supported by all browsers. Both jQuery and most libraries utilize this object for Ajax functionality. For more information and examples, visit: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
  2. XmlHttpRequest only allows requests to be made to the same domain as the page. To work around this limitation, a technique called JSON-P was introduced. By creating a `script` element with its source pointing to another domain, server-generated scripts can pass data as an argument to a callback function implemented in your page. The name of the function becomes part of the URL, like so:
<script type="text/javascript" 
    src="http://blogname.blogspot.com/feeds/posts/default?alt=json-in-script&callback=myFunc"
    ></script>

Take a look at this example URL (which fetches recent posts from Google's blogpost). Notice how everything is encapsulated within a call to the function `myFunc`, passed as a callback.

You can either embed the `script` element directly into your code, generate it dynamically using `document.write`, or use DOM manipulation to add a `SCRIPT` element to the document.

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

Pressing JavaScript buttons to trigger another button

I am looking to develop a script that generates a button which then creates another button. The subsequent button will be assigned an id attribute by incrementing from 1 to infinity. This feature should apply to all buttons (original button and the newly ...

Integrate fullCalendar event creation with Spring MVC using an AJAX request

I am looking to integrate a new event into fullCalendar and send this event as a JSON object to the server side, which is running on SpringMVC, through an AJAX request. However, every time I make the request, I receive a "400 Bad Request" response. Here i ...

I'm experiencing difficulty accessing the correct identification number for my questions on the website

Hi, I'm currently developing a website using Meteor where users can post questions and receive answers. I want to implement a feature that allows users to delete their own questions. When I try to directly pull the ID of the question and delete it, it ...

Having trouble with JavaScript canvas drawImage function not functioning correctly

Having some trouble drawing part of an image properly. The width and height are not matching the original. Check out my code below: window.onload = function() { ImageObjSketch = new Image(); // URL ImageObjSketch.src = 'https://i.imgur.com/75lATF9 ...

Looking to display the "loading....." message on a PHP page?

I am working on a PHP webpage where I need to implement the following features: 1. Upon clicking "Say Thanks", it should change to "Done!". 2. Simultaneously, I would like to trigger an action in the indexController. 3. While this action is happening, I wa ...

Do multiple AJAX calls share parameters?

I have a JavaScript function as shown below: function makeAjaxCall(outerParameter1, outerParameter2, outerDivId, paramInput){ $.ajax({ type: "POST", url: "some time taking LargeWebMethod or URL", //may take some time to return output dat ...

Tips for transferring form data from a React frontend to the backend Node.js server

I have been attempting to send FormData from React JS to my backend (Express Node server) with the code snippet provided below. However, I am encountering an issue where req.body.myFormData in expressTest.js is showing up as empty. Despite trying various ...

Organize JSON data based on the timestamp

What is the most effective method for sorting them by timestamp using jquery or plain JavaScript? [{"userName":"sdfs","conversation":"jlkdsjflsf","timestamp":"2013-10-29T15:30:14.840Z"},{"userName":"sdfs","conversation":"\ndslfkjdslkfds","timestamp" ...

Define the width of jqgrid

I have been utilizing SmartAdmin jqgrid to showcase data in tabular format. The number of columns in the datatable changes dynamically each time. I am converting the DataTable to a JSON object and assigning it to the jqgrid. However, it appears that jqgrid ...

What causes the failure of $event binding when using RowGroup tables with PrimeNG?

I have successfully implemented RowGroup to store 3 different tables, which is working great. However, I am facing an issue with the onRowSelect function not functioning properly. When I click on any row of the RowGroup tables, nothing happens. On another ...

Display the query results on a separate blade

In my original attempt, I intended to display the results in a modal but later decided to show them in a different blade. My goal is to fetch all comments related to a post using its post_id. However, I encountered the following error: The GET method is no ...

Retrieve all documents with a matching objectId field in MongoDB

I built an API that can fetch all data from a table, but within this table there is an object ID reference to a user. Table 1 - Story | Table 2 - User api.get('/all_stories', function(req, res) { Story.find({}, function(err, stories) { ...

Images set as the og:image on the following 14 websites hosted on Vercel require authentication to be displayed

After deploying my Next.js 14 site on Vercel, I placed opengraph-image.png in the app folder alongside layout.tsx. Upon inspecting the meta tag, I noticed the following: <meta property="og:image" content="https://ns-website-6pnvd8ili-mare ...

Sending a confirmation message after a successful JSON post

I am currently facing an issue with posting JSON data to a C# Web API. Below is the code snippet I am using to achieve this: submitData(data: any): Observable<Response> { return this.http.post( 'https://localhost:44396/api/PostNewCo ...

List of items displayed in alphabetical order using the ng-repeat directive:-

I'm working with an ng-repeat block in the code snippet below. My goal is to have the placeholder [[THE ALPHABET]] render as a, b, c, d representing bullets for the list in their respective order. There will always be 4 values present. What would be t ...

AngularJS: accessing remote systems - a guide

I am looking to explain my objective clearly I need guidance on how to establish a remote desktop connection from my Angular.js application to a windows application running system. The server I am using is Google App Engine. My current ideas: The Windo ...

Showcasing ranges from various input types on a single page

I have a challenge in displaying the values of multiple sliders on my webpage. Here's the code snippet I've been working on: var i = 0; var st = 'slider'; var ot = 'output'; var s = ''; var o = ''; for ...

Is there a way to display errors during jQuery validation?

Is there a specific function that can provide all error messages generated during form validation? I attempted to use the defaultshowerrors() function, but it only shows errors for the current element being validated. Is there a way to retrieve all error ...

How can we prevent components from rendering in React when their state or props have not changed?

I encountered a problem in my project where I have a main component that serves as the parent component of my project. Inside this main component, I have defined routes for other components and directly imported some components like a Side Navbar and Login ...

What is the best way to change the size of a QR code

My current HTML code: <input id="text" type="text"/> <div id="qrcode"></div> Previous version of JAVASCRIPT code: var qrcode = new QRCode("qrcode"); $("#text").on("keyup", function () { qrcode.makeCode($(this).val()); }).keyup().focus ...