I am using a JS/Ajax function to echo Selected values from select boxes. I am populating these select boxes with values from MySQL DB. The function works with text input fields but now that I am using it with these select boxes I am getting no response.
Can I echo the selected value from a select box with the JS? or Is there a better way? EXAMPLE
JS
<script>
$(document).ready(function() {
var timer = null;
var dataString;
function submitForm(){
$.ajax({ type: "POST",
url: "index.php",
dataType: 'json',
success: function(result){
$('#special').html('<p>' + $('#resultval', result).html() + '</p>');}
});
return false;
}
$('#category_form').on('change', function() {
clearTimeout(timer);
timer = setTimeout(submitForm, 2000);
});
});
</script>
PHP/HTML
try {
$pdo = get_database_connection();
$sql = "SELECT *
FROM `categories`
WHERE `master_id` = 0";
$statement = $pdo->query($sql);
$list = $statement->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
echo 'There was a problem';
}
<form action="" method="post" id="category_form'" name="category_form'">
<select name="main" id="main" size="7" class="update">
<option value="">Select one</option>
<?php if (!empty($list)) { ?>
<?php foreach($list as $row) { ?>
<option value="<?php echo $row['id']; ?>">
<?php echo $row['name']; ?>
</option>
<?php } ?>
<?php } ?>
</select>
<select name="subc1" id="subc1" size="7" class="update"
disabled="disabled" hidden="hidden">
<option value="">----</option>
</select>
<select name="subc2" id="subc2" size="7" class="update"
disabled="disabled" hidden="hidden">
<option value="">----</option>
</select>
<select name="subc3" id="subc3" size="7" class="update"
disabled="disabled" hidden="hidden">
<option value="">----</option>
</select>
</form>
<div id="special"></div>
It looks like you're selecting the wrong element with jQuery.
Change:
$('#category_form').on('change', function() {
clearTimeout(timer);
timer = setTimeout(submitForm, 2000);
});
To:
$('#main').on('change', function() {
clearTimeout(timer);
timer = setTimeout(submitForm, 2000);
});
Related
My page keeps refreshing when I select an item from a listbox. I'm new to Ajax and still learning from it. Here's my code I want to make Ajax code for this one.
<form id="myform" action="home_log.php" method="post">
<label1>Room Type:*</label1>
<select name="roomtype" onchange="this.form.submit();">
<option value="Standard Room A">Standard Room A</option>
<option value="Standard Room B">Standard Room B</option>
<option value="Deluxe Room">Deluxe Room</option>
</select>
</form><br>
<label1>Room Number:*</label1>
<div id="form_output">
<?php
$roomtype = isset($_POST['roomtype']) ? $_POST['roomtype'] : '';
echo "<select>";
include_once 'includes/dbh-inc.php';
$result = $conn->query("select RoomName from tblroom_sample where RoomType='".$roomtype."'");
while ($row = $result->fetch_assoc()) {
unset($roomtype);
$RoomName = $row['RoomName'];
echo '<option value="'.$RoomName.'">'.$RoomName.'</option>';
}
echo "</select>";
?>
</div>
Ajax:
$(document).ready(function () {
$('#myform').on('submit', function(e) {
e.preventDefault();
$.ajax({
url : $(this).attr('action') || window.location.pathname,
type: "GET",
data: $(this).serialize(),
success: function (data) {
$("#form_output").html(data);
},
error: function (jXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
I am trying to implement dependent dropdown using ajax and php. But anyhow the response from second dropdown is not coming. after checking in console, I am able to see the id of first dropdown but no response from second dropdown. So, When i click on first dropdown, I just get a blank value in Second dropdown.
HTML Code
<div class="col-md-6">
<?php
require_once('db.php');
$varient_result = $conn->query('select * from tv_varient');
?>
<select name="varient" id="varient-list" class="form-control c-square c-theme" required>
<option value="">Select Varient</option>
<?php
if ($varient_result->num_rows > 0) {
// output data of each row
while($row = $varient_result->fetch_assoc()) {
?>
<option value="<?php echo $row["id"]; ?>"><?php echo $row["name"]; ?></option>
<?php
}
}
?>
</select>
</div>
</br></br>
<label for="inputPassword3" class="col-md-4 control-label" style="margin-left: 15px;">Price:</label>
<div class="col-md-6">
<select name="price" id="price-list" class="form-control c-square c-theme" required>
<option value=''>Select Price *</option>
</select>
<div>
</div>
</div>
</div>
</div>
</div>
AJAX Code
<script>
$('#varient-list').on('change', function(){
var varient_id = this.value;
$.ajax({
type: "POST",
url: "get_price.php",
data:'varient_id='+varient_id,
success: function(result){
$("#price-list").html(result);
}
});
});
</script>
get_price.php
?php
require_once('db.php');
//$country_id = mysqli_real_escape_string($_POST['country_id']);
//var_dump($country_id);
//var_dump($_POST['country_id']);
$varient_id = $_POST['veriant_id'];
echo $varient_id;
//var_dump($varient_id);
var_dump($_POST['varient_id']);
if($varient_id!='')
{
$states_result = $conn->query('select * from tv_price where veriant_id='.$varient_id.'');
$options = "<option value=''>Select Price</option>";
while($row = $states_result->fetch_assoc()) {
$options .= "<option value='".$row['price']."'>".$row['price']."</option>";
}
echo $options;
}
?>
Try below code,
$(document).on('change', '#varient-list', function(e)
{
var varient_id = this.value;
$.ajax({
type: "POST",
url: "get_price.php",
data:'varient_id='+varient_id,
success: function(result){
$("#price-list").html(result);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
varient_id & veriant_id on the POST is wrong (the e & a difference).
$varient_id = $_POST['veriant_id']; should be $varient_id = $_POST['varient_id'];
I want to get some data via Ajax, but there must be some mistake because the result is empty
script:
<script>
function showUser(value) {
var values = $(this).serialize();
$.ajax({
url: "test.php",
data: {
id: value
},
type: "POST",
success: function(data){
$("#result").html(data);
}
})
}
</script>
html:
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Joseph Swanson</option>
<option value="4">Glenn Quagmire</option>
</select>
</form>
<br>
<div id="result"></div>
test.php:
<?php
$id = #$_POST['id'];
$pdo = $db->query('SELECT * FROM people WHERE id = "' . $id . '"');
while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
echo $row['id'];
}
?>
HTML:-
<select id ="myselect" name="users" onchange="showUser()">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Joseph Swanson</option>
<option value="4">Glenn Quagmire</option>
</select>
<br>
<div id="result"></div>
Javascript:-
<script>
function showUser() {
$.ajax({
url: "test.php",
data: {
id: $( "#myselect option:selected" ).val();
},
type: "POST",
success: function(data){
$("#result").html(data);
}
});
}
</script>
PHP:-
<?php
if(isset($_POST['id'])){
$id = $_POST['id'];
// i don't know from where $db is coming so check yourself
$pdo = $db->query('SELECT * FROM people WHERE id = "'.$id.'" LIMIT 1');
while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
echo $row['id'];
}
}else{
echo "Please select value from select box";
}
?>
Note:-
Meanwhile read about prepared statements and use them to prevent from SQL Injection. Thanks
If you dont want to use jquery, you can do something like this:-
var http = new XMLHttpRequest();
var url = "****Some URL (php etc to process the sql data)******";
var p = hex_sha512(userPass.value);
var params = "email="+userEmail.value+"&p="+p+"&adminStat=true";
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send(params);
http.onreadystatechange = function() {
if (http.readyState == 4) {
//Todo
// check addition stat and go to the destination page
if (http.responseText == "success") {
window.location = "*****Destination URL********";
} else {
alert("error");
}
}
};
I have a drop menu that includes some category every category has their own subcategory i want to show them buy selecting category name
but it's not working, did i miss something or am i doing it completely wrong?
<script type="text/javascript">
$(function() {
$("#error").hide();
$("#category").change(function(){
$("#error").hide();
var category = $("#category").val();
if (category == "") {
$("#error").show();
return false;
}
var data = $("#form").serialize();
$.ajax({
type:"POST",
url:"index.php",
data:data,
success: function(){
}
});
return false;
});
});
</script>
<form id="form" name="form">
<label for="category" id="error">Empty</label>
<select name="category" id="category">
<option></option>
<option value="News">News</option>
<option value="Items">Items</option>
<option value="Updates">Updates</option>
</select>
</form>
<?php
include("connect.php");
if(!empty($_POST['category'])){
$sql=$con->prepare("SELECT * FROM categorys WHERE category=:category ");
$sql->bindparam(":category",$_POST['category']);
$sql->execute();
while($r=$sql->fetch()){
echo $r['subcategory'];
}
}
?>
SomePage.php
<form id="form" name="form">
<div id='category'>
<label for="category" id="error">Empty</label>
<select name="category" id="category">
<option></option>
<option value="News">News</option>
<option value="Items">Items</option>
<option value="Updates">Updates</option>
</select>
</div>
<div id='subcategory'>
</div>
</form>
<script>
$('#category').change(function(){
var CatName= $('#category').val();
$.ajax({url:"AjaxSelectCategory.php?CatName="+CatName,cache:false,success:function(result){
$('#subcategory').html(result);
}});
});
</script>
Create New Page AjaxSelectCategory.php
[NOTE: If you want to change this page name. Change in <script></script> tag too. Both are related.]
<?php
include("connect.php");
if(!empty($_GET['CatName']))
{
$sql=$con->prepare("SELECT * FROM categorys WHERE category=:category ");
$sql->bindparam(":category",$_GET['CatName']);
$sql->execute();
?>
<select name='subcategory'>
<?php
while($r=$sql->fetch())
{?>
<option value="<?php echo $r['subcategory'];?>"><?php echo $r['subcategory'];?></option>
</select>
<?php }
}?>
Try like this,
$.ajax({
type:"POST",
url:"get_subcategory.php",
data:data,
success: function(data){
alert(data)// this will have the second dropdown. add to desired place in your view.
}
});
In get_subcategory.php
$sql = "Select * from table_name where catregory = ".$_POST'category'];
// execute the query.
$sub = "<select name='sub-category'>";
foreach(result from database as $row) {
$sub .= "<option value='$row->id'>$row->name</option>";
}
$sub .= "</select>";
echo $sub;
<script>
$(document).ready(function() {
$("#update_item").change(function (e) {
var update_item = $("#update_item").serialize();
$.post("item.php", {"update_item": update_item}, function (data) {
$('#details').html(data);
});
});
});
</script>
<select name="update_item" multiple="multiple" class="form-control" style="width:59%" id="update_item">
<option value="fff">fffffff</option>
<option value="ffff">Select Supplier</option>
<?php
$result = mysql_query("select * from item");
while ($row = mysql_fetch_array($result)){?>
<option value="<?php echo $row['item_name'];?>"><?php echo $row['item_name'];?></option>
<?php } ?>
</select>
<div id="details">
hii
</div>
Current output: update_item=fff&update_item=ffff&update_item=fdgdfgjkljklkj
Expected Output: fff,ffff,fdgdfgjkljklkj (implode post values).
You should define your HTML variable as an array ('update_item[]') and then serialize it so when you do:
var_dump($_POST['update_item'])
there will be an array data type, check:
<script>
$(document).ready(function() {
$("#update_item").change(function (e) {
$.post("item.php", $(this).serialize(), function (data) {
$('#details').html(data);
});
});
});
</script>
<select name="update_item[]" multiple="multiple" class="form-control" style="width:59%" id="update_item">
<option value="fff">fffffff</option>
<option value="ffff">Select Supplier</option>
<?php
$result = mysql_query("select * from item");
while ($row = mysql_fetch_array($result)){?>
<option value="<?php echo $row['item_name'];?>"><?php echo $row['item_name'];?></option>
<?php } ?>
</select>
<div id="details">
hii
</div>
Hope it helps!