Onchange populate different dropdown based on value - javascript

I'm trying to populate the second dropdown after I select the first option, nothing appears in the second dropdown.
My first select:
<select name="inst" class="form-control" required="" id="inst">
<option value=0 selected=1>Select...</option>
<?php
$sql="SELECT * FROM sapinst";
$myData=mysqli_query($GLOBALS['con'],$sql);
if (mysqli_num_rows($myData) > 0){
while ($row = mysqli_fetch_array($myData))
{
echo '<option value="' .$row["nbd"]. '">' .$row["nome"]. '</option>';
}
}
else{echo "No categories were found!";}
?>
</select>
My second select:
<select id= "sub" name="sub" class="form-control"></select>
My Script:
<script type="text/javascript">
$("#inst").change(function () {
//get category value
var cat_val = $("#inst").val();
// put your ajax url here to fetch subcategory
var url = '/ajax.php';
// call subcategory ajax here
$.ajax({
type: "POST",
url: url,
data: {
cat_val: cat_val
},
success: function (data)
{
$("#sub").html(data);
}
});
});
</script>
My Ajax.php file:
<?php
require_once 'edp/configdbedp.php';
$prod_cat = $_POST['cat_val'];
$sql = "SELECT * FROM " . $dbname . ".sappainel WHERE nbd = '$prod_cat'";
$result = mysqli_query($conn, $sql);
$msg = '';
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$msg =. '<option value="' . $row["nome"] . '">' . $row["nome"] . '</option>';
}
} else {
$msg .= "No categories were found!";
}
echo $msg;
mysqli_close($conn);
?>
if I try to print some thing in the Ajax php I can't...seems ajax.php won't run.
Am I calling it correctly?

Is your second ajax being called properly?
Check the console messages(in developer options, F12) for errors in ajax call.
you might want to do this as both cat_val are same. It might be giving an error. -
data: {
cat_val: cat_val_local //different variable names here.
},
Also "Select * from $TABLE_NAME(not #dbname)"
and next remove extra .[dot] here -> ".sappainel WHERE"
you can also try put console.log() in success callback and see if the success is returning any elements.
success: function (data)
{
console.log(data);
$("#sub").html(data);
}
If nothing is shown then your php might be wrong. Add an eror callback too! like this -
error: function (e)
{
console.log(e);
}
Hope this helps.

I already solved
Diferences on scrip:
<script type="text/javascript">
$("#inst").change(function(){
//get category value
var cat_val = $("#inst").val();
// put your ajax url here to fetch subcategory
var url = 'ajax.php';
// call subcategory ajax here
$.ajax({
type:"POST",
url:url,
data:{
cat_val : cat_val
},
success:function(data)
{
$("#sub").html(data);
}
});
});
</script>
On ajax.php
<?php
require_once 'edp/configdbedp.php';
$prod_cat = $_POST["cat_val"];
$sql = "SELECT * FROM ".$dbname.".sappainel WHERE nbd = '$prod_cat'";
$result = mysqli_query($GLOBALS['con'], $sql);
$msg ='';
if (mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_array($result))
{
$msg .='<option value="'. $row["nome"] .'">'. $row["nome"] .'</option>';
}
}
else{$msg .="No categories were found!";}
echo ($msg);
mysqli_close($GLOBALS['con']);
?>

Related

Getting json data back from php without reloading

I need to send a value from a form to php, get data from a database based on the posted value, store all the data in json and then change an input value to the value of the json. All that without reloading the page because I can't lose the stuff that user has input already in the form.
Here is the select where I get the value from:
<select name="groupName" id="groupName" class="form-control message" onchange="group_select()">
<?php
$user_id = $_SESSION["id"];
$sql = mysqli_query($link, "SELECT group_name FROM SMAILY_groups WHERE user_id = '".$user_id."'");
while ($row = $sql->fetch_assoc()){
echo "<option value='".$row['group_name']."'>" . $row['group_name'] . "</option>";
}
?>
</select>
The changing of the value is handled by this function:
function group_select(){
$.ajax({
url:'send.php',
type:'post',
data:$('#smsForm').serialize(),
success:function(data){
}
});
}
And php that handles it is this:
$groupName = $_POST["groupName"];
$user_id = $_SESSION["id"];
$stack = array();
$sql = "SELECT phone FROM SMAILY_groups_numbers t1 INNER JOIN SMAILY_groups
t2 ON t1.group_id = t2.group_id WHERE t2.user_id = '".$user_id."' AND
t2.group_name = '".$group_name."'";
$result = mysqli_query($link, $sql);
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
array_push($stack, $row["phone"]);
}
$stack = json_encode($stack);
$result->free();
Now I need to get the phone numbers that I got from the database, and assign them as a value to one of my input fields. I need to do this without refreshing the page. I'm pretty sure it's somehow done in the ajax success function but I just don't know how.
You are correct, it is done in the success callback. Actually it's pretty simple: Create a <input type="hidden" name="phonenumbers" id="phonenumbers"> element in your HTML.
<select name="groupName" id="groupName" class="form-control message" onchange="group_select()">
<?php
...
?>
</select>
<input type="hidden" name="phonenumbers" id="phonenumbers" value="">
Then, on each request, append the returned value(s) to the value of that <input> element. Don't forget to add a separator though! I use comma.
For example:
function ajaxSuccessHandler (data) {
var hiddenInput = document.querySelector('#phonenumbers');
if (hiddenInput.value.length >= 1) {
// if there are already one (or more) numbers in the hidden input
hiddenInput.value += ',' + data.join(',');
} else {
hiddenInput.value = data.join(',');
}
}
You can either call that function inside the success callback or as your success callback. So this:
function group_select(){
$.ajax({
url:'send.php',
type:'post',
data:$('#smsForm').serialize(),
success: ajaxSuccessHandler
});
}
or this:
function group_select(){
$.ajax({
url:'send.php',
type:'post',
data:$('#smsForm').serialize(),
success: function (data) {
ajaxSuccessHandler(data);
}
});
}
should produce the same result.
You Can try this
<select name="groupName" id="groupName" class="form-control message" onchange="group_select()">
<?php
$user_id = $_SESSION["id"];
$sql = mysqli_query($link, "SELECT group_name FROM SMAILY_groups WHERE user_id = '".$user_id."'");
while ($row = $sql->fetch_assoc()){
echo "<option value='".$row['group_name']."'>" . $row['group_name'] . "</option>";
}
?>
</select>
Javascript Code Dont Forget to Include jquery in your page head
<script>
function group_select(){
let groupName = document.getElementById('groupName').value;
$.ajax({
url:'send.php?groupName='+groupName,
type:'GET',
success:function(data){
var obj = jQuery.parseJSON(data);
//Field to which you want to sent value
document.getElementById('fieldName').value = obj.variableName;
}
});
}
</script>
send.php will look some what like this
$groupName = $_GET["groupName"];
$user_id = $_SESSION["id"];
$stack = array();
$result = mysql_query("SELECT phone FROM SMAILY_groups_numbers t1 INNER JOIN SMAILY_groups
t2 ON t1.group_id = t2.group_id WHERE t2.user_id = '".$user_id."' AND
t2.group_name = '".$group_name."'");
$row = mysql_fetch_assoc($result);
echo json_encode($row);

get selected list option from database

i have to get select option list from my database
and for this my controller is
<?php
require_once 'connexion.php';
$sql = "select * from Motif";
$stmt = sqlsrv_query($conn, $sql);
if ($stmt === false)
{
die(print_r(sqlsrv_errors() , true));
}
$data = array();
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
{
$data["id"] = $row['id'];
$data["libelle"] = utf8_encode($row['libelle']);
echo json_encode($data);
}
echo json_encode($data);
exit;
?>
and my html like this
<select id="rejetselect" class="form-control">
<option value="" selected="selected"></option>
</select>
and to get values from database with ajax i did this code
var $select = $('#rejetselect');
$.ajax({
url: 'motifRejet.php',
dataType: 'json',
data: 'libelle',
success: function() {
alert('good');
},
error: function() {
alert('nooo');
}
});
so after testing all this i can see my alert in good and in my console i can see the information that i got from database but i can't see it in my select option

I can not display the data from my json_encode ($.each)

Hello to every one and thank you for your time.
My problem is that i can not display the json_encode from my php database but in my chrome the data is appear.
The $.each is not dispaly all only one
enter image description here
now the code for the php :
comment.php
$data = $_REQUEST;
$photo_id =38;//$data['photo_id_comment'];
$con = mysqli_connect('localhost','root','','gallery');
$sql = "SELECT * FROM comments";
$sql .= " WHERE photo_id = " . $database->escape_string($photo_id);
$sql .= " ORDER BY photo_id ASC";
$result = mysqli_query( $con,$sql);
$arr = array();
$row_count = mysqli_num_rows($result);
while ($row = mysqli_fetch_array($result)) {
array_push($arr , $row);
}
mysqli_close($con);
echo json_encode($arr);
And the ajax to retrieve data is: script.js
function refreshComment() {
requestData = $("#photo_id_comment").serialize();
$.ajax({
url: "http://localhost/udemy/app_php/includes/comment.php",
type: "get",
data: requestData,
dataType: "text",
success : function (data) {
jQuery.each(data, function(index, item) {
//now you can access properties using dot notation
$('#chat_box').val( $('#chat_box').val() + item.body + '\n');
/* $('#author_comment').html(item.author);
$('#chat_box').html(item.body);*/
});
},
error: function (http, status, error) {
alert('Some error occurred :'+error);
}
});
return false;
}
setInterval( refreshComment , 5000 );
And the html where the data is not display is: photo.php.
<div class="media">
<a class="pull-left" href="#">
<img class="media-object" src="http://placehold.it/64x64" alt="">
</a>
<div class="media-body">
<h4 id="author_comment" class="media-heading"></h4>
<p id="chat_box"></p>
<p class="text-info">This is post at: </p>
</div>
</div>
Please try this one,
$sql = "SELECT * FROM comments WHERE photo_id = " . $database->escape_string($photo_id) ORDER BY photo_id ASC";
$result = mysqli_query( $con,$sql);
$arr = array();
while ($row = mysqli_fetch_array($result)){
$arr[] = $row;
}
echo json_encode($arr);
and change ,
dataType:'json' instead of dataType:'text'
in script.
change dataType:text to dataType:JSON
EDIT
use this instead of $.each
for(var i = 0;i < data.length ; i++)
{
/*access data as data[i].orfeas*/
}
PHP
$array = array();
$i = 0;`
foreach($res as $r){
$array[$i] = $r;
$i++;
}
header('Content-Type:Application/json');
echo json_encode($array);
EDIT2
USE Header to help jQuery to identify the response type and then jQuery will parse the JSON and you can access it by using a loop above mentioned
in your script.js file make change on success function of ajax:-
success : function (data) {
$.each($.parseJSON(data), function(key,item){
$('#chat_box').val( $('#chat_box').val() + item.body + '\n');
});
}

select option in php and mysql.. once option selected list down my sql database data

I been finding for long unable to search for it.. I have a dropdown select option call from mysql database.. I wanted when the user choose a employee from the option.. when selected.. it's list out the data from mysql database the employee data that is selected. here the code..
<select value="employee" selected="selected"> Select a employee</option>
<?php
$query = "SELECT * FROM users";
$result = mysqli_query($link,$query);
while ($row = mysqli_fetch_array($result)) {
$fname = $row["first_name"];
$lname = $row["last_name"];
echo "<option value'" . $fname . " " . $lname ."'>" . $fname . " " . $lname . "</option>";
}
?>
</select>
sorry i'm new to js.. how do I get the data from selected value?
First of all edit your page and add jquery library
<select id="listEmployee" value="employee" selected="selected"> Select a employee</option>
<?php
$query = "SELECT * FROM users";
$result = mysqli_query($link,$query);
while ($row = mysqli_fetch_array($result)) {
$fname = $row["first_name"];
$lname = $row["last_name"];
$id = $row["id"];
echo "<option value'" .$id."'>" . $fname . " " . $lname . "</option>";
}
?>
</select>
Then you should listen to select change
$( "#listEmployee" ).change(function() {
getSelectedEmplpyee();
});
Then create an ajax function that get informations about the selected employee
function getSelectedEmplpyee()
{
var selectedId = $('#listEmployee').val();
$.ajax({
type: "POST",
url: "Controller.php",
data: {selected: selectedId},
success: function(data) {
//display response
},
error: function(data) {
// display error
}
});
}
in controller.php read the id using
$id = $_POST['selected']
in controller.php run your select query and return result using echo ,
the result is stored in the variable data in your function getSelectedEmplpyee()
Try to do like this:
var selected_value = $('#your_select_id').val();
$.ajax({
type: "POST",
url: "your_url",
data: {selected: selected_value},
success: function(data) {
//display response
},
error: function(data) {
// display error
}
});

how to select the select box item based on another and vice versa

how to select the select box item based on one another and vice versa.here I use ajax for redirect to query page.
while($fet = mysql_fetch_assoc($sql1))
{
echo "<option value=".$fet['username'].">".$fet['username']."</option>";
}
echo '</select></td>';
echo "<td><div id='myDiv'><select id=id name=id onchange=loadXMLDoc()>";
$sql = "select * from sample";
$sql1 = mysql_query($sql);
while($fet = mysql_fetch_assoc($sql1))
{
echo "<option value=".$fet['id'].">".$fet['id']."</option>";
}
echo '</select></div></td>';
You Need To Use Ajax For That,
For Example You Have A Select like This
<select id=id1 name=id1 onchange=loadXMLDoc()>
here is the second one you want to change
<select id=id2 name=id2>
On Javascript You Call a php file via ajax Like This
function loadXMLDoc(){
$.ajax({ // i think you used jquery on your project
type: "post",
url: "getdata.php",
data: $('input[\'name=id1\']'),
dataType: "json",
success:(function(result){
html = '';
if(result.data.length > 0){
$.each(result.data, function( index, value ) {
// alert( index + ": " + value );
html += '<option value="'+value.id+'">'+value.title+'</option>';
});
$('#id2').html(html);
}else{
// nothing
}
}));
});
}
then on php file you just echo the json_encode result you want to get
$sql = mysql_query('SELECT id,title FROM your_table Where your_field='.$_POST['id1']);
$query= mysql_query($sql);
while( $row = mysql_fetch_array($query)){
$json['data'][] = array('id' =>$row->id,'title'=>$row->title )
}
echo json_encode($json);

Categories

Resources