Trigger JS function on pageload when populating select box from database - javascript

I have the following js script that triggers onChange of the select box below.
It then retrieves data from a table and returns some input fields populated with the data (using PHP code below). Then saves the data.
This part works fine.
However, if I run the script again, and it populates the selected option from DB and shows as a selected option, but it does not display the populated input fields returned from the PHP code/DB query since I am not triggering the onChange again.
I tried to add 'window.onload = showAgentOne;' under the JS for the onChange function, assuming it would see the value in (str) from the select box, but I am probably missing something as it does not work.
New to JS - I hope this makes sense.
JS:
function showAgentOne(str) {
if (str == "") {
document.getElementById("agent1").innerHTML = "";
return;
}
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("agent1").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "user_agent1.php?q=" + str, true);
xmlhttp.send();
}
window.onload = showAgentOne; // trigger function on pageload - not working
HTML:
<select name="narid" onchange="showAgentOne(this.value)" class="form-control">
<option selected="selected" disabled value="">select agent</option>
<?php
$sql = "select last_name, first_name, active, nrds_id from ft_form_2 ORDER BY last_name";
$sql_result = mysqli_query($mysqli,$sql);
while ($row = mysqli_fetch_array($sql_result)) }?>
<option value="<?php echo $row[" nrds_id "]; ?>" <?php if($narid_agent1==$ row[ "nrds_id"]) { echo ' selected '; } ?> >
<?php echo strtoupper($row["last_name"]) . ' > ' . $row["first_name"] . ' ' . $row["last_name"] . ' ['.$active.']'; ?>
</option>
<? } ?>
</select>
<div id="agent1"></div>
PHP (user_agent1.php) ------------------------- $q=$_GET["q"]; $sql="SELECT pay_to_name,nrds_id FROM ft_form_2 WHERE nrds_id = $q"; $result = mysqli_query($mysqli,$sql); while($row = mysqli_fetch_array($result)) { ?>
<input type="text" name="narid_agent1" value="<?php echo $row['nrds_id']; ?>">
<input type="text" name="pay2_agent1" value="<?php echo $row['pay_to_name']; ?>">
<?php } ?>

'window.onload = showAgentOne;' is a good try but it is expecting a str param, otherwise it returns and do nothing. That's why nothing happens.
You will have to try something like
window.onload = function (event) {
let str = 'ADD_YOUR_VALUE_HERE';
showAgentOne(str);
}
But I can't help you with what str should be.

Related

Dynamically Update drop down value 2 according to selection of drop value 1 inside a modal in PHP

I have two drops downs on my page.
I have a drop directly taken from DB.
I have a drop totally depends on the selection from dropdown 1 and taken from db.
I have both of these drop-downs inside a modal. I am not sure how to insert the javascript variable to dropdown 2.
Here is my code:
Dropdown 1:
<select class="selectpicker form-control mt-2" id="schoolname" name="schoolname" data-width="" title="School" onChange=reload(this.form)>
<?php
$prod_query = "SELECT * FROM my_school_class";
$prodresult = mysqli_query($DBconnect, $prod_query);
while($r = mysqli_fetch_array($prodresult))
{
if (!empty($schoolName) && $schoolName == $r['schoolName'])
{
$selected = 'selected="selected"';
}
else
{
$selected = '';
}
echo "<option ".$selected." value=".$r['schoolName'].">".$r['schoolName']."</option>";
} ?>
</select>
Dropdown 2:
<select class="selectpicker form-control mt-2" id="classname" name="classname" data-width="" title="class">
<?php
$prod_query = "SELECT * FROM my_class WHERE school="JAVASCRIPT VARIABLE SHOULD COME HERE";
$prodresult = mysqli_query($DBconnect, $prod_query);
while($r = mysqli_fetch_array($prodresult))
{
echo "<option ".$selected." value=".$r['className'].">".$r['className']."</option>";
} ?>
</select>
Javascript writing correctly to console:
<script language=JavaScript>
function reload(form)
{
var val=form.schoolname.options[form.schoolname.options.selectedIndex].value;
console.log (val);
}
The above variable prints the selection correctly on the console in chrome.
And I have all these inside a modal. Let me know how to fix this?
Thanks!
use this using JQUERY
index.html
$(document).on('change','#schoolname',function(){
var schoolname = $('#schoolname').val();
$('#classname').empty();
$('#classname').append('<option value="" disabled selected>Choose your option</option>');
$.ajax({
url: 'GetClassname.php',
type: 'POST',
data: {schoolname : schoolname },
success: function(data) {
$('#classname').append(data);
}
});
});
GetClassname.php
<?php
include('../config.php');
$schoolname = $_POST['schoolname'];
$prod_query = "SELECT * FROM my_class WHERE school='$schoolName'";
$prodresult = mysqli_query($DBconnect, $prod_query);
while($r = mysqli_fetch_array($prodresult)) {
echo "<option ".$selected." value=".$r['className'].">".$r['className']."</option>";
}
?>
Call ajax like this (pure vanilla js)
function reload(form)
{
const id = form.schoolname.options[form.schoolname.options.selectedIndex].value
var xhr = new XMLHttpRequest();
xhr.open('POST', '/fetch_second.php/');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
xhr.onload = function() {
if (xhr.status === 200) {
const data = xhr.responseText
let elem = document.querySelector( 'css-selector (#container id)')
elem.appendChild(responseText)
}
else if (xhr.status !== 200) {
console.log('Request failed. Returned status of ' + xhr.status);
}
}
xhr.send(encodeURI('id=' + id))
}
and change
this css-selector (#container id) to your container id or className from your modal
And in your fetch_second.php
$schoolName = $_POST['id'];
$prod_query = "SELECT * FROM my_class WHERE school='$schoolName'";
$prodresult = mysqli_query($DBconnect, $prod_query);
while($r = mysqli_fetch_array($prodresult)) {
echo "<option value=".$r['className'].">".$r['className']."</option>";
}

Retrieving large data amount as datalist from Remote PC

I have a simple HTML page that allows the user to select the amount of fields to enter information. Once the user selects a number, a Javascript onchange method is called that sends the parameter to a PHP page where data is retrieved from a database and stored in a datalist, that is dynamically appended to the HTML page.
When I access this function on the host PC, everything works perfectly. However, when I access this from a remote client, the input fields dont generate automatically.
Here is the code:
<html>
<head>
<script>
function GetInfo(str) {
if (str == "") {
document.getElementById("items").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("items").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","../php/Return-List.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form method="POST" action="../php/Submit.php">
<label>Number of Items</label>
<input type="number" name="numberofitems" onchange='GetInfo(this.value)'>
<br/>
<div id="items"></div>
<input type="submit" value="Go" />
</form>
</body>
</html>
PHP:
<?php
include("connection.php");
if($conn->connect_error) {
die("Connection Failed");
} else {
$items = $_GET['q'];
$fields = "";
$query = mysqli_query($conn,"SELECT name, desc FROM ItemTB");
for($i=1; $i<=$items ; $i++) {
$fields .= "<label>Input</label>
<input list='items' name='items[]' />
<datalist id='items'>";
while($row = mysqli_fetch_array($query)) {
$fields .= "<option value='" . $row['name'] . " | " . $row['desc'] . "'> " . $row['desc'] . "</option>";
}
$fields .= "</datalist>";
}
echo $fields;
}
?>
I have tried using relative and fixed locations in the JavaScript, and limiting the results to 500. Limiting the database results works, and it is important to note that the table returns upwards of 170 000 results. This seems to be the issue here.
How do I retrieve the entire dataset? Is there a way to do this more efficiently, to pack all data without lag?
Thanks in advance.

Fetching column value from DB for a Select Option

I've a drop-down list for selecting an Id on a php page, the values of which is getting fetched from the database(1st Column).
There's a text-field next to the drop-down in which I want to display the name of the member (2nd Column) from the database.
The code is below -
<?php
include ('connection.php');
$query = "SELECT Member_id FROM member_db ORDER BY Member_id ASC";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn)."[".$query."]");
?>
<Select id="st_id" placeholder="Enter Member id" name="ist_id" required class="styled-select green semi-square onChange="showMember(this.value)"">
<option selected ="true" disabled="disabled">Select Member Id</option>
<?php while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)){?>
<option value=" <?php $row['Member_id']; ?> ">
<?php echo $row['Member_id'];?>
</option>
<?php }?>
</Select>
<input style="min-height:30px" type="text" id="st_name" placeholder="Member name" name="ist_name" disabled/>
The JavaScript code I'm calling is this -
function showMember(str) {
if (str == "")
{
document.getElementById("txtHint").innerHTML = "";
return;
}
else {
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 (this.readyState == 4 && this.status == 200)
{
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","getMember.php?q="+str,true);
xmlhttp.send();
}
}
The getMember.php is another php file in which I'm firing a query to get the Member_name based on the value of Member_id.
But the problem is that somehow, that onChange, the page doesn't call the showMember() function.
1) Missing echo in value attribute <option value="<?php $row['Member_id']; ?> "> <?php echo $row['Member_id'];?>
2) onchange should be outside the class attribute .<Select id="st_id" placeholder="Enter Member id" name="ist_id" required class="styled-select green semi-square" onChange="showMember(this.value)">
simple use jquery ajax
function showMember(str)
{
$.ajax({
url:'getMember.php',
type:'post',
data:{q:str},
success:function(data)
{
$('#st_name').val(data);
}
});
}
Note :don't forgot to include jquery

ajax calling php loop with form not working on first loop only

I have a page called events.php that lists past and upcoming events, using ajax to call on pastevents.php and upcomingevents.php, which both have forms that collect users' opinions on past events and whether they will attend future events; then a handle sends it to psql db.
Everything works except the first iteration of the looped form does not submit correctly. Instead of continuing onto pastevents-handle.php, it doesn't post and returns a get on events.php; so I see the user's response in the url bar, but it never gets to the db. I made a test page that didn't use ajax by copy-pasting all the code and that works, so it's definitely something to do with ajax, but neither me or my professor could find out what.
I don't know how to use jquery yet, so please answer with plain javascript.
Here's events.php:
<script>
//show past events
function showPastEvents(str) {
document.getElementById('pastevents').style.display = "block";
document.getElementById('hideoldbutton').style.display = "block";
var xhttp;
if (str == "") {
document.getElementById("pastevents").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("pastevents").innerHTML = this.responseText;
}
};
xhttp.open("POST", "pastevents.php?q="+str, true);
xhttp.send();
}
function hidePastEvents() {
document.getElementById('pastevents').style.display = "none";
document.getElementById('hideoldbutton').style.display = "none";
}
//show upcoming events
function showUpcomingEvents(str) {
document.getElementById('upcomingevents').style.display = "block";
document.getElementById('hidenewbutton').style.display = "block";
var xhttp;
if (str == "") {
document.getElementById("upcomingevents").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("upcomingevents").innerHTML = this.responseText;
}
};
xhttp.open("POST", "upcomingevents.php?q="+str, true);
xhttp.send();
}
function hideUpcomingEvents() {
document.getElementById('upcomingevents').style.display = "none";
document.getElementById('hidenewbutton').style.display = "none";
}
</script>
<!-- page content -->
<div class="content">
<h6>Past events</h6>
<form name="postpastevents" action=""/>
<div id="pastevents"></div>
<input type="button" onClick="hidePastEvents()" id="hideoldbutton" value="Hide" style="display:none;"/>
</form>
<input type="button" onClick="showPastEvents()" id="showoldbutton" value="Show past"/>
<br>
<br>
<!-- ####### -->
<h6>Upcoming events</h6>
<form name="postupcomingevents" action=""/>
<div id="upcomingevents"></div>
<input type="button" onClick="hideUpcomingEvents()" id="hidenewbutton" value="Hide" style="display:none;"/>
</form>
<input type="button" onClick="showUpcomingEvents()" id="shownewbutton" value="Show upcoming"/>
Here is pastevents.php (it's the same code for upcomingevents.php):
<?php
$conn = pg_connect ('dbname=xxxx') or die ('Connect failed ');
$query = "SELECT eventname, eventdate, location, eventdesc FROM events WHERE eventdate < current_date ORDER BY eventdate;";
$result = pg_query($query);
while ( $row = pg_fetch_assoc($result) ) {
$i = 0;
echo "<tr>"; //table row
foreach ($row as $key => $value) {
if ($i == 0) {
$eventname = $value;
}
if ($i == 1) {
$eventdate = $value;
}
$eventinfo = $value;
echo "<td>"; //1 column each loop
echo "$eventinfo";
if ($i == 1) {
echo date(" (l, F jS)", strtotime($eventdate));
}
echo "<br><br>";
echo "</td>";
$i++;
}
echo "<td>";//1 column while same event
?>
<div>
<form name="pasteventsurvey" action="pastevent-handle.php" method="post">
What did you think of the event?
<select name="pasteventopinion">
<option value="">(Choose one)</option>
<option value="good">Loved it!</option>
<option value="okay">Liked it</option>
<option value="bad">Needs improvement</option>
<option value="time">Time conflict</option>
<option value="NA">NA</option>
</select>
<input type="hidden" name="eventname" value="<?php echo $eventname; ?>">
<input type="submit" name="enter" value="Submit"><input type="reset" name="erase" value="Clear">
</form>
</div>
<?php
echo "</td>";
echo "</tr>"; //-table row
}
pg_close($conn);
?>
Here's pastevents-handle.php:
<?php
$conn = pg_connect ('dbname=xxxx') or die ('Connect failed ');
pg_query_params("INSERT INTO eventsurveypast(eventname, opinion) VALUES ($1, $2)", array($name, $opinion));
echo "email is $idkey, eventname is $name, pastopinion is $opinion";
pg_close($conn);
?>
(I edited a bit for space, ignore anything that isn't vital)
It is illegal to have a form inside another form.
Remove the outer form and everything should work fine, except you have another problem with the code.

Using AJAX, PHP and MySQL to display table data

I would like to display one column of data, [pin], based on the [plan] and [order_id] values. plan=9 and order_id=0. Would like to load data without reloading page, using ajax.
Here is my HTML/Script:
<script>
function showPins(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
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) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getPins.php?q="+str,true);
xmlhttp.send();
}
}
</script>
HTML:
<div align="center">
<h3>View PIN's</h3>
<form>
<select name="users" onchange="showPins(this.value)">
<option value="">Select Plan Type:</option>
<option value="1">Plan1</option>
<option value="2">Plan2</option>
<option value="3">Plan3</option>
</select>
</form>
<br/>
<div id="txtHint"></div>
</div>
This is my PHP file (getPins.php):
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('myHost','myUsername','myPw','my_db');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"my_db");
$sql="SELECT * FROM attPins WHERE (order_id=0, plan=9 and id = '".$q."')";
$result = mysqli_query($con,$sql);
echo "<table>
<tr>
<th>PIN's</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['pin'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
This is based off the tutorial shown here: http://www.w3schools.com/php/php_ajax_database.asp
Trying to make it work for showing the correct pins for plan type chosen.
your query would be wrong read manual where
$sql="SELECT * FROM attPins WHERE (order_id=0, plan=9 and id = '".$q."')";
It would be
WHERE (order_id=0 and plan=9 and id = '".$q."')
Or
WHERE (order_id=0 OR plan=9 and id = '".$q."')
according to your requirment

Categories

Resources