"Utilizing an AJAX request to dynamically fill form fields based on a database query as the selected value

I've searched through the questions here but haven't found a precise answer to my query :( However, I have managed to find something.

I have a form select field that I populate from a database query.

<select style="width:100%;" class="quform-tooltip chosen-select" id="company_select" name="company_select" title="Company Select" onChange="showUser(this.value)">
<option value="">Please select</option>
<?php
$userID = $user->getUserID();
$query = $user->database->query("SELECT * FROM tbl_businesses as business LEFT JOIN tbl_user_businesses as biz_user ON business.businessID = biz_user.businessID WHERE biz_user.userID ='$userID'");

while($row=$user->database->fetchArray($query))
{
    $bizID = $row['businessID'];
    $bizName = $row['businessName'];
    echo "<option value='$bizID'>$bizName</option>";
}?>
</select>

Currently, there are 2 other textboxes (which may increase in the future) that I want to populate when the value of the select box above is changed/selected.

<input id="company_name" type="text" name="company_name" value="" />
<input id="company_email" type="text" name="company_email" value="" />

So, I have an onchange function on my select box which is this:

<script>
function showUser(str)
{
if (str=="")
{
    document.getElementById("company_name").innerHTML="";
    return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        var data = JSON.parse(xmlhttp.responseText);
        for(var i=0;i<data.length;i++) 
        {
          document.getElementById("company_name").innerHTML += data[i].id + ' - ' + data[i].name + ' - ' + data[i].web;
        }
    }
}
xmlhttp.open("GET","formdata.php?q="+str,true);
xmlhttp.send();
}
</script>

And my formdata.php file is like this:

<?php
include("include/user.php");

$q = intval($_GET['q']);

$sql="SELECT * FROM tbl_businesses WHERE businessID = '".$q."'";

$result = $user->database->query($sql);
$info = array();
while($row=$user->database->fetchArray($result))
{
    $cID = $row['bussinessID'];
    $cName = $row['businessName'];
    $cWeb = $row['businessWebsite'];
    $info[] = array( 'id' => $cID, 'name' => $cName, 'web' => $cWeb );
}
echo json_encode($info);?> 

The ajax call is functioning correctly and returning the expected data, but now I need help populating the textbox values.

Could someone please assist me with this? I've spent a lot of time trying to figure it out. I'm not familiar with JavaScript/JSON, so I don't know where to start.

I'd like the company_name textbox value to be set to $cName and the company_email textbox value to be set to $cWeb.

Appreciate any assistance.

Luke

Answer №1

Here is the solution I used to solve the issue:

In my index.php file, I included both the JavaScript and form code.

JavaScript Code:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" type="text/javascript"></script>

<script>
function showUser(str)
{
if (str=="")
{
    document.getElementById("company_name").value="";
    return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        var data = JSON.parse(xmlhttp.responseText);
        for(var i=0;i<data.length;i++) 
        {
          document.getElementById("company_name").value = data[i].name;
          document.getElementById("company_email").value = data[i].web;
        }
    }
}
xmlhttp.open("GET","formdata.php?q="+str,true);
xmlhttp.send();
}
</script>

Form Code:

    <select style="width:100%;" class="quform-tooltip chosen-select" id="company_select" name="company_select" title="Company Select" onChange="showUser(this.value)">
<option value="">Please select</option>
<?php
$userID = $user->getUserID();
$query = $user->database->query("SELECT * FROM tbl_businesses as business LEFT JOIN tbl_user_businesses as biz_user ON business.businessID = biz_user.businessID WHERE biz_user.userID ='$userID'");

while($row=$user->database->fetchArray($query))
{
    $bizID = $row['businessID'];
    $bizName = $row['businessName'];
    echo "<option value='$bizID'>$bizName</option>";
}?>
</select>

<input id="company_name" type="text" name="company_name" value="" />
<input id="company_email" type="text" name="company_name" value="" />

Lastly, in my formdata.php file:

    $q = intval($_GET['q']);

$sql="SELECT * FROM tbl_businesses WHERE businessID = '".$q."'";

$result = $user->database->query($sql);
$info = array();
while($row=$user->database->fetchArray($result))
{
    $cID = $row['businessID'];
    $cName = $row['businessName'];
    $cWeb = $row['businessWebsite'];
    $info[] = array( 'id' => $cID, 'name' => $cName, 'web' => $cWeb );
}

echo json_encode($info);?>

This solution worked for me, thanks to charlietfl for the assistance!

I hope this explanation can help someone else too :)

Answer №2

If you're new to PHP and JQuery, it's essential to understand how they work together. Before diving into AJAX, take some time to familiarize yourself with JQuery, as it will greatly benefit your development process. JQuery offers handy methods like get and ajax for making asynchronous requests to the server.

Below is an example of using JQuery to retrieve JSON data from a server:

var title = '.....'
$.getJSON('getActivite.php?title=' + title, null,
        function(data){
            $("#currentId").val(data.ID);
            $("#nomActivite").val(data.Nom);
            $("#Description").val(data.Description);
            $("#DateEvent").val(data.Date);
});     

The line `$("#currentId").val(data.ID);` essentially means finding the element with the ID 'currentId' in the Document Object Model (DOM) and updating its value with the ID property obtained from the AJAX response.

On the PHP side of things, the script looked something like this:

<?php
    header('Content-Type: application/json');

    mysql_connect("localhost","root") or die (" NOPE . [" . mysql_error() . "]");
    mysql_select_db("garderie");

    $title  = $_GET["title"]; // receiving input from JSON call

    $query = "SELECT a.ActiviteID AS ActiviteID, rtrim(a.Nom) AS Nom, a.Description FROM activites a INNER JOIN ..... ";

    $result = mysql_query($query);       
    $ligne = mysql_fetch_array($result);

    $data = array(
        'ID' => $ligne["ActiviteID"],
        'Nom' => $ligne["Nom"],
        'Description' => $ligne["Description"],
        'Date' => $date
    );

    mysql_close();

    echo(json_encode($data));
?>

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

The deletion request using the form in Express is experiencing issues and not functioning properly

When attempting to delete data from a database using a form in node.js and express, I am encountering issues with the deletion process. It seems that there are only two methods available - get and post - and no specific delete method. router.js code rout ...

exploring methods to prevent flash of unstyled content (fouc)

Looking for a way to control CSS with a cookie: Want the user's style choice to stick until they change it or the cookie expires Avoid any default styling issues when the user returns Avoid using jquery, libraries, or frameworks Need compatibility w ...

Transitioning from using a jQuery get request to utilizing Vue.js

Looking to transition from JQuery-based js to Vue as a newcomer to JavaScript. Seeking guidance on making a get request and displaying the retrieved data. What approach would you recommend for this task? Here's the HTML snippet: <div> <di ...

What is the method for revealing elements with a click?

Every time I click on a button, the number 1 is displayed. However, upon clicking again, an error occurs stating that "push" is not a function. It appears that index 1 in the button array has been pushed into state.num, causing the type of state.num to cha ...

Problems with the functionality of the remote feature in Twitter Bootstrap Modal

Utilizing Twitter Bootstrap, I aim to retrieve HTML from another page and inject it into the modal on my current page. This led me to create a JavaScript function to facilitate this process. Within my 'index.php' file, I include the following: ...

"Confusion arises when handling undefined arguments within async.apply in the context of async

While working on my project, I encountered a strange issue with the async library. Some of my arguments end up being "undefined" in my function calls. For example (this is just simplifying my problem): var token; async.series([ function getToken (do ...

Displaying Stats.js inside a different canvas using ThreeJS

Just starting out with Three.js and wanted to test displaying the Stats.js in a small scenario. Check it out here Decided not to use modules for now, but followed similar code structure as in the examples: var stats = new Stats(); var renderer = ...

Employing passport-steam alongside sails-generate-auth

As I develop my SailsJS application, I am aiming for users to authenticate solely through Steam. I utilized `sails-generate-auth` to set up some boilerplate code with sails routes, but integrating passport-steam has proven challenging. If you are interest ...

To ensure the next line only runs after the line above has finished executing, remember that the function is invoked in HTML

my.component.html <button (click)="refresh()">Refresh</button> my.component.ts refresh() { let self = this; self.isRefresh = true; //1st time self.getfun().then(() => { self.isRefresh = false; ...

What are alternative methods for implementing autocomplete search for usernames from a database without relying on jQuery?

Searching through various exam resources, I have come across autocomplete solutions using jQuery. In my MySQL database, I have a collection of usernames. My objective is to create an autocomplete feature which pulls data from the database by utilizing PHP ...

Displaying a ReactJS component inside a map function by giving it a unique identifier

When I click on a button within a .map function, I want only the component I clicked on to be displayed and not repeated in all the others. Currently, the behavior of the component is as follows. https://i.sstatic.net/FxsGC.png Clicking on the three dots ...

Converting a file from a URL to a blob in PHP for use in JavaScript

Attempting to convert an image from a URL to a blob file that can be utilized in JavaScript, but encountering challenges. Is this achievable and if so, how? Current attempts include: // $request->location is the url to the file in this case an ima ...

Using the Trigger Method in a Vue JS Component with Sibling Components

Seeking assistance once again for a VueJS2 project. Currently, I have a setup with a parent component, along with child1 and child2. The scenario is that the form in child1 needs to receive data from child2, which acts as a table. When a checkbox on a row ...

Using interpolation brackets in Angular2 for variables instead of dots

I'm curious if Angular2 has a feature similar to the bracket notation in Javascript that allows you to use variables to select an object property, or if there is another method to achieve the same functionality. Here is the code snippet for reference ...

Uploading JSON object to server using Angular

I am currently utilizing json-server along with db.json. In the db.json file, there is an empty array "feedback":[] where users should be able to submit feedback from the application. However, I am facing an issue where nothing is being pushed into the se ...

Determine the number of distinct values in objects contained in a large JSON file using Python

My JSON files are quite large, with thousands of objects in a single array. The structure of the JSONs is as follows: { "alert": [ { "field1": "abc", "field2": "def", "field3": "xyz }, { "field1": null, "field2": null, "field3": "xyz", }, ...

A step-by-step guide on initializing and setting a cookie value with expiration

Below is the code I have added. Can someone please help me locate the bug? Here is the code snippet: $_SESSION['browser'] = session_id(); setcookie($expire, $_SESSION['browser'], time() + (60 * 1000), "/"); echo "Value is: " . $_COO ...

Efficient methods for transferring information between a main and pop-up page within angularjs

On my webpage, I have a button that opens a popup page. I need to figure out a way to transfer json data from the main page to the popup page. These two pages are running separate angular applications. Once the data is transferred, it will be updated base ...

The array is giving back null values

When making a POST request with AJAX and sending data in JSON format, everything seems to be working fine until trying to print out a specific index value from the decoded array, which returns null. What could be causing this issue? Here's the AJAX re ...

Is it possible to obtain the outcome from the MySQL database in JSON format?

Currently, I am utilizing Node.js along with MySQL for my project. My goal is to retrieve data from the MySQL database in JSON format. Can anyone provide me with some guidance on how to achieve this? ...