What is the most effective way to transfer an array from one PHP file to a different JavaScript file?

Utilizing AJAX to send a request to another php page and retrieve the result of a query, I originally used xmlhttprequest to pass the php logic along with the query information. However, I wanted to separate the presentation logic from the actual code logic by storing the query results in an array and passing it down to my javascript function through ajax.

My goal is to populate a drop-down list with the contents of this array. Despite attempting json encode, I am facing some difficulties.

Here is the code for the requested php page:

<html>
<head>
</head>
<body>
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);


$con = mysqli_connect('*******','********','******','****');
if (!$con) {
    die('Could not connect: ' . mysqli_error($con));
}

$j = mysqli_real_escape_string($con, $_GET['j']);

mysqli_select_db($con,"4h");
$sql="SELECT nombreClub FROM club4h WHERE oficinaLoc LIKE '%".$j."%'";
$result = mysqli_query($con,$sql);

while($row = $result->fetch_array()) {
    $response[] = $row;
}

file_put_contents('getnombre.php',json_encode($response));

mysqli_close($con);
?>
</body>
</html>

Below is my javascript function:

function loadDoc(url, cfunc, sel){
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function(){
        if (xhttp.readyState == 4 && xhttp.status == 200){
            cfunc(xhttp);
        }
    }
    xhttp.open("GET", url +sel, true);
    xhttp.send();
}

function selClub(xhttp) {
    document.getElementById("nombreClub").style.display = "inline";
    var optData = <?php file_get_contents('getnombre.php'); ?>;
    var newClub = document.getElementById("addClub");
    newClub.type = "text";
    document.getElementById("addOption").style.display = "inline";
            $("#addOption").click(function(){
            $("#nombreClub").append('<option value="' + $("#addClub").val() + '">' + $("#addClub").val() + '</option>');
            $("#nombreClub").last().focus;
            });
}

I trigger this function with an onchange event when a user selects a value from a previous drop-down list. The options in this specific drop-down list are populated based on the selection made. While I understand how to add options to the list, I am facing challenges in transferring data from the php page to javascript without resorting to directly echoing html elements.

Answer №1

Allow me to guide you through the process...

Using PHP to Retrieve Data

To retrieve and return your data in JSON format, PHP offers the convenient json_encode() function.

// Implement your database query code to create an array
$query_results = array(
    array('agent'=>'Agent 1'),
    array('agent'=>'Agent 2'),
    array('agent'=>'Agent 3')
);

return json_encode($query_results);

Create a Select Element in HTML Page

<select name="agenteExt" id="agenteExt"></select>

JavaScript Functionality

An AJAX function for retrieving data

function loadDoc(url, callback){
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function(){
        if (xhttp.readyState == 4 && xhttp.status == 200){
            if( callback ) callback(xhttp)
        }
    }
    xhttp.open("GET", url, true);
    xhttp.send();
}

A function to populate your html element with retrieved data

function fillOptions(){
    loadDoc('your-query-page.php', function(xhttp){

        // Convert received JSON data into a JavaScript object
        var data = JSON.parse(xhttp.responseText);

        // Access the `<select>` element
        var el = document.getElementById('agenteExt');

        var html = '<option>Make a selection</option>';

        // Loop through data to generate `<option>` elements for the select
        for(i = 0; i < data.length; i++){
            html += '<option value="'+data[i].agent+'">'+data[i].agent+'</option>'
        }

        // Update the select element with the new options
        el.innerHTML = html;
    }
}

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

I am attempting to create basic animations using css, but I'm having some trouble

Currently, I am attempting to add animation to a css div without including the top property in the original div style. I omitted it because I wanted to delay the animation, so I placed it within the @keyframes property. However, the element disappears afte ...

Creating a bordered triangle using only CSS

Looking to create a message holder with a triangular tip bordered shape? I've successfully crafted the tip using two triangles: #triangle-border { width: 0px; height: 0px; border-style: solid; border-width: 0 100px 80px 100px; bor ...

Showing local storage on a webpage using Jquery

I have encountered an issue where I can successfully add and remove items from local storage, but the added item does not display on my HTML page. The expected behavior is that when an item is added to local storage, it should be visible on a favorites pag ...

What is the best way to execute an ajax call in a Ruby on Rails application?

Hey there, I am just starting to learn Ruby on Rails and I need help with making an ajax request. Here is the JavaScript code I have: $(document).ready(function(){ $(".form_submit").click(function() { var apiid = $('#apiid').val(); ...

transferring information between two html pages using javascript

Although this question has been raised multiple times, I have gone through the answers and attempted various solutions, however, my code is still not functioning correctly. Below are my working files : my_app -index.html -task1 -index.html I ...

Having trouble rendering JSON encoded data in a JqPlot Chart within a PHP script

I've spent the past few days scouring through Stack Overflow and various other websites, but I haven't been able to find a solution to my specific issue. Even the book 'Create Web Charts with JqPlot' by Fabio Nelli didn't provide t ...

Is there any way to extract the source files from a compiled Electron application?

Is there a way to extract the contents of a .app Application developed using Electron for Mac OS? I'm eager to explore the underlying source files, but I'm not familiar with the procedure to access them. Any assistance would be greatly appreciate ...

React with TypeScript: The struggle of getting LocalStorage to work

Currently, I am dealing with persistence in a todo application developed using React and TypeScript. To achieve the desired persistence, I have implemented localStorage. Allow me to share some code snippets: const [todos, setTodos] = useState<todoMod ...

Is there a way to adjust the contents of an iframe to match the dimensions of the iframe itself?

I am trying to adjust the width of an iframe to 60%, regardless of its height. Is there a way to "zoom in" on the contents of the iframe to fit the width, so that I can then set the height based on this zoom level? I haven't been able to find any solu ...

Swap out the HTML button element for text once the form is submitted

On the main page, I have a button that opens a modal when clicked. Inside the modal, there is a form with a submit button that closes the modal and returns to the main page. After closing the modal, I want to change the HTML button on the main page to plai ...

Obtain the content from a dynamically generated dropdown menu and incorporate it into a separate file

My website features two dropdown menus - one for selecting countries and another for cities. The country menu is populated with data from a database, and once a country is selected, the city dropdown is dynamically filled with corresponding cities using a ...

Retrieving information from dictionary in swift version 4

Currently, I am utilizing an API and trying to display its data in a table view. import UIKit import Alamofire class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! @IBOu ...

Implementing JSON Parsing to dynamically add markers on Google Maps by passing a tag in the URL

There is a URL where I need to parse some information, including latitude and longitude, and display them on a map. Parsing and adding markers to the map seem to work fine. However, the markers are not being displayed, only the map itself. Initially, I tho ...

Text located incorrectly beside image within container box

Below is the HTML code that defines a box containing title text and an image. <div id="about"> <div id="title"> <h3><b>About</b></h3></div> <div id="text"><p>Text</p></div> <div id="img ...

You cannot utilize Lesson as a JSX Component in Next JS TypeScript

Below is my updated page.tsx code: import Aspects from '@/components/Aspects'; import FreeForm from '@/components/FreeForm'; import Lesson from '@/components/Lesson'; import React from 'react'; import { Route, Route ...

Architecture of Zend_Queue database

Currently, my email queuing and sending system utilizes Zend_Queue (http://framework.zend.com/manual/en/zend.queue.adapters.html) I am wondering if there is a method to change the default table names in Zend_Queue_Adapter_Db. The default names "queue" and ...

Using Sequelize to Include Model Without Specifying Table Name

I am new to Sequelize I am facing an issue with "Nested Eager Loading" I have 2 tables with a one-to-many relationship Comment Table User Table This is the code I am using for the query Comment.findAll({ include: [User] }) The result I got was ...

The Dropdownlist jQuery is having trouble retrieving the database value

Within my database, there is a column labeled Sequence that contains integer values. For the edit function in my application, I need to display this selected number within a jQuery dropdown list. When making an AJAX call, I provide the ProductId parameter ...

Combining multiple storageStates in a playwright context for efficient loading

I am trying to load multiple storageStates into a single context in playwright, but I am facing some issues. When using the following code: const context = await browser.newContext({ storageState: "telegram.json",storageState: "google. ...

Design an interactive div element that allows users to modify its content, by placing a span

Here is an example of the desired effect: ICON LINE - 1 This is some sample text inside a div element and the next line should begin here ICON LINE - 2 This is some sample text inside a div element a ...