JS/PHP <--> embedded PHP HTML - javascript

I’m beginner to JS/PHP/MySQL development. I want to populate a select HTML element with table (nearly 4000 Records) from MySQL DB, relevant code is below.
<body onload="jsonload()">
<label>Beneficier Employee:</label>
<select item class = "BenEmpNo" name = "BenEmpNo" id = "BenEmpNo" onchange="jsEmpNoOnChg()" >
</select>
</body>
<script language="javascript" type="text/javascript">
function jsonload()
{
let jsSelBenEmpNo = document.getElementById("BenEmpNo");
let jsBenEmpNoDataAry;
jsSelBenEmpNo.innerHTML = "<option value='-select-'>-Select-</option>";
oReq = new XMLHttpRequest();
oReq.open('POST', "../php/oh-get_BenEmpNo.php", true);
oReq.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
oReq.onload = function () {
jsBenEmpNoAry = this.responseText.split('|');
for (let i = 1; i < jsBenEmpNoAry.length; i++)
{
jsBenEmpNoDataAry = jsBenEmpNoAry[i].split('~');
jsSelBenEmpNo.innerHTML += "<option value='" + jsBenEmpNoDataAry[0] +"'>" + "(" + jsBenEmpNoDataAry[0] + ")" + jsBenEmpNoDataAry[1] + "</option>";
}
}
oReq.send("parsparm=" + "|");
}
</script>
</html>
---- PHP ---
<?php
$sql = "select EmpNo, EngName from beneficiary";
$ResultSet = "";
require_once("oh-dbcon.php");
if ($result = mysqli_query($db_con, $sql))
{
while ($row = mysqli_fetch_row($result))
{
$ResultSet = $ResultSet . "|" . $row[0] . "~" . $row[1];
};
$ResultSet = $ResultSet . "~OK";
}else
$ResultSet = "ERROR Result (" . mysqli_error($db_con) . ")-(" . $sql . ")";
mysqli_close($db_con);
echo $ResultSet;
?>***
When I used pure JS (XMLHttpRequest) it takes long time (around 50s) to populate the select, during which the page is froze.
But when using HTML embedded PHP code, it is almost instantly populating the select element (below code).
<label>Beneficier Employee:</label>
<select item class = "BenEmpNo" name = "BenEmpNo" id = "BenEmpNo" onchange="jsEmpNoOnChg()" >
<option value = "-Select-">-Select-</option>
<?php
include("ohdadbcon.php");
$sql_phrase_ben = "select EmpNo, EngName from beneficiary";
$qry_result_ben = #mysqli_query($db_con, $sql_phrase_ben);
while ($row_ben = mysqli_fetch_assoc($qry_result_ben))
{
?>
<option value = "<?php echo $row_ben['EmpNo']?>" >
<?php
echo $row_ben['EngName'] . " | " . $row_ben['EmpNo'] ;
?>
</option>
<?php
}
mysqli_free_result($qry_result_ben);
?>
</select>
I want to use JS request only. Is there any other way or workaround for the slowness to this request?, or I’m doing something wrong here?

2 options... Tweak to only modify the DOM once:
let options = '';
for (let i = 1; i < jsBenEmpNoAry.length; i++)
{
jsBenEmpNoDataAry = jsBenEmpNoAry[i].split('~');
options += "<option value='" + jsBenEmpNoDataAry[0] +"'>" + "(" + jsBenEmpNoDataAry[0] + ")" + jsBenEmpNoDataAry[1] + "</option>";
}
jsSelBenEmpNo.innerHTML = options;
OR
You could also potentially generate the select or options list with PHP, and have THAT returned via AJAX. Then all the JS has to do is add/replace a single element in the DOM. This will move the entire loop to the server instead of the browser.
Though as others have mentioned, 4K items in a drop-down is going to be slow (not to mention very hard to use) just due to the size of the list. I would expect machines with low resources to get a bit choppy when the select is opened.

Related

How to display data value in real time without refreshing the page with PHP/Javascript?

This is a survey system. I have a dynamic dropdown that displays one column 'questiontitle' from my table database. How do I display its other columns 'Option_1 to Option_10' (I assumed the maximum options are 10), depending on the 'answer_type' column when it's clicked in real time without refreshing the page? Like if it the 'answer_type' is checkbox it will display it as checkbox and if it's radiobutton it will display radiobuttons. Here's my code of displaying the 'question_title' in the dropdown
$query=mysqli_query($con, "SELECT question.* FROM question LEFT JOIN category AS subcategory on subcategory.category_id = question.question_subcat WHERE question.question_category = $question AND (question.question_subcat IS NULL OR subcategory.category_id IS NOT NULL)");
echo "<b id='labelquestion_dropdown".$i."'>Question #". $i."</b>";
echo "<select id='question_dropdown".$i."' class='form-control-static' name='question_dropdowns".$i."'>";
echo "<option selected>"; echo "Select"; echo "</option>";
while($row=mysqli_fetch_array($query))
{
echo "<option value='$row[question_id]'>";
echo $row["questiontitle"];
echo "</option>";
}
echo "</select>";
echo "<br />";
And here's my database table.
Do some thing like this.
<script>
$.ajax({
url:'ajax.php?id=<?php $row['id']; ?>',
success:function(data){
if(data){
// do what ever you want to do
}
}
});
</script>
on AJAX.php
First you get record against this id that you send in ajax url.
prepare your desired result
Use Ajax Technology then do this in your JS
$(document).on('change','.dynamic-qst',function(){
// ajax question possible answers or rather ajax your database where id = question id
/* $.ajax({
url: 'getPossibleAnswers.php',
data: {id: $(this).val()},
success: function(response){
//insert the var output = '';
// to $('#possible-ans').html(output);
}
}) */
// assuming we had successfully ajax it and the response is
// for question 1 example
var response2 = {'answer_type':'checkbox', 'option_1':'Cellphone', 'option_2':'Computer', 'option_3':'Laptop', 'option_4':'', 'option_5':'', 'option_6':'', 'option_7':'', 'option_8':'', 'option_9':'', 'option_10':''};
// for question 2 example
var response = {'answer_type':'radio', 'option_1':'Sushi', 'option_2':'Maki', 'option_3':'Sashimi', 'option_4':'Teriyaki', 'option_5':'Misono', 'option_6':'', 'option_7':'', 'option_8':'', 'option_9':'', 'option_10':''};
var output = '', x;
for(x = 1; x <= 10 ; x++)
{
var cur_ans = eval("response.option_" + x);
if(response.answer_type == 'checkbox')
{
if(cur_ans != '')
{
output += '<input type="checkbox" name="ans" value="' + cur_ans + '">' + cur_ans;
}
}
else if(response.answer_type == 'radio')
{
if(cur_ans != '')
{
output += '<input type="radio" name="ans" value="' + cur_ans + '">' + cur_ans;
}
}
}
$('#possible-ans').html(output);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="dynamic-qst">
<option value selected disabled>-- Select One --</option>
<option value="1">What gadget do you usually use?</option>
<option value="2">What is your favorite food?</option>
</select>
<div id="possible-ans"></div>

Get data from Database Using Ajax and PHP and Return Result as Dropdown list

I have the idea of what i wanted but need assistance on how to get it done.Below is the scenerio: I have a two dropdwon. The First dropdown is fetched from the DB, which works fine. At the change event of the first dropdown,the system should go to the Database, and fetch the result into the next dropdown. see what I have done so far for assistance:
JQUERY SECTION
<script type="text/javascript" src="includes/scripts/newJquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#locate").change(function(){
var selectedloc = $("#locate option:selected").val();
$.ajax({type: "POST",url:"process-loc.php",data:{loca:selectedloc}}).done(function(data){
var ans=jQuery.parse(data);
//using php-mysql before
var ps = ans.res;
$("#subloc").html(ps);
});
});
});
</script>
FrontEnd(HTML)
<tr>
<th>Primary Location:</th>
<?php
$result = mysqli_query($connection,"SELECT * FROM tab_location");?>
<td>
<select name="locate" class="form-control" id="locate">
<option>Select Main Location</option>
<?php while($rw = mysqli_fetch_array($result)){ ?>
<option value="<?php echo $rw['location_name'];?>"><?php echo $rw['location_name'];?></option>
<?php };?>
</select>
</td>
</tr>
<tr>
<th>Sub Location:</th>
<td id="subloc"></td>
</tr>
Process-loc.php
if(isset($_POST["loca"])){
include 'includes/session.php';
include 'includes/db_connection.php';
include 'includes/functions.php';
$main = $_POST["loca"];
$gets = "SELECT * FROM tab_fltlocation WHERE mainloc='".$main."'";
$get = mysqli_query($connection,$gets);
$gt = mysqli_fetch_array($get);
//$nos= $gt['opsNo'];
if(mysqli_num_rows($get)>=0)
{
echo json_encode(array("res"=>$gt));//or do a dropdown using <select name='subloc'><option value=$gt['loc']>$gt['loc']</option></select>
}else{
echo json_encode(array("res"=>"0"));
}
}
?>
This is what I wants to be displayed on the Front End page for the use:
$gt['loc']
How can I achieve this.
$query = "
SELECT
tariff_name
FROM tariff_setting";
$result = mysqli_query($this->_connection, $query);
while ($row = mysqli_fetch_assoc($result))
$response[] = $row['tariff_name'];
}
$tarrifList = json_encode($response);
// $tarrifList is the response and sent it in json encode format and decode on ajax success
// Javascript Process
var obj = JSON.parse(resdata);
var areaOption = "<option value=''>Select State</option>";
for (var i = 0; i < obj.length; i++) {
areaOption += '<option value="' + obj[i] + '">' + obj[i] + '</option>'
}
$("#patientSelectState").html(areaOption);
You can change your AJAX processor to do this:
Process-loc.php
/* Above code the same */
if(mysqli_num_rows($get)>=0) {
$out = '<select id="selSubLoc"><option value="">Choose One:</option>';
foreach($gt AS $loc){
$seld = ($_POST['loca'] == $loc) ' selected' ? : '' ;
$out .= '<option value="' .$loc. '" ' .$seld. '>' .$loc. '</option>';
}
$out .= '</select>';
}else{
$out = 0;
}
echo $out;
And change your front-end code's AJAX routine to be like this:
$.ajax({
type: "POST",
url:"process-loc.php",
data:{loca:selectedloc}
}).done(function(recd){
$("#subloc").html(recd);
});
The data received back from PHP will be in HTML format unless you use dataType: to change it, so you can build the HTML over on the PHP side and then just plop it into the #subloc table cell.
On the event of the first box call the function containing the ajax which would retrieve information from the database. This ajax call will get data according to the first input.
Now query your database and echo the results in a foreach loop(you can make a tag there only).
In the ajax 'success:' catch the data and display it.
//from the database
foreach ($info as $product)
{
echo "<option value=".$product['childsticker_id'].">".$product['name']</option>";
}
//ajax call page
success: function(result)
{
$("#states").html(result);
}
http://www.9lessons.info/2010/08/dynamic-dependent-select-box-using.html

InnerHTML creation issue, doesn't load in the correct order, possible processing issue

I am using a series of JavaScript functions to load information from a database and use the information in the creation of a thumbnail image and a radio button corresponding to each 'comic' record that the user has theoretically created and uploaded to the database.
My problem arises when the HTML tags are created. While the image and button are both created correctly with no errors, they are outputted in the wrong order. They should be loaded alphabetically by 'comicName', which is represented in the radio button's text, for example:
Comic A (img)
Comic B (img)
Comic C (img)
I have checked the array 'arr' of 'comicID's that determine the order of outputted html objects at several stages in the code using window alerts, and at all stages the comics are ordered correctly in the array, even when outputting incorrectly. There is an odd circumstance when I have quite a lot of alerts opening up at once; the items DO in fact output in the correct order. (In this case there were around six 'comicID's in the array and each ID had an alert pop up for it at three different times).
I therefore think that the code is creating them in the correct order and trying to output them as such, but some items may be loading sooner than others due to image size or some other processing reason. If this is indeed the case how would I go about sorting it to make sure they load correctly?
Thanks in advance.
Javascript:
<script>
// Loads the user's comic list from the database.
function loadComic()
{
var xmlhttp = new XMLHttpRequest();
var getID = '<?php echo $_SESSION["userID"]; ?>';
var url = "loadCom.php?userID="+getID;
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
loadComicJSON(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
// JSON parsing for 'loadComic'.
function loadComicJSON(response)
{
var arr = JSON.parse(response);
var i;
var out = "";
document.getElementById("loadList").innerHTML="";
if (arr.length == 0)
{
document.getElementById("uploadTagID").innerHTML="";
document.getElementById("uploadTagID").innerHTML="No Comics Uploaded";
document.getElementById("btnDeleteComic").disabled=true;
document.getElementById("btnEditComic").disabled=true;
document.getElementById("btnDelAllComics").disabled=true;
$("#listButtons").hide();
}
else
{
document.getElementById("loadList").innerHTML="<br>";
for(i = 0; i < arr.length; i++)
{
tempID = (arr[i].comicID);
getCoverJSON(arr, i, tempID);
}
document.getElementById("uploadTagID").innerHTML="";
document.getElementById("uploadTagID").innerHTML="<u>Uploaded Comics</u>";
document.getElementById("btnDeleteComic").disabled=false;
document.getElementById("btnEditComic").disabled=false;
document.getElementById("btnDelAllComics").disabled=false;
$("#listButtons").show();
}
}
</script>
<script>
// Function to prevent $.get from technically being inside a loop (fixes an issue when loading more than one item).
function getCoverJSON(arr, i, tempID)
{
$.get("getCover.php", {'comicID': tempID}, function(result)
{
getCover(result, arr, i);
}
);
}
</script>
<script>
// Function to create a list of radio buttons and associated images from a user's comic list.
function getCover(result, arr, i)
{
var buildLine = document.getElementById("loadList").innerHTML;
if (result[0].pageLocation == "nocvr")
{
var out = "<hr><br><input name='comicList' type='radio' id='" + arr[i].comicID + "' value='" + arr[i].comicID + "'>" + arr[i].comicName + " </option><br><br><img name = '" + ('cm' + arr[i].comicID) + "' id='" + ('com' + arr[i].comicID) + "' onclick='resizeThumb(this)' height='100px;' src='assets/img/nocvr.jpg'><br><br>";
document.getElementById("loadList").innerHTML="";
document.getElementById("loadList").innerHTML=(buildLine + out);
}
else
{
var getImg = result[0].pageLocation;
var out = "<hr><br><input name='comicList' type='radio' id='" + arr[i].comicID + "' value='" + arr[i].comicID + "'>" + arr[i].comicName + " </option><br><br><img name = '" + ('cm' + arr[i].comicID) + "' id='" + ('com' + arr[i].comicID) + "' onclick='resizeThumb(this)' height='100px;' src='" + getImg + "'><br><br>";
document.getElementById("loadList").innerHTML="";
document.getElementById("loadList").innerHTML=(buildLine + out);
}
}
</script>
PHP (loadCom.php):
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$user = $_GET['userID'];
include_once('includes/conn.inc.php');
$query = ("SELECT comicID, comicName FROM comic WHERE userID = '$user' ORDER BY comicName ASC");
$result = mysqli_query($conn, $query);
$outp = "[";
while($rs = $result->fetch_array(MYSQLI_ASSOC))
{
if ($outp != "[")
{
$outp .= ",";
}
$outp .= '{"comicID":"' . $rs["comicID"] . '",';
$outp .= '"comicName":"' . $rs["comicName"] . '"}';
}
$outp .="]";
$conn->close();
echo ($outp);
?>
PHP (getCover.php)
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
if (isset($_GET["comicID"]))
{
include_once('includes/conn.inc.php');
$checkID = $_GET["comicID"];
$query = ("SELECT pageLocation FROM page WHERE comicID = '$checkID' ORDER BY pageNum");
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) == 0)
{
$outp = '[{"pageLocation":"nocvr"}]';
echo ($outp);
}
else
{
$outp = "[";
while($rs = $result->fetch_array(MYSQLI_ASSOC))
{
if ($outp != "[")
{
$outp .= ",";
}
$outp .= '{"pageLocation":"' . $rs["pageLocation"] . '"}';
}
$outp .="]";
$conn->close();
echo ($outp);
}
}
else
{
$checkID = null;
echo "Error. No comic found.";
}
?>
You're using AJAX calls, which are by default asynchronous - there is NO guarantee whatsoever as to what order the responses come back in. e.g. if you have requests A,B,C, then the response to A might come 20 minutes after the C response, because someone's backhoe severed an optic cable somewhere and caused the A request to take a much longer path to the server than C's.
You can switch to synchronous, but that will lock the browser while the requests are pending, which is a bad user experience.
You'd be better off simplifying the code. Instead of doing one ajax call per fetch, you should have ONE call, and send over all of the ids you want to fetch.
In other words, instead of
$.get('getCover.php', {id:1});
$.get('getCover.php', {id:2});
$.get('getCover.php', {id:3});
switch your code over to
$.get('getCover.php', {ids:[1,2,3]});
Now it's one single ajax request, one single json response, and within that response, you can order your data however you want.

php, mysql dynamicaly dropdown using jquery

i am trying to create a dynamic dropdown menu for my website to add address like state, city, area and postcode. i am using code is working when i try one by one preview in live browser but it does not work when i try to use java-script its not show the data in dropdown menucan you plese tell me where i am making mistake
it is index.php
<head>
</head>
<script src="scripts/jquery.js" type="text/javascript"></script>
<script src="scripts/scripts.js" type="text/javascript"></script>
<body>
<h1>address</h1>
<hr/>
<label>please select state</label>
<select id="slctstate"></select>
<br />
<br />
<label>please select city</label>
<select id="slctcity"></select>
</body>
</head>
it is script.js
$(document).ready(function() {
$.getJSON("get_stat.php", success = function(data){
var options = "";
for(var i = 0; i < data.lenght; i++)
{
options += "<option value='" + data[i].toLowerCase() + "'>" + data[i] + "</option>";
}
$("#sltstate").append(options);
});
$("#slctstate").change(function(){
$.getJSON("get_city.php?state=" +$(this).value(), success = function(data){
var options = "";
for(var i = 0; i < data.lenght; i++)
{
options += "<option value='" + data[i].toLowerCase() + "'>" + data[i] + "</option>";
}
$("#slctcity").append(options);
});
});
});
it is get_state.php
<?php
require "Connections/dbopen.php";
$query = "SELECT state_name FROM states";
$data = mysqli_query($conn, $query);
$states = array();
while ($row = mysqli_fetch_array($data))
{
array_push($states, $row["state_name"]);
}
echo json_encode($states);
require "Connections/dbclose.php";
?>
and hers is get_city.php
<?php
require "Connections/dbopen.php";
if(isset($_GET["$state"]));
{
$state = $_GET["state"];
$query = "SELECT city_name FROM city
INNER JOIN states ON
city.state_id=states.state_id
WHERE state_name LIKE '{$state}'";
$data = mysqli_query($conn, $query);
$city = array();
while ($row = mysqli_fetch_array($data))
{
array_push($city, $row["city_name"]);
}
echo json_encode($city);
require "Connections/dbclose.php";
}
?>
but at the final step i did not get any value in my drop down can any one please help me thanks
You might want to make the following changes:
change lenght to length
change success = function(data) to function(data)
change isset($_GET["$state"]) to isset($_GET["state"])
refer to http://php.net/manual/en/pdostatement.fetch.php for fetching data in an easier way(optional if the first 3 changes dont work)

Pull dropdown Options from a DB based on selection in another dropdown

I have two dropdown lists as a part of a form I'm creating, both of which have options that are being pulled from a mysql database. I would like the options in the second dropdown to change based on the selection in the first dropdown. I know how to do this using Javascript when the second list is static, but I would like both dropdowns to dynamically pull from the database. Below is the HTML and Javascript I'm currently using. Any ideas would be great.
HTML:
<form>
<label for="org_name">Organization Name:</label>
<select id="org_name" name="org_name" onchange="configureDropDownLists(this,'submitter_name')">
<option value="empty"> </option>
<?php
mysql_connect("database", "username", "password") or die(mysql_error ());
mysql_select_db("databaseName") or die(mysql_error());
$query = "SELECT * FROM Table";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
echo "<option value='" . $row['org_name'] . "'>" . $row['org_name'] . "</option>";
}
mysql_close();
?>
</select>
<label for="submitter_name">Request Submitted By:</label>
<select id="submitter_name" name="submitter_name">
<option value="empty"> </option>
</select>
<input type="Submit" value="Submit">
</form>
Javascript:
function configureDropDownLists(org_name,submitter_name) {
var org = new Array('Submitter 1', 'Submitter 2');
switch (org_name.value) {
case 'org':
document.getElementById(submitter_name).options.length = 1;
for (i = 0; i < org.length; i++) {
createOption(document.getElementById(submitter_name), org[i], org[i]);
}
break;
default:
document.getElementById(submitter_name).options.length = 1;
break;
}
createOption(document.getElementById(submitter_name), 'Other', 'Other');
if (org_name.value === 'empty') {
document.getElementById(submitter_name).options.length = 1;
}
}
function createOption(ddl, text, value) {
var opt = document.createElement('option');
opt.value = value;
opt.text = text;
ddl.options.add(opt);
}
As suggested, AJAX was the answer. For anyone curious who comes across this, below is the solution I came up with. I left the HTML unchanged other than removing onchange="configureDropDownLists(this,'submitter_name')" from the first dropdown. Instead of the above Javascript, I used the below AJAX and PHP. Works really nicely.
JQuery:
$(document).ready(function() {
$("#org_name").on("change", function() {
var orgName = document.getElementById("org_name").value;
$.post('admin_list.php', { org: orgName }, function(result) {
$('#submitter_name').html(result);
}
);
});
});
and the referenced PHP page:
<?php
mysql_connect("database", "username", "password") or die(mysql_error ());
mysql_select_db("databaseName") or die(mysql_error());
$org_name = $_REQUEST['org'];
$query = mysql_query("SELECT * FROM Table WHERE user = '$org_name'");
while($row = mysql_fetch_array($query)){
echo "<option>" . $row['admin_first_name'] . " " . $row['admin_last_name'] . "</option>";
}
mysql_close();
?>
Sounds like you need some AJAX to pull your data from the database, format on the server side (JSON will likely be easiest to work with), then use a callback function in Javascript to populate the second drop down based on the JSON data received.

Categories

Resources