php ajax droplist - php

i am creating 2 drop down list that the second one is based on the selection of the first drop down list. the data are retrieved from the mysql database
index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Playing With Select list</title>
<link rel="stylesheet" type="text/css" href="css/demo.css" />
<link href='http://fonts.googleapis.com/css?family=Open+Sans:300,700' rel='stylesheet' type='text/css' />
<!--[if lte IE 8]><style>.main{display:none;} .support-note .note-ie{display:block;}</style><![endif]-->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$(".country").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "ajax_category.php",
data: dataString,
cache: false,
success: function(html)
{
$(".governorate").html(html);
}
});
});
});
</script>
</head>
<body>
<div class="container">
<header>
<h1><strong>Playing With Select List</strong></h1>
<h2>Select One List To see Output On Other</h2>
</header>
</div>
<span style="margin-left:22%">
<label>country :</label> <select name="country" class="category">
<option selected="selected">--Select Country--</option>
<?php
include('db.php');
$sql=mysql_query("select country_id,country_name from country");
while($row=mysql_fetch_array($sql))
{
$id=$row['country_id'];
$data=$row['country_name'];
echo '<option value="'.$id.'">'.$data.'</option>';
} ?>
</select>
<label>Governorate :</label> <select name="governorate" class="subcategory">
<option selected="selected">--Select governorate--</option>
</select>
</span>
<br><br><br>
<h1><center><strong>Go To-:TrickToDesign</strong></center></h1>
</body>
</html>
ajax_category.php
<?php
include('db.php');
if($_POST['governorate_id'])
{
$id=$_POST['governorate_id'];
$sql=mysql_query("select b.governorate_id,b.governorate_name from governorate a,contry_id b where b.country_id=a.country_id and parent='$id'");
while($row=mysql_fetch_array($sql))
{
$id=$row['governorate_id'];
$data=$row['governorate_name'];
echo '<option value="'.$id.'">'.$data.'</option>';
}
}
?>
how to make the second drop list appear with data in it that is the error that i face

Change $(".governorate").html(html) to $(".subcategory").html(html)

Related

AJAX send value from js to php

been tring to send var form js to php and do some manipulation but I keep receving this error. Is it even possible to send the value through to php?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>test</title>
<script
src="https://code.jquery.com/jquery-3.5.0.min.js"
integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ="
crossorigin="anonymous">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/d3js/5.15.1/d3.min.js"></script>
</head>
<body>
<input type="text" name='name'>
<p id="hey"></p>
<?php
echo $_POST['name'];
?>
<button id='button'>hi</button>
</body>
<script src="index.js"></script>
</html>
$("#button").click(function(){
$.post("index.php",
{
name: "Donald Duck",
city: "Duckburg"
},
function(data, status){
$("#hey").append(status);
});
});
I created one index.php file here this should work for you.
<?php
if ($_POST) {
echo json_encode(['data' => $_POST['name'], 'success' => true]);
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>test</title>
<script
src="https://code.jquery.com/jquery-3.5.0.min.js"
integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ="
crossorigin="anonymous">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/d3js/5.15.1/d3.min.js"></script>
</head>
<body>
<input type="text" name='name'>
<p id="hey"></p>
<div id='test'></div>
<button id='button'>hi</button>
</body>
<script>
let data = {
name: "Donald Duck",
city: "Duckburg"
};
$("#button").click(function(){
$.ajax({
type: "POST",
url: 'index.php',
data: data,
dataType: 'json'
}).done(function(response) {
if (response.success) {
$('#hey').html('success');
$('#test').html(response.data);
}
});
});
</script>
</html>
This does not work because when you first load the page $_POST['name'] is undefined. Your javascript code does not trigger a submit (= reload to send the data). $_POST['name'] is never set because it will not be updated on the fly. To make this work make a separate php file which only handles the POST data from your javascript and returning a value.
/* call post.php and add console.log to track data */
$("#button").click(function(){
$.post("post.php",
{
name: "Donald Duck",
city: "Duckburg"
},
function(data, status){
$("#hey").append(status);
console.log(data);
});
});
<?php
// post.php
if($_SERVER['REQUEST_METHOD'] == "POST") {
echo $_POST['name'];
}
This is of course very basic. In order to communicate effectively you should look into formating the data e.g. into JSON.

Dropdown list not work with data-native-menu="false"

I use dropdown list with PHP to retrieve data from my sql database, It exists on this link.
It worked well but when I change the menu style what I want, does not work.
this menu code is what I want:
<select name="parent_cat" id="parent_cat" data-native-menu="false" class="filterable-select" data-iconpos="left">
I think the problem exists because the menu shows in popup : `#&ui-state=dialog`
but I do not know how to solve this problem.
this full HTML code :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Dependent DropDown List</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#parent_cat").change(function() {
$(this).after('<div id="loader"><img src="img/loading.gif" alt="loading subcategory" /></div>');
$.get('loadsubcat.php?parent_cat=' + $(this).val(), function(data) {
$("#sub_cat").html(data);
$('#loader').slideUp(200, function() {
$(this).remove();
});
});
});
});
</script>
</head>
<body>
<form method="get">
<label for="category">Parent Category</label>
<select name="parent_cat" id="parent_cat" data-native-menu="false" class="filterable-select" data-iconpos="left">
<?php while($row = mysql_fetch_array($query_parent)): ?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['category_name']; ?></option>
<?php endwhile; ?>
</select>
<br/><br/>
<label>Sub Category</label>
<select name="sub_cat" id="sub_cat"></select>
</form>
</body>
</html>
Please help

autocomplete based on option value

I have here autocomplete from jquery.com. Instead of making a variable to show in autocomplete. I want to show autocomplete from database records. I want only show in autocomplete the records based on dropdown option value. How to do this? Please help me. I'm stuck in here.
This what I have here right now. But how to do this if the comparing value is from option value?
$(document).ready(function(){
$("#tag").autocomplete("autocomplete.php", {
selectFirst: true
});
});
Here's my autocomplete.php
<?php
$mysqli = new mysqli("localhost", "root", "", "2015") or die("Database Error");
$auto = $mysqli->real_escape_string($_GET["q"]);
$sql = $mysqli->query("SELECT * FROM code WHERE item LIKE '%$auto%' GROUP BY id ORDER BY item" );
if($sql)
{
while($row=mysqli_fetch_array($sql))
{
echo $row['item']."\n";
}
}
?>
Here's autocomplete code
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {
var availableTags = [
"ActionScript",
"AppleScript",
];
$( "#tags" ).autocomplete({
source: availableTags
});
});
</script>
</head>
<body>
<select id="main" name="main">
<option value="" disabled="disabled" selected="selected">Choose</option>
<?php echo $option; ?>
</select>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
</body>
</html>
HTML should be
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {
$( "#tags" ).autocomplete({
source: 'yourPHPFile.php?'
});
});
function changeAutoComplete (val) {
$( "#tags" ).autocomplete({
source: 'yourPHPFile.php?selected='+val
});
}
</script>
</head>
<body>
<select id="main" name="main" onchange="changeAutoCompete(this.value)">
<option value="" selected="selected">Choose</option>
<?php echo $option; ?>
</select>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
</body>
</html>
PHP should be like this.
<?php
$mysqli = new mysqli("localhost", "root", "", "2015") or die("Database Error");
$auto = $mysqli->real_escape_string($_GET["term"]);
$selected = $mysqli->real_escape_string($_GET["selected"]);
$sql = $mysqli->query("SELECT * FROM code WHERE item LIKE '%$auto%' AND selected='$selected' GROUP BY id ORDER BY item" );
if($sql)
{
$str = array();
while($row=mysqli_fetch_array($sql))
{
$str[] = $row['item'];
}
echo json_encode($str);
}
?>
This is easily accomplished with basic HTML.
<input list="languages">
<datalist id="languages">
<option value="Dutch">
<option value="English">
<option value="German">
<option value="Chinese">
<option value="Swedish">
</datalist>
Fiddle demo

Can't refresh HTML page

I have a problem. I have made a HTML and PHP page with jQuery, jQuery-ui, jQuery mobile, then kineticjs. When switching to another page, do not refresh the whole page. I also tried using <meta http-equiv="refresh" content="URL=aa.php"> but did not work.
In that page I am also using php to get result from that PHP. Here is the code from my php page :
<?php
if ( isset($_POST['address']) && isset($_POST['prefix']) && isset($_POST['levels']) ) {
require_once 'convert.php';
$network = new Network($ip, $prefix, $levels);
print_html($network);
exit();
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="refresh" content="URL=aa.php">
<title>aa</title>
<link rel="stylesheet" href="css/jquery-ui.css" />
<link rel="stylesheet" href="css/jquery.mobile-1.3.0.css" />
<script src="js/jquery-1.9.1.js"></script>
<script src="js/jquery.mobile-1.3.0.js"></script>
<script src="js/jquery-ui.js"></script>
<script src="js/kinetic-v4.3.2-beta.js"></script>
</head>
<body>
<div data-role="page">
<div data-role="header">
<h3>aa</h3>
</div>
<div data-role="content">
<h3>aa</h3>
<br />
<div>
<label for="address">Address:</label>
<input type="text" id="address">
<select id="prefix">
<?php for ( $i = 49; $i < 64; $i++ ) : ?>
<option value="<?php echo $i; ?>">/<?php echo $i; ?></option>
<?php endfor; ?>
</select>
<label for="subnet">Total Subnets: </label>
<input type="text" id="subnets">
<button class="btn" id="build"> Build It </button>
</div>
<div id="network"></div>
</div>
</div>
<script src="js/jquery.js"></script>
<script type="text/javascript">
$(function(){
$("#build").click(function(){
var subnets = parseInt( $("#subnets").val() );
var address = $("#address").val();
var prefix = $("#prefix").val();
var levels = $("#subnets").val();
$.post("aa.php", {address:address, prefix:prefix, levels:levels}, function(response){
$("#network").html(response);
$("#network > .branch").show();
$("#network .open-children").click(function(){
$(this).text('-');
$(this).parent().children(".branch").toggle();
return false;
});
});
});
});
</script>
</body>
</html>
whether the problem comes from too many javascript?
Meta refresh should work so:
<meta http-equiv="refresh" content="0;url=aa.php">
You can use it without JS.
<noscript><meta http-equiv="refresh" content="0;URL='?nojs=1'"></noscript>
Check if you have any errors in console and remove them. Also you should detect if you have mobile or PC version of browser and include either jquery-1.9.1.js or jquery.mobile-1.3.0.js
you can also use
window.location
with setInterval or setTimeout it'll do the same. But you can't have any JS errors.
you can use this javascript code for refresh your page:
document.location.reload();
or change your location if you want:
document.location = "http://google.com";
Try this,
<meta http-equiv="refresh" content="0;url=aa.php">

Interactive forms with PHP and Ajax via JQuery

I can't make the html loaded via ajax update the DOM. What am I doing wrong?
HTML:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8">
<title>Test</title>
<link rel="stylesheet" type="text/css" href="//atpc.info/f/styles.css" media="all">
<link rel="stylesheet" type="text/css" href="//atpc.info/f/form.css" media="all">
<link rel="stylesheet" type="text/css" href="//atpc.info/f/pesquisa.css" media="all">
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript" src="//atpc.info/f/t/test.js"></script>
</head>
<body>
<form id="form_p" action="">
<fieldset class="p_test">
<legend>Test question text?</legend>
<label for="p_test_y"><input type="radio" id="p_test_y" name="p_test" value="y">Yes!</label>
<label for="p_test_n"><input type="radio" id="p_test_n" name="p_test" value="n">No!</label>
<a class="continue_r">Continue →</a>
</fieldset>
<small id="update_p"></small> <span id="status_p"></span>
</form>
</body>
</html>
JQuery:
$(document).ready(function() {
$('label').css('display','block');
$('a.continue_r').live('click',function(event) {
var id_p=$('input:radio:first').attr('name');
var v_r=$('input:radio:checked').val();
alert(v_r);
$.post(
'test.php',
{ id_p:id_p, v_r:v_r },
function(data){
alert('Retorno:\n' + data);
//$('form').append($(data).hide().fadeIn('slow'));
$('body').append(data);
$('label').css('display','block');
}
);
});
});
PHP:
<?
if(!empty($_REQUEST['id_p'])) $id_p=$_REQUEST['id_p'];
else die('Ops! no id_p');
if(!empty($_REQUEST['v_r'])) $v_r=$_REQUEST['v_r'];
else die('Ops! no v_r');
if($_REQUEST['id_p']=='p_test1') die('Victory!!!');
echo<<<FORM
<fieldset class="p_test1">
<legend>Test 1 question text?</legend>
<small>Last question was $id_p and you option was $v_r</small>
<label for="p_test1_y"><input type="radio" id="p_test1_y" name="p_test1" value="ohy">Oh, Yes!</label>
<label for="p_test1_n"><input type="radio" id="p_test1_n" name="p_test1" value="ohn">Oh, No!</label>
<a class="continue_r">Continue →</a>
</fieldset>
FORM;
?>
For those interested, here is the final working JQuery code:
$(document).ready(function() {
$('label').css('display','block');
$('a.continue_r').live('click',function(event) {
//var fieldset=$(this).closest('fieldset');
var fieldset=$(this).parent('fieldset');
//alert(fieldset.attr('class'));
//var id_p=$('input:radio').attr('name');
//var id_p=fieldset.attr('class');
var id_p=$('fieldset:last').attr('class');
var v_r=$('input:radio:checked:last').val();
if(v_r=='') v_r=$('textarea:last').val();
fieldset.hide();
//alert('id_p = '+id_p+' - v_r = '+v_r);
$.post(
'test.php',
{ id_p:id_p, v_r:v_r },
function(data){
//alert('Retorn:\n' + data);
$('body').append($(data).hide().fadeIn('slow'));
//$('body').append($(data));
//$('body').append($data);
$('label').css('display','block');
//console.log(data);
}
);
});
});
Actually, the DOM is updated. But I think the selector is wrong.
Try this?
$(':radio:checked:last')
This will get the last checked radio input, which is probably what you want instead. Based on the markup:
<fieldset class="p_test">
<legend>Test question text?</legend>
<label for="p_test_y"><input type="radio" id="p_test_y" name="p_test" value="y">Yes!</label>
<label for="p_test_n"><input type="radio" id="p_test_n" name="p_test" value="n">No!</label>
<a class="continue_r">Continue →</a>
</fieldset>
The fieldset tag wraps everything up, so your handler can be defined like:
$('a.continue_r').live('click', function() {
var $fieldset = $(this).parent('fieldset');
// Do stuff like $fieldset.find(), which ensures that your matches are contained therein.
});

Categories