"Utilizing AJAX to dynamically extract data from PHP and manipulate it in a multi-dimensional

Just starting out with JSON/AJAX and I'm in need of some help...

I have a PHP page that seems to be returning [{"id":"1"},{"id":2}] to my javascript. How can I convert this data into something more user-friendly, like a dropdown menu in HTML?

Here is the code snippet:

<script>
function displayData(str) {
   if (str=="") {
    var ajaxDisplay=xmlhttp.responseText;
    var res=ajaxDisplay.split("#");
    document.getElementById("ajax1").innerHTML=res[1];
     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 ajaxDisplay=xmlhttp.responseText;
    var res=ajaxDisplay.split("#");
    document.getElementById("ajax1").innerHTML=res[0];
     }
   }
   xmlhttp.open("GET","get.php?q="+str,true);
   xmlhttp.send();
 }
</script>

<div id='ajax1'><b>The ID dropdown will appear here.</b></div>

Answer №1

It seems like you've declared the variables twice, but I believe this explanation could be beneficial if you're seeking my opinion.

function displayUser(from, to)
{

if (from=="")
{
document.getElementById("show").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 arr=xmlhttp.responseText.split(":||:");//Used as a delimiter 
document.getElementById('show').innerHTML=arr[0];
     document.getElementById('show1').innerHTML=arr[1];
}
}
 xmlhttp.open("GET","some.php?q="+ from + "&w=" + to,true);
 xmlhttp.send();
 }

The PHP side is slightly different than usual, you'll require something similar to this.

 if  (!$result=mysqli_query($con,$sql))
 {
 die('Could not retrieve data: ' . mysqli_error($sql));
 }
 $test=mysqli_fetch_all($result,MYSQLI_ASSOC);//Crucial for fetching the array correctly for display
  $length=count($test);
  $half_length=$length/2;
 //echo $half_length."<br />";//used for testing
 $test12=array_chunk( $test,$half_length+.5,false);//true can also be used to preserve keys, worked in both ways for me 
 $test5=$test12[0];
 $test6=$test12[1];
 while(list($key,$val)=each($test5))
 {
 echo "<p>".$val[$colunm_name]."<p/><br />";//You can insert tags here to list your array in the desired format
  }
  echo ":||:";//Ensure the delimiter is outside of the loop
 while(list($key2,$val2)=each($test6) )
 {
 echo "<p>".$val[$colunm_name]."<p/><br />";//You can adjust the tags here as needed
 //echo "result_count_".count($test)."_-st<br/>";//used for testing 

Understanding this may take some time, but I trust it will be valuable to you.

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

Retrieving Data from all Rows in jQuery DataTables

Is there a way to copy all rows in jQuery DataTables into a JavaScript array by clicking the header checkbox? https://i.sstatic.net/57dTB.png I need to locate where jQuery DataTables store the HTML for the remaining page of rows so that I can manipulate ...

Using SVG Mask to enhance shape Fill

I am having trouble achieving the desired effect of darkening the fill of objects based on a specified gradient. Instead, when the mask is applied over the fill, it actually lightens it. I suspect that this issue arises from the color blending method being ...

Tips for resolving the issue of "Unable to assign property '_DT_CellIndex' to undefined in Jquery Datatable"

<?php if(mysqli_num_rows($result)>0) {?> <table class="table table-striped" id="example" align="center"> <tr> <thead> <th style=&quo ...

Unable to locate the appropriate constructor for com.eviware.soapui.support.XmlHolder using java.io.StringWriter as an argument

I am attempting to compare database values with API values using soapui in the same testcase but different steps. The first step involves retrieving a list from the database, while the second step involves comparing these values to the API. Database resp ...

Personalizing MaterialUI's autocomplete functionality

Trying to implement the material-UI Autocomplete component in my react app and looking for a way to display a div when hovering over an option from the list, similar to what is shown in this reference image. View example If anyone has any tips or suggest ...

Avoiding memory leaks in Node.js with Express framework

Dealing with memory leaks in nodejs (express.js) has been a challenge for me. I followed various tutorials online, but unlike the examples provided, identifying the source of the leak in my code has not been straightforward. Through the use of Chrome Dev T ...

Is there a way to trigger an interact.js event that will reset all draggables back to their original position at coordinates (0, 0)?

I am trying to figure out how to trigger an onmove or drag move event to reset the position of a draggable div to x:0 y: 0. Despite looking at various sources like help topics here and on interact.js main page, I haven't found the right solution yet. ...

fetching indexeddb information using the equivalent of a "WHERE IN (a,b)" query

I've been working on transitioning from websql to indexeddb, but I'm struggling to recreate the SELECT query: "SELECT * FROM tableA WHERE cid ='"+cid+"' AND hid IN("+hid+",1) ORDER BY hid DESC LIMIT 1"; function getMyData(e) { var ...

Are Css3 Transition and Transform properties dysfunctional in older versions of IE?

Snippet of HTML Code: <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="css/demo.css" /> </head> <body> <div></div> </body> </html> CSS Snippet: div { width: 100p ...

Issues with click events in the navigation menu

How can I make my menu close when clicking on other parts of my website, instead of opening? I know that I should use a click event for this, but when I implemented a click event, my menu encountered 2 unwanted problems: 1- Whenever I clicked on a menu i ...

JavaScript: Retrieving the names of children within a <div> element

Within my structure setup, there is a tower div with inner elements like this: <div class="tower"> <div class="E0">abc</div> <div class="GU">123</di </div> The challenge I am facing is that I need to access the in ...

"Utilizing jQuery's getJSON method in a session to fetch data

I have a code snippet that fetches the current number of likes on Facebook like this: $(document).ready(function() { $.getJSON('https://graph.facebook.com/<username>?callback=?', function(data) { var fb_count = data['likes ...

Encountering a type error when attempting to assign an interface to a property

In my Angular project, I am working with typescript and trying to assign the IInfoPage interface to some data. export interface IInfoPage { href: string; icon: string; routing: boolean; order: number; styleType: string; ...

Storing data in localStorage with the use of java, json, ajax, and html

I have been exploring the use of localStorage to transfer variables between pages. In my JavaScript, I am populating a List: output.add(0, accountGroup.getAccountId()); output.add(1, accountGroup.getLevel()); output.add(2, accountGroup.getGroupName()); ou ...

Executing a command to modify the local storage (no need for an API request) using redux persist in a React Native environment

Currently, I am facing an issue where I am attempting to trigger an action in Redux sagas to assign an ID to a local store: import { call, takeEvery } from 'redux-saga/effects'; import { BENEFITS } from '../actions/types'; function* ...

React application not functioning on localhost:3000 despite successful compilation with no errors, only displaying the title on localhost but failing to show any content

I recently started developing a new website with React. Everything was running smoothly on localhost until I made some changes, and now the homepage content is not displaying when I visit localhost:3000. I suspect there may be an issue with my routing or s ...

Transfer a script from a view to application.js in Rails: Guide and Instructions

After conducting some research, I found a code that worked well for me in the view. However, I am looking to transfer it to application.js so that I can utilize it in various forms. Another issue I encountered is having two scripts performing the same fun ...

Is there a method to store only a portion of the string object in async-storage?

Is there a way to save only part of the string object into async-storage? For example, if the "result.userPrincipalName" contains "[email protected]", I want to save only the "bob23". What is the best method to achieve this? await AsyncStorage.setIt ...

What are some strategies for exporting methods without resorting to the use of import * as ...?

Imagine having a file structured like this: // HelperFunctions.ts export const dateFormat = 'MM/DD/YYYY'; export const isEmpty = (input: string | null | undefined): boolean => { if (input == null) { return true; } if (!in ...

Tips on how to submit the ID of a span element with ajax

Can anyone help me retrieve the post ID of a span using Ajax? I have tried using alert($(this).attr("id")) and it works, but when I try to use Ajax it doesn't work. Any ideas why? $(".nav-item").click(function() { $.ajax({ ...