How to produce dynamic div id? in PHP/JAVASCRIPT/MYSQL - javascript

I have an ajax code that displays data from table columns when a data is chosen from the dropdown.
surveycontent.php
<script type="text/javascript">
function showUser(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","hay.php?q="+str,true);
xmlhttp.send();
}
}
</script>
ajax.php. I have a textbox that generates dropdowns based on how many the user input
if($question !="" && $cnt!="" && $addQues!="yes" && $main == 1){
$i = 0;
for ($i = 1; $i <= $cnt; $i++)
{
$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 "<form><b id='labelquestion_dropdown'>Question #". $i."</b>";
echo "<select id='question_dropdown".$i."' class='form-control' onchange='showUser(this.value)' style='width: 300px;' 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></form>";
echo "<div id='txtHint'><b>Person info will be listed here...</b></div>";
echo "<br />";
}
echo "<div id='insertQuesHere".$i."'></div>";
echo "<a href='#add_question' onclick='return addQues_Cat();'>Add Question</a> | ";
echo "<a href='#del_question' onclick='return delQues();'>Delete Question</a>";
}
hay.php
<?php
$con = mysqli_connect('localhost','root','','imetrics') or die ("Cannot connect to database");
if(!$con){
echo ('Could not connect: ' . mysqli_error($con));
}
$id= isset($_GET["q"])?intval($_GET["q"]):"";
$query = mysqli_query($con, "SELECT * FROM question WHERE question_id = '".$id."'");
function displayOption($i, $value, $answer_type) {
if($value == null) {
return;
}
if($answer_type == "radiobutton") {
echo '<input type="radio" name="rinput" value="'.htmlspecialchars($value, ENT_QUOTES).'">'.htmlspecialchars($value).'<br>';
} else if($answer_type == "checkbox") {
echo '<input type="checkbox" name="cinput['.$i.']" value="'.htmlspecialchars($value, ENT_QUOTES).'">'.htmlspecialchars($value).'<br>';
}
}
while($row = mysqli_fetch_assoc($query)) {
for($i = 1; $i<=10; ++$i) {
displayOption($i, $row["Option_$i"], $row['answer_type']);
}
}
?>
I have a textbox that generates dropdowns based on the user input. For example, I generated 3 dropdowns, I need to make it possible that hay.php will display data for each of the dropdowns when clicked. Atm it's only showing 1 whichever dropdown I use to choose from. I think the problem is I only have 1 id for the <div id='textHint'> or is it a different problem?

One "hacky" way you could do this ( if I understood the problem correctly ) would be to assign a unique id to the various generated DIV elements and supply that ID as a second argument to your ajax function.
/* note 2nd parameter - id */
function showUser(str,id) {
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) {
/* use id supplied */
document.getElementById(id).innerHTML = this.responseText;
}
};
xmlhttp.open("GET","hay.php?q="+str,true);
xmlhttp.send();
}
}
And the PHP code
for( $i = 1; $i <= $cnt; $i++ ){
$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 "
<form>
<b id='labelquestion_dropdown'>Question #{$i}</b>
<select id='question_dropdown{$i}' class='form-control' onchange=\"showUser( this.value, 'txtHint{$i}' )\" style='width: 300px;' name='question_dropdowns{$i}'>
<option selected>Select";
while($row=mysqli_fetch_array($query)){
echo "<option value='{$row['question_id']}'>" . $row["questiontitle"];
}
echo "
</select>
</form>
<div id='txtHint{$i}'><b>Person info will be listed here...</b></div>
<br />";
}
You might notice the missing </option> from the above - it's not necessary to use it so I tend to omit it.

Okay! If You wanna to put your div in Drop-down.
You may try this in Your code
echo "<option class="HINT"><div id='txtHint'><b>Person info will be listed here...</b></div></option>";
<select>
<option>one</option>
<option>two</option>
<option>three</option>
<option>four</option>
<option><div>THIS IS DIV</div></option>
</select>

Related

show the button if the condition is true according to the input data

I have a input text field i get the data from database using javascript and php.
get.html get the data by javascript
function showUser(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","get.php?q="+str,true);
xmlhttp.send();
}
}
<input type="text" id="name" onblur="showUser(this.value)">
<input type="buton" name="">
<br>
<div id="txtHint"><b>Person info will be listed here...</b></div>
get.phpto connect database to show data
<?php
$q = intval($_GET['q']);
$con=mysql_connect("localhost","root","") or die("Could not Connect with Sql");
mysql_select_db("dialog",$con) or die("Could connect to Database");
$sql="SELECT * FROM customer WHERE cx_number = '".$q."'";
$result = mysql_query($sql);
echo "<table>
<tr>
<th>cx_number</th>
<th>package</th>
<th>balance</th>
</tr>";
while($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['cx_number'] . "</td>";
echo "<td>" . $row['package'] . "</td>";
echo "<td>" . $row['balance'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
now my question is how to show the button to increase package amount if package balance is zero
If you need it for each user just replace in get.php
echo "<td>" . $row['balance'] . "</td>";
to
echo "<td>" . $row['balance'] ;
if ($row['balance'] <= 0) echo "<button>Your button </button>";
echo "</td>";
You also can do it on browser side. Add after
document.getElementById("txtHint").innerHTML = this.responseText;
code like this
$("#txtHint tr").each(function() { // cicle through each row
el=$this.find( "td:eq(2)" ) // get td with index==2.(firs==0, secon==1)...
if (parseFloat(el.html()<=0) { // check if it's 0 or lower
el.append( $( "Your button or link html here" ) ); // add button
}
});
you can change it in your div like this :
function showUser(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","get.php?q="+str,true);
xmlhttp.send();
}
}
<input type="text" id="name" onblur="showUser(this.value)">
<div id="txtHint">
<b>Person info will be listed here...</b></div>
in your ajax file :
<?php
$q = intval($_GET['q']);
$con=mysql_connect("localhost","root","") or die("Could not Connect with Sql");
mysql_select_db("dialog",$con) or die("Could connect to Database");
$sql="SELECT * FROM customer WHERE cx_number = '".$q."'";
$result = mysql_query($sql);
echo "<table>
<tr>
<th>cx_number</th>
<th>package</th>
<th>balance</th>
</tr>";
while($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['cx_number'] . "</td>";
echo "<td>" . $row['package'] . "</td>";
echo "<td>" . $row['balance'] . "</td>";
echo "<td>". if( $row['balance'] == 0) { '<input type="button" name="" value="your value"> } '. "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>

How do I put document get element by id in a loop in javascript/php

How do I put 'txthint' in a loop using javascript? Like making them have differnt id's if i have more than 1 in the page. I think it's important if Im displaying different id's in hay.php
<html>
<head>
<script>
function showUser(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","hay.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
</html>
<form>
<select name="users" onchange="showUser(this.value)">
<option>-None Selected-</option>
<?php
$con = mysqli_connect('localhost','root','','imetrics') or die ("Cannot connect");
$query=mysqli_query($con, "SELECT * FROM question");
while($row=mysqli_fetch_array($query)) {
?>
<option value="<?php echo $row["question_id"]; ?>"><?php echo $row["questiontitle"]; ?></option>
<?php
}
?>
</select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here...</b></div>
this is my php code in hay.php
<?php
$con = mysqli_connect('localhost','root','','imetrics') or die ("Cannot connect to database");
if(!$con){
echo ('Could not connect: ' . mysqli_error($con));
}
$id= isset($_GET["q"])?intval($_GET["q"]):"";
$query = mysqli_query($con, "SELECT * FROM question WHERE question_id = '".$id."'");
function displayOption($i, $value, $answer_type) {
if($value == null) {
return;
}
if($answer_type == "radiobutton") {
echo '<input type="radio" name="rinput" value="'.htmlspecialchars($value, ENT_QUOTES).'">'.htmlspecialchars($value).'<br>';
} else if($answer_type == "checkbox") {
echo '<input type="checkbox" name="cinput['.$i.']" value="'.htmlspecialchars($value, ENT_QUOTES).'">'.htmlspecialchars($value).'<br>';
}
}
while($row = mysqli_fetch_assoc($query)) {
for($i = 1; $i<=10; ++$i) {
displayOption($i, $row["Option_$i"], $row['answer_type']);
}
}
?>

My div doesn't appear when I click on the submit button

I would like to create a poll and show the results when this one is completed. But, the answers don't appear...
Here is my page1.php:
<div id="poll">
<?php
echo "<form onsubmit='getVote(option_ID); return false;' >" ;
echo "<p><b> $question_content </b></p>" ;
$poll_option_selection = "SELECT option_ID, option_content FROM poll_options WHERE question_ID='$question_ID'" ;
$poll_option_result = mysqli_query ($connect,$poll_option_selection) ;
foreach ($poll_option_result as $poll_option) {
$option_ID = $poll_option ['option_ID'] ;
$option_content = $poll_option ['option_content'] ;
?><script type="text/javascript">var option_ID = <?php echo json_encode($option_ID) ; ?> ;</script><?php
echo "<input type='radio' id='$option_ID' value='option' required' /> $option_content</br>" ;
}
echo "<p><input type='submit'></p></form>" ;
?>
</div>
<script type="text/javascript">
var user_ID = <?php echo json_encode($user_ID) ; ?> ;
function getVote(option_ID) {
var option_ID = document.querySelector("input[value='option']:checked").id;
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 (option_ID.readyState==4 && option_ID.status==200) {
document.getElementById("poll").innerHTML=option_ID.responseText;
}
}
xmlhttp.open("GET","./core/vote.php?user_ID="+user_ID+"&option_ID="+option_ID,true);
xmlhttp.send();
}
</script>
And here is page2.php with the results, called by getVote(option_ID):
<?php
echo "<p><b> $question_content </b></p>" ;
$option_selection = "SELECT option_content, option_score FROM poll_options WHERE question_ID='$question_ID' ORDER BY option_score DESC" ;
$option_result = mysqli_query ($connect,$option_selection) ;
foreach ($option_result as $option) {
$option_content = $option ['option_content'] ;
$option_score = $option ['option_score'] ;
echo "
<table>
<th><td> $option_content : </td>
<td><b> $option_score votes </b></td></th>
</table>
" ;
}
echo "<p>Vous devez attendre 6 heures afin de pouvoir revoter</p>" ;
?>
Could someone explain the error to me with an example please? Because I am a beginner... Thank you.
You're checking a string, the elements ID, for it's readyState, which won't work, you'd have to check the XMLHttpRequest object instead.
Here's really what you're doing
function getVote(option_ID) {
var option_ID = document.querySelector("input[value='option']:checked").id;
xmlhttp.onreadystatechange = function() {
if ( option_ID.readyState == 4 && option_ID.status == 200 ) {
// ^ THATS A STRING ?
}
What you want to do is
var user_ID = <?php echo json_encode($user_ID) ; ?>;
function getVote(option_ID) {
var option_ID = document.querySelector("input[value='option']:checked").id;
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("poll").innerHTML = xmlhttp.responseText;
}
}
var data = "?user_ID=" + encodeURIComponent(user_ID) +
"&option_ID=" + encodeURIComponent(option_ID);
xmlhttp.open("GET", "./core/vote.php" + data, true);
xmlhttp.send();
}

I don't know how to display response text in multiple divs

I am making a quiz website ,on click it get questions and options from database
in a row.I want to display question in one div and options in other 3 divs.
i have two pages for it one is careerguidance.php and one is getquestion.php.
Careerguidance.php
<head>
<script>
var str=0;
function showquestion() {
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("div1").innerHTML = xmlhttp.responseText;
// document.getElementById("dop1").innerHTML = xmlhttp.responseText;
// document.getElementById("dop2").innerHTML = xmlhttp.responseText;
// document.getElementById("dop3").innerHTML = xmlhttp.responseText;
}
}
str++;
xmlhttp.open("GET","getquestion.php?idd="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<button onClick="showquestion()">Next</button>
<div class='quiz' id='div1'><h2>$question</h2></div>
<div class='quizoption' id='dop1' onClick=''><h4></h4></div>
<div class='quizoption' id='dop2' onClick=''><h4></h4></div>
<div class='quizoption' id='dop3' onClick=''><h4></h4></div>
</body>
getquestion.php
<?php
$idd = intval($_GET['idd']);
require_once('db_con.php');
//$sq="select id from questions";
//$q_id = (isset($_GET['id']) ? intval($_GET['id']) : 1);
//static $r=1;
//static $q_id=0;
//$q_id++;
$sql="SELECT * FROM questions where id= '".$idd."'";
//$sql="SELECT * FROM questions WHERE id =$r";
$result = mysql_query($sql);
/*
echo "<table>
<tr>
<th>Question</th>
<th>Option1</th>
<th>Option2</th>
<th>Option3</th>
<th>Next</th>
</tr>";
*/
while($row = mysql_fetch_array($result)) {
// echo "<tr>";
echo "<h2>";
echo $row['question'];
echo "</h2>" ;
// echo "<br>" . $row['option1'] ;
// echo "<td>" . $row['option2'] . "</td>";
// echo "<td colspan='2'>" . $row['option3'] . "</td>";
// echo "</tr>";
}
//echo "</table>";
mysql_close($conn);
?>
</body>
</html>
You need to parse your response in parts and then assign values to specific divs. E.g. if your xmlhttp.responseText` looks like this:
{
"question": "Who is it?",
"answers": ["Merry", "Billy", "Joe"]
}
you will something like this:
function buildQuestionaree(data) {
//
// if data is a string
// data = JSON.parse(data);
//
var question = data.question;
var answers = data.answers;
document.getElementById("div1").innerHTML = question;
document.getElementById("dop1").innerHTML = answers[0];
document.getElementById("dop2").innerHTML = answers[1];
document.getElementById("dop3").innerHTML = answers[2];
}

Multiple selection listbox of State not displaying all Cities in another listbox(Php,mysql,ajax)

Selecting the Country dropdown displays State listbox with multiple selections without refreshing page . But selecting 2 or 3 States not displaying all cities in another lisbox. Cities are displaying for only one State. help
loadData.php
<?php
$q = $_GET['q'];
$con = mysqli_connect('localhost','root','','test');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"test");
$sql="SELECT * FROM state WHERE country_id = '".$q."'";
$result = mysqli_query($con,$sql);
echo "<select name='try[]' onchange='showSecondUser(this.value)' multiple>";
while($row = mysqli_fetch_array($result)){
echo "<option value='".$row['id']."'>".$row['state_name']."</option>";
}
echo" </select>";
$g = $_GET['g'];
$sql="SELECT * FROM city WHERE state_id = '".$g."'";
$result = mysqli_query($con,$sql);
echo "<select name='try' multiple>";
while($row = mysqli_fetch_array($result)){
echo "<option value=''>".$row['city_name']."</option>";
}
echo" </select>";
mysqli_close($con);
?>
index.php
<html>
<head>
<script>
function showUser(str) {
if (str=="") {
document.getElementById("txtHint").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) {
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","loadData.php?q="+str,true);
xmlhttp.send();
}
function showSecondUser(str) {
if (str=="") {
document.getElementById("txtHint2").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) {
document.getElementById("txtHint2").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","loadData.php?g="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select Country</option>
<option value="1">Australia</option>
<option value="2">Japan</option>
<option value="3">Russia</option>
<option value="4">Germany</option>
</select>
</form>
<br>
<div id="txtHint"></div>
<div id="txtHint2"></div>
</body>
</html>
It' because mysql query is wrong. You providing multiple numbers in a simple equal.
That should be:
$g = $_GET['g'];
$sql="SELECT * FROM city WHERE state_id IN (".$g.")";
$result = mysqli_query($con,$sql);
if $g is a comma separeted list of numbers.
If not you have to make it so.
So if $g is an array you have to do an implode() on it and than you can use it in the query
$g = $_GET['g'];
$g = implode(',', $g);
$sql="SELECT * FROM city WHERE state_id IN (".$g.")";
$result = mysqli_query($con,$sql);
if it is a string and lets say the numbers are separated my space than you replace space with comma:
$g = $_GET['g'];
$g = str_replace(' ', ',', $g);
$sql="SELECT * FROM city WHERE state_id IN (".$g.")";
$result = mysqli_query($con,$sql);
So in your case the MySQL query should be this:
$sql="SELECT * FROM state WHERE country_id = '".$q."'";
$result = mysqli_query($con,$sql);
echo "<select name='try[]' onchange='showSecondUser(this)' multiple>";
// there is a change here ^
while($row = mysqli_fetch_array($result)){
echo "<option value='".$row['id']."'>".$row['state_name']."</option>";
}
echo" </select>";
/*######################################################*/
$g = $_GET['g'];
$sql="SELECT * FROM city WHERE state_id IN (".$g.")";
$result = mysqli_query($con,$sql);
And the javascript should be this:
function showSecondUser(str){
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
document.getElementById("txtHint2").innerHTML = xmlhttp.responseText;
}
}
var values = new Array();
for (var i=0; i < str.options.length; i++) {
cur = sel.options[i];
if (cur.selected) {
values.push(cur.value);
}
}
if (values.length) {
values = values.join(",");
} else {
values = null;
}
xmlhttp.open("GET","loadData.php?g="+values,true);
xmlhttp.send();
}

Categories

Resources