Send multiple variable with PHP AJAX GET onclick of a button - javascript

I have two dynamically loaded dropdowns: one containing golf course holes information and another holding users- together the information will be used to generate a scorecard.
When the course is selected and a user is selected I want to click a button and then this will generate the scorecard.
Below is the code for the 'course' dropdown
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = '';
$con = mysqli_connect($db_host,$db_user,$db_pass, $db_name);
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$sql = "SELECT courseID, name FROM courses";
$result = mysqli_query($con, $sql) or die("Error: ".mysqli_error($con));
while ($row = mysqli_fetch_array($result))
{
$courses[] = '<option value="'.$row['courseID'].'">'.$row['name'].'</option>';
}
?>
Below is the code for the 'user' dropdown
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = '';
$con = mysqli_connect($db_host,$db_user,$db_pass, $db_name);
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$sql = "SELECT userID, forename, surname FROM user";
$result = mysqli_query($con, $sql) or die("Error: ".mysqli_error($con));
while ($row = mysqli_fetch_array($result))
{
$users[] = '<option value="'.$row['userID'].'">'.$row['forename'].' '.$row['surname'].'</option>';
}
?>
Below is the HTML code for the dropdowns
<form>
<select id="selectCourse" onchange="showCourse(this.value)">
<option value = "">Select Course</option>
<?php foreach($courses as $c){
echo $c;
}?>
</select>
<select id="selectUser" >
<option value = "">Select User</option>
<?php foreach($users as $u){
echo $u;
} ?>
</select>
<button type="button" >Click me</button>
</form>
At the moment I have code that uses the 'onchange' to load the first part of the scorecard which contains the hole information about that course. I am having problems changing this to the click of the button and also consider another variable from the user dropdown.
The below code is taken from W3Schools which loaded the hole information correctly based on 'onchange'.
<script>
function showCourse(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","generateSC.php?cValue="+str,true);
xmlhttp.send();
}
}
</script>
The below code shows the first half of the scorecard being generated from the selection of the first dropdown.
<?php
$cValue = mysql_real_escape_string($_GET['cValue']);
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = '';
$con = mysqli_connect($db_host,$db_user,$db_pass,$db_name);
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$sql="SELECT DISTINCT holeNumber, strokeIndex, par FROM holes WHERE courseID= '".$cValue."'";
$result = mysqli_query($con,$sql) or die("Error: ".mysqli_error($con));
echo '<div class="scorecardTable">
<table>
<tr>
<th>HoleNumber</th>
<th>Par</th>
<th>Stroke Index</th>
<th>Score</th>
<th>Points</th>
</tr>';
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['holeNumber'] . "</td>";
echo "<td>" . $row['par'] . "</td>";
echo "<td>" . $row['strokeIndex'] . "</td>";
echo "<td> <input required type=text /></td>";
echo "<td> </td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</body>
</html>
What I am looking to know is can I pass two variables through at this point below:
xmlhttp.open("GET","generateSC.php?cValue="+str,true);
and if so how would I get the second variable.
EDIT
<script>
function showCourse(course, user) {
var user = document.getElementById('selectUser').value;
var course = document.getElementById('selectCourse').value;
if (user || course == "") {
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","generateSC.php?course="+course+"&user="+user,true);
xmlhttp.send();
}
}
</script>
I've updated what I have above... the problem now is how do i get the button to work with the two variables?
<form>
<select id="selectCourse">
<option value = "">Select Course</option>
<?php foreach($courses as $c){
echo $c;
}?>
</select>
<select id="selectUser" >
<option value = "">Select User</option>
<?php foreach($users as $u){
echo $u;
} ?>
</select>
<button type="button" >Click me</button>
</form>

Just fetch the values from both dropdowns and concatinate the URL:
var user = document.getElementById('selectUser').value;
var course = document.getElementById('selectCourse').value;
xmlhttp.open("GET","generateSC.php?cValue="+course+"&user="+user,true);
Then your generateSC php script will of course have to fetch the value from the user parameter and work with that as well.
$_GET['user'] will fetch the value from the user parameter.

Related

Get response from PHP code by Ajax

I try to send the data from the HTML form to php code by Ajax and it does not get the response
the html form get user_id from the user entry then send it by java script function that handle ajax code and send the user_id to php code to get user_id by $user_id = $_GET['user_id']; and search by the user_id then show what ever in php code in the other html code to show div content showdocument.getElementById("content").innerHTML=xmlhttp.responseText; response from php
function showUser(str) {
if (str == "") {
document.getElementById("content").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("content").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "http://localhost/gpms/admin_modify_user.php?user_id=" + str, true);
xmlhttp.send();
}
<head>
<script src="http://localhost/gpms/admin_user.js"></script>
</head>
<body>
<form method=post>
<label> Enter User ID: </label>
<input id="user_id" type=text name=user_id>
<br><br>
<input id="modify" type=submit value=Modify onclick="<script>showUser(user_id);</script>">
</form>
</body>
<?php
$user_id = $_GET['user_id'];
//create connection
$conn = mysqli_connect("localhost","root","","gpms");
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM user WHERE user_id = '$user_id' ";
$result = mysqli_query($conn, $sql);
if (mysqli_query($conn, $sql)) {
$row = mysqli_fetch_assoc($result);
if ($row == 0) {
echo "No Results";
}
else {
$id = $row['user_id'];
$name = $row['user_name'];
$password = $row['user_password'];
$email = $row['user_email'];
$department = $row['user_department'];
echo "<div id = demo>";
echo "<table>";
echo "<tr>";
echo "<td> ID </td><td> Name </td><td> Password </td><td> E-mail </td><td> Department </td>";
echo "</tr>";
echo "<tr>";
echo '<td> '. $id .' </td><td> '. $name .' </td><td> '. $password .' </td><td> '. $email .' </td><td> '. $department .' </td>';
echo "</tr>";
echo "</table>";
echo "<button onclick = 'editUser(\"$id\",\"$name\",\"$password\",\"$email\",\"$department\")' > Edit </button>";
echo "<button onclick = 'deleteUser(".$id.")' > Delete </button>";
echo "</div>";
}
}
else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
$conn->close();
?>
Your onclick attribute is wrong. It should just be the Javascript code, it shouldn't have <script>...</script> around it.
<input id="modify" type=submit value=Modify onclick="showUser(user_id);">
If you had looked in your Javascript console you would have seen it complain of a syntax error when you clicked.
And in the PHP, this line:
if (mysqli_query($conn, $sql)) {
should be:
if ($result) {
Otherwise you do the same query twice, which is unnecessary.

How do I run a click event for a php created html table

I have php creating a table based on the results of a search and this table overwrites a previous table. When clicking a row of this table I want the details of the row to be displayed. However while clicking on the previous table works when clicking on the results table the click event is not triggered.
The initial table code and containing div:
<div id="fixInfo" style="overflow-y: auto; overflow-x:hidden;max-height:350px; width: 1000px;">
<table class="standard" id= "list">
<?php
include 'DATA.php';
$sql = "SELECT * FROM FIX";
$result = mysqli_query($conn, $sql);
if ($result = mysqli_query($conn, $sql)){
while ($row = mysqli_fetch_assoc($result)){
echo '<tr>';
echo '<td style="width:150px;">'.$row["FIX_ID"].'</td>';
echo '<td style="width:150px;">'.$row["TIME"].'</td>';
echo '<td style="width:150px;">'.$row["DATE"].'</td>';
echo '<td style="width:150px;">'.$row["PROVIDER_ID"].'</td>';
echo '</tr>';
}
}
mysqli_close($conn);
?>
</table>
</div>
The jquery click event code:
<script>
$("#list tr").on("click",function(){
var ID = $(this).find("td:first").text();
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200) {
document.getElementById("fixstuff").innerHTML = this.responseText;
}
};
var params= "ID="+ID;
xmlhttp.open("POST","fixdetails.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
});
</script>
The result table creation code(searchFix.php):
<?php
$sort = $_POST['sort'];
$search= $_POST['search'];
include 'DATA.php';
if($search==""){
$sql = "SELECT * FROM FIX";
}
else{
$sql= "SELECT * FROM FIX WHERE ".$sort." =". $search;
}
$result = mysqli_query($conn, $sql);
if ($result = mysqli_query($conn, $sql)){
while ($row = mysqli_fetch_assoc($result)){
echo '<tr>';
echo '<td style="width:150px;">'.$row["FIX_ID"].'</td>';
echo '<td style="width:150px;">'.$row["TIME"].'</td>';
echo '<td style="width:150px;">'.$row["DATE"].'</td>';
echo '<td style="width:150px;">'.$row["PROVIDER_ID"].'</td>';
echo '</tr>';
}
}
mysqli_close($conn);
?>
As you are altering the dom you will need to do a rebind.
$.on does not work the same as the deprecated $.live
try changing initial line to
$(document).on('click','#list tr', {} ,function(e){

chained dropdown from database

so basically im trying to achieve this: When someone selects any option from the drop down called subject, the sections drop down should show all sections of that subject. The subject drop down works well, fetches all names of subjects but the sections one won't work. Im unable to find the issue. Thanks in advance. My code is below:
my js code
<script type="text/javascript">
function getSection(strURL)
{
alert(strURL);
var req = getXMLHTTP(); // fuction to get xmlhttp object
if (req)
{
req.onreadystatechange = function()
{
if (req.readyState == 4) { //data is retrieved from server
if (req.status == 200) { // which reprents ok status
document.getElementById('sectiondiv').innerHTML=req.responseText;
}
else
{
alert("There was a problem while using XMLHTTP:\n");
}
}
}
req.open("GET", strURL, true); //open url using get method
req.send(null);
}
}
</script>
php code:
<div>
Subject:
<?php
$conn = new mysqli('localhost', '', '', '')
or die ('Cannot connect to db');
$result = $conn->query("select name from class");
echo "<select name='subject' onchange='getSection('findsection.php?subject=>'this.value'";
while ($row = $result->fetch_assoc()) {
unset($id, $name);
$name = $row['name'];
echo '<option value="subject">'.$name.'</option>';
}
echo "</select>";
?>
</div>
<br>
<div id="sectiondiv">
Section:
<select name="select">
</select>
</div>
my findsection.php
<? $subject=intval($_GET[‘subject’]);;
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
$mysqli = new Mysqli($servername, $username, $password, $dbname) or mysqli_error($mysqli);
$section = $mysqli->query("SELECT section FROM class WHERE name = '$subject'")->fetch_object()->section;
$result=mysql_query($section);?>
<select name="section">
<? while ($row = $result->fetch_assoc()) { ?>
<option value><?=$row['section']?></option>
<? } ?>
</select>
echo "<select name='subject' onchange='getSection('findsection.php?subject=>'this.value'";
You appear to be missing a bracket here.
I sincerely hope it's that simple, lemme know! :D

Can't get ajax working with PHP to load a table of info from MySQL

So basically I have a drop down list that displays data from a MySQL table(accounts) that would display user accounts. When the user selects one of the accounts I want it to display all facilities(facility table) that are owned by that account.
I have the drop down displaying the accounts, but it will not run the onChange() function to load my table. Here is everything I have, can someone tell me why my function is not getting triggered at all?
Index.php
<?php
require_once('sessionstart');
require_once('header.php');
require_once('dbconn.php');
//Accounts
require_once('getaccounts.php');
//Facility
echo "<div id='facilities'>";
require_once('getfacility.php');
echo "</div>";
?>
<?php
require_once 'footer.php';
?>
getaccounts.php
<?php
//require files
require_once('sessionstart.php');
require_once('dbconn.php');
//clear options variable
$options = "";
//connect to db and test connection.
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (!$dbc) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT account_id, account_name FROM accounts";
$data = mysqli_query($dbc, $sql);
//loop through data and display all accounts
while ($row = mysqli_fetch_array($data)) {
$options .="<option>" . $row['account_name'] . "</option>";
}
//account drop down form
$accountDropDown="<form id='account' name='account' method='post' action='getaccounts.php'>
<label>Accounts: </label>
<select name='account' id='account' onchange='showFacilities(this.value)'>
<option selected='selected' disabled='disabled' value=''>Select account</option>
" . $options . "
</select>
</form>";
//echo out account form
echo $accountDropDown;
?>
This works how I need it to and displays all accounts within the drop down. However I can't seem to get the showFacilities() function to work.
getfacility.php
<?php
require_once('dbconn.php');
$q = intval($_GET['q']);
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (!$dbc) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM facility "
. "INNER JOIN accounts ON accounts.account_id = facility.account_id "
. "WHERE facility.account_id = '".$q."'";
$data = mysqli_query($dbc, $sql);
echo "<table>
<tr>
<th>Facility Number</th>
<th>Facility Name</th>
<th>Facility Address</th>
<th>Facility City</th>
</tr>";
//loop through data and display all accounts
while ($row = mysqli_fetch_array($data)) {
echo "<tr>";
echo "<td>" . $row['facility_number'] . "</td>";
echo "<td>" . $row['facility_name'] . "</td>";
echo "<td>" . $row['facility_address'] . "</td>";
echo "<td>" . $row['facility_city'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
footer.php (includes showFacilities())
<script>
function showFacilities(account){
//I wrote this to test and see if this function was even being triggered.
document.alert("test");
if(account == ""){
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) {
document.getElementById("facilities").innerHTML = xmlhttp.responseText;
}
}
else{
xmlhttp.open("GET","getfacility.php?q="+account,true);
xmlhttp.send();
}
}
</script>
<footer>
<p>Copyright &copy</p>
</footer>
</body>
</html>
Please tell me if I am doing this all wrong, am I laying everything out properly? Why is this function not being hit?
I have tried to a bunch of different things, and I just can't seem to get this to work, any help or advice or even a push in the proper direction will be very appreciated, thanks.
Your if else clauses don't add up (so your script is generating a script error, most likely a syntax error).
else{
xmlhttp.open("GET","getfacility.php?q="+account,true);
xmlhttp.send();
}
This piece doesn't have an IF to accompany it.
This would be correct:
if(account == ""){
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("facilities").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getfacility.php?q="+account,true);
xmlhttp.send();
}
On a sidenote: Why create a form wrapper around your select (the one that where you can load accounts) when you use an onchange event to fire an XmlHTTPRequest?

Pagination in php. AJAX,PHP, MYSQL

I am creating a forum kind of a website, where I display posts dynamically using ajax. When the user logs in he finds a 'orderby' drop down select option, where he can choose the order of the posts.
select menu
<select name="orderby" id="orderby" onchange="showposts(this.value)" >
<option value="1" selected>By Time</option>
<option value="2">By Genuine Count</option>
<option value="3">By Dubious Count</option>
</select>
when the page is loaded window.onload function is called, which calls the 'showposts()' function to display the posts.
onload()
window.onload=function(){
showposts();
};
showposts() function
function showposts(str){
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if(str != undefined){
currentType=str; //save the current type for later use
document.getElementById("postsdiv").innerHTML = "";
}else{
var e = document.getElementById("orderby");
str = e.options[e.selectedIndex].value;
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
// alert(xmlhttp.responseText);
document.getElementById("postsdiv").innerHTML=xmlhttp.responseText;
}
};
xmlhttp.open("GET","showposts.php?q="+str,true);
xmlhttp.send();
}
a part of showposts.php page which gets posts from database if the selected option is 1
if(intval($_GET['q'])==1){
while($row = $result->fetch_assoc()) {
echo "<div class='postclass'>";
echo "<span id='postspan".$row['id']."' name='postspan".$row['id']."' >";
echo "<span id='editspan".$row['id']."' name='editspan".$row['id']."' >";
echo "</br>";
echo "Posted By: &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp <span class='bold'> ".$row['user']."</span>";
if($username==$row['user']){
echo "<a href='javascript:void(0);' onclick='deletepost(".$row['id'].")' >DELETE </a>&nbsp&nbsp&nbsp";
echo "<a href='javascript:void(0)'onclick='editpost(".$row['id'].",\"".$row['subject']."\",\"".$row['post']."\")' >EDIT </a></br>";
}else{
echo "</br>";
}
echo "<a id=".$row['id']."></a>";
echo "Date & Time: ".$row['date']."</br>";
echo "<span id=genuinecount".$row['id'].">Genuine Count: ".$row['genuine']."</span></br>";
echo "<span id=dubiouscount".$row['id'].">Dubious Count: ".$row['dubious']."</span>";
echo "</br>------------------------ </br>";
echo "Subject: <span class='bold' >".$row['subject']."</span></br>";
echo "Post: ";
echo "<div class='postbox' >&nbsp•&nbsp".$row['post'] . "</div><br /></br>";
}
}
So, my question is how to add pagination for this script? Can anyone help?
query
$sql = "SELECT * FROM posts order by date desc";
$result = $connection->query($sql);
showposts() function
function showposts(str, page, pagesize){
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if(str != undefined){
currentType=str; //save the current type for later use
document.getElementById("postsdiv").innerHTML = "";
}else{
var e = document.getElementById("orderby");
str = e.options[e.selectedIndex].value;
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
// alert(xmlhttp.responseText);
document.getElementById("postsdiv").innerHTML=xmlhttp.responseText;
}
};
xmlhttp.open("GET","showposts.php?q="+str+'&page='+page+'&pagesize='+pagesize,true);
xmlhttp.send();
}
query
$page = intval($_GET['page');
$pagesize = intval($_GET['pagesize']);
$sql = "SELECT * FROM posts order by date desc limit "
. ($page-1)*$pagesize . ", " . $pagesize;
Example link
Page 1, 20 per page

Categories