Mysql Populating dropdown based on another dropdown choice - javascript

I've been testing out a lot of codes for this but i can't get it to work.
I want to populate a dropdown based on the value of another dropdown.
EDIT:
my table name is zipcode and i have CITY, STATE, Zipcode, FULLSTATE, and zipID
STATE is abbreviation of FULLSTATE
I have:
zipcode:php
<?php
/* Template Name: Zipcode Help */
?>
<?php get_header(); ?>
<?php
global $wpdb;
$query = "SELECT * FROM zipcode group by FULLSTATE";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result))
{
$dd .= "<option value='".$row['STATE']."'>".$row['FULLSTATE']."</option>";
}
?>
<select name="dropdown1" id="dropdown1" onchange="populatelist">
<option value="empty" selected>--Select State--</option>
<?php echo $dd; ?>
</select>
<select id="city" name="city">
<option value="empty"> </option>
</select>
<!--content of the page-->
<div class="container-wrapper clearfix" id="main-content-container">
<div class="container">
<?php if (have_posts()) : while (have_posts()) : the_post();?>
<?php the_content(); ?>
<?php endwhile; endif; ?>
</div>
</div>
<?php get_footer(); ?>
Jquery:
function populatelist()
{
var qry=document.getelementbyid('dropdown1').value;
var xmlhttp;
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)
{
});
}
}
xmlhttp.open("POST", "help.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("qry="+qry);
}
Reference Page:(help.php)
<?php
/* Template Name: Help */
?>
<?php get_header(); ?>
<?php
global $wpdb;
$value=$_POST['qry'];
$query = "SELECT * FROM zipcode where STATE like '$value'";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result))
{
$ee .= "<option value='".$row['CITY']."'>".$row['CITY']."</option>";
}
echo $ee;
mysql_close();
?>
<?php get_footer(); ?>
Questions: Where should i put my help.php if i'm using wordpress?
I've created a custom template named 'help' then created a page in dashboard and assigned that template. Is this correct? I uploaded it on the theme directory. Also put it inside the js folder. I dunno I never tried jquery before :S
How should i call the jquery?
I put it on header:
<?php wp_enqueue_script('jquery'); ?>
<?php wp_head() ?>
<script type="text/javascript" src="<?php bloginfo("template_directory"); ?>/js/zipcode.js"></script>
</head>
I've been doing this for 3 days already and i'm so exhausted. I really don't know where to put the reference page

Use the following code in your zipcode.php file.
<?php
/* Template Name: Zipcode Help */
?>
<?php get_header(); ?>
<?php
global $wpdb;
$query = "SELECT * FROM zipcode group by FULLSTATE";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result))
{
$dd .= "<option value='".$row['STATE']."'>".$row['FULLSTATE']."</option>";
}
?>
<select name="dropdown1" id="dropdown1">
<option value="empty" selected>--Select State--</option>
<?php echo $dd; ?>
</select>
<select id="city" name="city">
<option value=""> </option>
</select>
<!--content of the page-->
<div class="container-wrapper clearfix" id="main-content-container">
<div class="container">
<?php if (have_posts()) : while (have_posts()) : the_post();?>
<?php the_content(); ?>
<?php endwhile; endif; ?>
</div>
</div>
<script type="text/javascript">
$(function () {
$('#dropdown1').change(function () {
var value = $(this).val();
if (value == "") {
$("#city").html("<option value=''>Select</option>");
} else {
$.ajax({
type: "POST",
url: "<?php bloginfo('template_directory'); ?>helper/help.php",
data: "value=" + value,
success: function (server_response) {
$("#city").html(server_response);
}
}); //$.ajax ends here
} //if else
return false
});
}); // function ends here
</script>
<?php get_footer(); ?>
Inside your wordpress theme folder create a folder called helper and put your helper.php file in there.
Use the following code in your help.php file;
<?php
$value = $_POST['value'];
global $wpdb;
$value= a_href;
$query = "SELECT * FROM zipcode where STATE like '$value'";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result))
{
$ee .= "<option value='".$row['CITY']."'>".$row['CITY']."</option>";
}
echo $ee ;
?>
I didn't test the code but I think it should work. Let me know if you have any more question.
**Make sure Jquery is loaded properly
Very Important: mysql_query is deprecated as of PHP 5.5.0 . You should use PDO or mysqli extension. Check This: http://cz1.php.net/mysql_query

Related

How to Create Load More With PHP and PDO

i want to create load more to my site, but when i try to click load more it just load 2 items.
my index.php
<div class="postList">
<?php
// Include the database configuration file
include 'koneksi.php';
// Get records from the database
$query = $db->prepare("SELECT * FROM master_post, posting WHERE master_post.master_post_name = posting.master_post_name AND posting.sticky = 'Normal' ORDER BY posting.idpost DESC LIMIT 2");
$query->execute();
if($query->rowCount() > 0){
while($row = $query->fetch()){
$postID = $row['idpost'];
?>
<div class="list_item"><?php echo $row['file_name']; ?></div>
<?php } ?>
<div class="show_more_main" id="show_more_main<?php echo $postID; ?>">
<span id="<?php echo $postID; ?>" class="show_more" title="Load more posts">Show more</span>
<span class="loding" style="display: none;"><span class="loding_txt">Loading...</span></span>
</div>
<?php } ?>
</div>
my javascript
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click','.show_more',function(){
var ID = $(this).attr('id');
$('.show_more').hide();
$('.loding').show();
$.ajax({
type:'POST',
url:'ajax_more.php',
data:'id='+ID,
success:function(html){
$('#show_more_main'+ID).remove();
$('.postList').append(html);
}
});
});
});
</script>
my ajax_more.php
if(!empty($_POST["id"])){
// Include the database configuration file
include 'koneksi.php';
// Count all records except already displayed
$query = $db->prepare("SELECT COUNT(*) as num_rows FROM master_post, posting WHERE master_post.master_post_name = posting.master_post_name AND posting.sticky = 'Normal' AND posting.idpost < ".$_POST['id']." ORDER BY posting.idpost DESC");
$row = $query->fetch();
$totalRowCount = $row['num_rows'];
$showLimit = 2;
// Get records from the database
$query = $db->query("SELECT * FROM master_post, posting WHERE master_post.master_post_name = posting.master_post_name AND posting.sticky = 'Normal' AND posting.idpost < ".$_POST['id']." ORDER BY posting.idpost DESC LIMIT $showLimit");
if($query->rowCount() > 0){
while($row = $query->fetch()){
$postID = $row['idpost'];
?>
<div class="list_item"><?php echo $row['file_name']; ?></div>
<?php } ?>
<?php if($totalRowCount > $showLimit){ ?>
<div class="show_more_main" id="show_more_main<?php echo $postID; ?>">
<span id="<?php echo $postID; ?>" class="show_more" title="Load more posts">Show more</span>
<span class="loding" style="display: none;"><span class="loding_txt">Loading...</span></span>
</div>
<?php } ?>
<?php
}
}
I'm not sure where the mistake is. im using tutorial from this site https://www.codexworld.com/load-more-data-using-jquery-ajax-php-from-database/

How to auto refresh div contents contain php variables?

I created a page named queries.php
<?php
require("connection.inc.php");
$query = "SELECT SUM(john), SUM(robert), COUNT(school) FROM election";
$result = mysql_db_query($db, $query, $connection) or
die("query error!");
$data = mysql_fetch_array($result);
$john = number_format($data[0], 0,',','.');
$robert = number_format($data[1], 0,',','.');
$school = $data[2];
$total = $john + $robert;
$remaining_school = 524 - $school;
$percentage_john = round(($john*100/$total),2);
$percentage_robert = round(($robert*100/$total),2);
?>
Then I display the data in display.php
The data displayed well and nothing error, I tried a couple of tricks to auto refresh the container using jquery but failed.
Here is my display.php page:
<?php
include("queries.php");
?>
<div id="totaljohn"> // <--- the div id taken from css layout
<h9>John: <?php echo $john; ?> <br> (<?php echo $percentage_john; ?> %)</h9>
</div>
<div id="totalrobert">
<h9>Robert: <?php echo $robert; ?><br> (<?php echo $percentage_robert; ?> %)</h9>
</div>
<div id="totalboth">
<h4>Total : <?php echo $total; ?> Suara</h4>
</div>
<div id="totalschool">
<h4>Total School attending : <?php echo $school; ?> Schools</h4>
</div>
<div id="remaining_schools">
<h4>Remaining Schools: <?php echo $remaining_school; ?> of 524 schools</h4>
</div>
Everything looks good. Is your database connected? Is your SQL correct? Are there records in the database returned for your query?

autosubmit drop down value into database

i'm trying to auto submit the value of drop down menu using onchange=this.form.submit() into database but i couldn't make it work. can anyone please help me. any suggestions will be highly appreciated.
here is the code:
<?
require_once ('database.php');
?>
<form action="" method=post>
<select name="assignee" onchange="this.form.submit()">
<option value="0">Unassigned</option>
<?
$find_selected = mysql_query("select assign_to from orders where id = $id");
$asignee =mysql_fetch_row($find_selected);
$list=mysql_query("SELECT id, full_name from user where username <> 'root' and nature = 3");
while($row_list=mysql_fetch_assoc($list)){
?>
<option value="<? echo $row_list['id']; ?>"<? if($row_list['id']== $asignee['0']){ echo "selected"; } ?>><? echo $row_list['full_name'] ?></option>
<?
}
mysql_free_result($list);
mysql_free_result($find_selected);
?>
</select>
</form>
<?php
if(isset($_POST['submit'])){
$sql = "UPDATE `orders` SET `assign_to` = '{$_POST['assignee']}' WHERE `id` = '$id' ";
mysql_query($sql) or die(mysql_error());
}
?>
<?php
if(isset($_POST['assignee'])){
$sql = "UPDATE `orders` SET `assign_to` = '{$_POST['assignee']}' WHERE id=$id";
mysql_query($sql);
}
?>
You just defined your query but didn't executed it

xmlhttp.responseText returns contents of the script tag

<script>
function refresh_event(){//CALLED WHEN EVENT IS CHANGED
document.getElementById("frm_event").submit();
}
function click1(i,stuid){//AJAX CODE
var obj = document.getElementById("event");
var eid = obj.options[obj.selectedIndex].value;
var xmlhttp;
var j=document.getElementById("link"+i).innerHTML;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
//alert("in");
document.getElementById("link"+i).innerHTML=xmlhttp.responseText;
// alert(xmlhttp.responseText);
}
}
//alert("a"+j+"b");
xmlhttp.open("GET","register.php?i="+j+"&sid="+stuid+"&eid="+eid+"&val=1&t="+Math.random(),true);
xmlhttp.send();
}
</script>
<?php
if($val==0){//LANDING PAGE
?>
<?php
if(mysqli_connect_errno()){
echo "connection error";
}
$query="select name,eid from event_info";
$result = mysqli_query($con,$query);
?>
<!-- CODE TO POPULATE EVENT LIST -->
<form id="frm_event" method="GET" action="register.php">
Events:<select id="event" name="event" onchange="refresh_event()">
<?php
if($event==0){
?>
<option value=0 selected> --select-- </option> <!-- IF NOTHING IS SELECTED -->
<?php
}else{
?>
<option value=0> --select-- </option> <!-- IF EVENT IS SELECTED -->
<?php
}
?>
<?php
while($row=mysqli_fetch_array($result)){ //FETCH EVENT FROM DATABASE
if($event==$row['eid']){
?>
<option value=<?=$row['eid'] ?> selected> <?=$row['name'] ?> </option>
<?php
}
else{
?>
<option value=<?=$row['eid'] ?>> <?=$row['name'] ?> </option>
<?php
}
}
?>
</select>
</form>
<?php
$query="select stuid,name from stud_info";
$result = mysqli_query($con,$query);
$i=1;
?>
<br>
<table>
<?php
if($event==0){//IF EVENT IS NOT SET
?>
<?php
while($row=mysqli_fetch_array($result)){
?>
<tr>
<td>
<p><?=$row['name'] ?></p>
</td>
<td>
Assign
<!-- Assign 1-->
</td>
</tr>
<?php
$i++;
}
}
else{//IF EVENT IS SET
?>
<?php
while($row=mysqli_fetch_array($result)){//FETCH REGISTERED STUDENT FROM DATABASE
$regid=0;
$stuid=$row['stuid'];
$query_event="select regid from event_register where stuid='$stuid' and eid='$event'";
$result_event=mysqli_query($con,$query_event);
$count1 = mysqli_num_rows($result_event);
?>
<tr>
<td>
<p><?=$row['name'] ?></p>
</td>
<td>
<?php
if($count1>0){//IF STUDENT IS REGISTERED FOR THIS EVENT
?>
Remove
<?php
}
else{
?>
Assign
</td>
</tr>
<?php
}
$i++;
}
}
?>
</table>
<?php
}
else{
//$_GET['change']="new";
$val=0;//RESET THE VALUE
$var =$_GET['i'];
$sid = $_GET['sid'];
$eid = $_GET['eid'];
if($var=="Assign"){
//INSERT QUERY
$query="insert into event_register (stuid,eid) values ('$sid','$eid')";
$result = mysqli_query($con,$query);
echo "Remove";
}
else{
//delete
$query="delete from event_register where stuid='$sid' and eid='$eid'";
$result = mysqli_query($con,$query);
//if(mysqli_affected_rows($con)>0){
echo "Assign";
//}
/* else{
echo "Assign";
} */
//return "return";
}
}
?>
here is my code. using php and javacript. trying to fetch values from the databse using ajax. But the value returned by xmlhttp.responseText is giving problem.
above is the partial content of the script tag.
xmlhttp.responseText returns the entire contents of the script tag including the tag itself.
tried changing the getElementbyId to getElementsbyName still no luck.
the section of the code that executes on ajax call is at the end.
anyhelp is much appreciated.
I'm not sure why it is happenning for you but it happened to me for the following reason: I had named my js and php file the same name, ex "script", and then in my js file, say "script.js", instead of setting handler url to script.php I set it to script.js, and so where as I might have had in my script.php, echo "resp on my php script", instead the whole text of my js file is read out.

Sequential jquery 'pages', third frame gives a reference error

I am quite new to javascript/jquery and having been playing around with the w3schools tutorials and the jquery documentation and made a page which will accept some user input and then via javascript print some output. I assumed i could modify this to work sequentially but when the second page should call the third page I get
ReferenceError: $gp is not defined
[Break On This Error]
$('#txtField2').load('getglycosites.php?q='+$gp+'r='+$('.glycotype').val());
I would appreciate if anyone has a trick to be able to use the $_get variable in the jquery script.
Code for pages:
first page (test.php):
<html>
<head>
<title>LeidenGlycoPeptide DataBase</title>
<script src="jquery-1.9.1.min.js"></script>
</head>
<script>
$(document).ready(function() {
$('.glycoprotein').change(function() {
$('#txtField').load('getglycopeptides.php?gp='+$('.glycoprotein').val());
});
});
</script>
<body>
<h1>Welcome to the LeidenGlycoPeptide DataBase</h1>
<?php
$link = mysql_connect("localhost","reader","") or die (mysql_error());
mysql_select_db('leidenGlycoPeptide') or die ();
$query = 'select protein from glycoPeptide';
$result = mysql_query($query);
mysql_close($link);
?>
<form>
<p>Select glycopeptide to search for (interactive dialog)</p>
<?php
echo"<select class=\"glycoprotein\">";
echo"<option value=\"\">select glycoprotein</option>";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
foreach ($line as $col_value) {
echo"<option value=\"$col_value\">$col_value</option>";
}
}
echo"</select>";
?>
</form>
<br>
<div id="txtField"></div>
</body>
</html>
Second Page (getglycopeptides.php):
<html>
<head>
<title>glyco</title>
<script src="jquery-1.9.1.min.js"></script>
</head>
<script>
$(document).ready(function() {
$('.glycotype').change(function() {
//NOTE $q/q are undefined
$('#txtField2').load('getglycosites.php?q='+$gp+'r='+$('.glycotype').val());
});
});
</script>
<body>
<?php
// The next variable is the one I would like to use inside the jquery
$gp=$_GET["gp"];
$link = mysql_connect("localhost","reader","") or die (mysql_error());
mysql_select_db("leidenGlycoPeptide",$link) or die();
$query = "select glycoType from run,glycoPeptide where run.id = glycoPeptide.id and glycoPeptide.protein like '".$gp."'";
$result = mysql_query($query);
?>
<form>
<?php
echo "<select class=\"glycotype\">";
echo "<option value=\"\">select glycosylation</option>";
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
foreach ($row as $col_value)
{
echo"<option value=\"$col_value\">$col_value</option>";
}
}
echo "</select>";
mysql_close($link);
?>
</form>
<br>
<div id="txtField2"></div>
</body>
</html>
The third page (getglycosites.php):
<html>
<head>
<title>sites</title>
</head>
<body>
<?php
$gp=$_GET["gp"];
$r=$_GET["r"];
$link = mysql_connect("localhost","reader","") or die (mysql_error());
mysql_select_db("leidenGlycoPeptide",$link) or die();
$query = "select glycoSite from run,glycoPeptide where run.id = glycoPeptide.id and run.glycoType like '".$r."' and glycoPeptide.protein like '".$q."'";
//echo $query;
$result = mysql_query($query);
echo "<select name=\"site\" onchange=\"foo\">";
echo "<option value=\"\">select glycosite</option>";
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
foreach ($row as $col_value)
{
echo"<option value=\"$col_value\">$col_value</option>";
}
}
echo "</select>";
mysql_close($link);
?>
</body>
</html>
PS: The third page is currently only supposed to show a new select field but once I get this working it will be a part in a large sequential sequence.
Thanks in advance
I was able to 'fix' this by adding the following line (to the jquery script):
var gp = '<?php echo htmlspecialchars($_GET['gp']); ?>';
Making the total script part of the third page:
<script>
var gp = '<?php echo htmlspecialchars($_GET['gp']); ?>';
$(document).ready(function() {
$('.glycotype').change(function() {
$('#txtField2').load('getglycosites.php?q='+gp+'&r='+$('.glycotype').val());
});
});
</script>

Categories