Updating div based on dropdown response without refreshing - javascript

I am trying to create a dropdown that will update text on a page without refreshing the page. The updated text will be supplied by a php function which is passed a value from the dropdown. Right now, my dropdown does nothing, but here is where I've managed to get:
webpage.php:
My dropdown. Populated by a database.
<form method='post'>
<select name="skill1_level" id="skill1_level" onchange="skill1ValueChange(this.value)">
// PHP to dynamically populate list from the DB
<?php foreach ($skill_levels as $key => $skill_levels_list): ?>
<option value=""><?= $skill_levels_list->skill_level ?></option>
<?php endforeach ?>
</select>
</form>
My div. Currently just loading a default string. Need to figure out how to make this change when the dropdown is submitted. Not sure how to use AJAX here.
<div class="panel-body" id="skill1_text">
<?php echoSkill($hero->skill1_desc, $placeholders, $id_hero, 1, 1, $dbh); ?>
</div>
functions.js. Javascript to be called when dropdown is submitted. Calls PHP function.
function skill1ValueChange(skill_level) {
$.ajax({
url: 'functions.php',
type: 'POST',
data: {option : skill_level},
success: echoSkill($hero->skill1_desc, $placeholders, $id_hero, 1, skill_level, $dbh) {
console.log("Data sent for skill1.");
}
});
functions.php. does some stuff to my data based on the dropdown value, then echos the resulting string.
function echoSkill ($skill_desc, $placeholders, $id_hero, $skill_num, $skill_level, $dbh) {
$skill_values = fetchSkillValues($id_hero, $skill_num, $skill_level, $dbh);
$skill_values = array($skill_values[0]->skill_x, $skill_values[0]->skill_y, $skill_values[0]->skill_z, $skill_values[0]->skill_a);
$skill_desc = str_replace($placeholders, $skill_values, $skill_desc);
echo $skill_desc;
}
Any help and explanation you can provide would be greatly appreciated!

Probably the easiest for you would be to return HTML from your functions.php (actually, you should probably have it reference a different page that includes the functions.php page and echos the echoSkill() function) file:
Page with dropdown:
<!-- I assume you already have the libraries...-->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<form method='post'>
<!--You can just add the change in the jQuery instead of inline js -->
<select name="skill1_level" id="skill1_level">
<option value="1">Value 1</option>
<option value="2">Value 2</option>
<option value="3">Value 3</option>
<option value="4">Value 4</option>
</select>
<!-- This is where your empty div will fill with the php content -->
<div class="panel-body" id="skill1_text"></div>
</form>
<script>
// Select by the <select> named "skill1_level"
// When changed...
$("select[name='skill1_level']").change(function() {
// Assign the selection's value
var OptionVal = $(this).val();
$.ajax({
url: 'functions.php',
type: 'post',
data: { option: OptionVal },
// You need a success function here
success: function(response) {
// This will print out the response from your php page
// to the div on this page called "skill1_text"
$("#skill1_text").html(response);
}
});
});
</script>
functions.php
<?php
//code here to return just the text or whatever
// You should actually have the ajax call a page that has the "echoSkill()"
// function on it rather than the function page itself
echo 'Response to ajax page.';
echoSkill($blah,$blah2,$blah3,$blah4,$blah5,$blah6);
print_r($_POST);
?>

Related

Why cant I send data through this ajax?

Hey guys I have been trying to hook up Html select element with ajax to change the language on my website. The idea is to send the value of select thought ajax to PHP file where I would then use that value as a session to include other PHP files with language variables.
Everything works ok, but for some reason, the PHP file is not getting the data from ajax.
So here is the code:
HTML:
<div class="lang langMobile" style="opacity: 1; transform: translateX(0px);" >
<div data-uk-form-custom="target: true" class="uk-form-custom">
<select class="custom-select custom-select-mobile"id="language_custom-select">
<option class="custom-option" hidden> <?php echo $_SESSION['lang']?></option>
<option class="custom-option" value="En"> En</option>
<option class="custom-option" value="Bs">Bs</option>
</select>
</div>
</div>
JS:
$('#language_custom-select').change(function() {
var optionValue = $('#language_custom-select').val();
console.log(optionValue)
$.ajax({
url:'switch.php',
method: 'POST',
data: {selected: optionValue},
}).done(function(data) {
window.location.reload();
})
})
PHP:
if(isset($_POST['selected'])) {
$_SESSION['lang'] = $_POST['selected'];
} else if (!isset($_SESSION['lang'])) {
$_SESSION['lang'] = "En";
}
include "include/" . $_SESSION['lang'] . ".php";

jquery ajax post to self not working

i am taking a value from the dropdown using jquery on change , i am using ajax to post to self, but i am not able to echo the posted variable.
<form>
<label>Select Doctor:</label>
<select class="docdrop">
<option value="">Choose</option>
<option value = "123">doca</option>
<option value = "456" >docb</option>
</select>
</form>
<script>
$(document).ready(function(){
$("select.docdrop").change(function(){
var d_Id = $(this).val();
if(d_Id!="")
{
$.ajax({
type: "POST",
url: "<?php echo $_SERVER['PHP_SELF'];?>",
data: {d_id1 : d_Id}, //using 'd_id1' did not make a change
success: function(){
alert(d_Id]);
}
});
}
});
});
</script>
//php code in same page
<?php
if(isset($_POST['d_id1']))
$d_Id = $_POST['d_id1'];
?>
<p><?php echo $d_Id; ?></p>
i get the alert on success but , i am unable to echo the posted variable. i dont want to use serialize() or post the entire form. just d_Id whic i obtain in jquery
If you want you can do this without using jQuery in this way :
<?php
$d_id1 ="";
if(isset($_POST['d_id1'])){
$d_Id = $_POST['d_id1'];
echo $d_Id;
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
</head>
<body>
<form>
<label>Select Doctor:</label>
<select class="docdrop" >
<option value="">Choose</option>
<option value = "123">doca</option>
<option value = "456" >docb</option>
</select>
</form>
<script>
$(document).ready(function(){
$("select.docdrop").change(function(){
var d_Id = $(this).val();
if(d_Id!="")
{
$.ajax({
type: "POST",
url: "<?php echo $_SERVER['PHP_SELF'];?>",
data: {d_id1 : d_Id},
success: function(data){
d_id1 = data;
document.getElementById('name').innerHTML = d_id1;
console.log(data);
}
});
}
});
});
</script>
<p id ="name"><?php echo $d_id1;?></p>
</body>
</html>
php code execute one time on page load, so that time your variables $d_Id and $d_Id1 are not created, so it is not display any value.
also ajax execute without page refresh and all code in side success executed without any error.
success: function(data){
alert(data);
}
You will alert the data send from backend i.e. echoed by your php part, which in your case will be the result of <p><?php echo $d_Id; ?></p>, if you just need your $d_id selected without the paragraph tags change your code to <?php echo $d_Id; ?>. Of course you may prefer to use JSON as output of your backend and then parse it in the success callback with $.parseJSON(data) per instance or use data type 'json' in your AJAX reques.

Append json data to HTML List box

HTML code is :
<select name="ser" id="ser" class="form-control" onchange="getPrice(this.value);">
<option value="">--Select--</option>
<option value="Value11">Value1</option>
<option value="Value2">Value2</option>
</select>
<select name="freeitem" id="freeitem" class="form-control">
</select>
Js Code :
function getPrice(val) {
$.ajax({
type: 'post',
url: 'get_sales_price.php',
data: {
get_option: val
},
dataType: 'json',
success: function(response) {
console.log(response)
$('#freeitem').html(response.fritm);
}
});
}
and Php Code is :
$option = $_POST['get_option'];
$data = array();
$prdqty = $db->execute("select product_name from master_purchase where product_code='$option' and delet='0'");
while ($tqty = $prdqty->fetch_assoc())
{
$data['fritm'] = '<option value="'.$tqty['product_name'].'">'.$tqty['product_name'].'</option>';
}
echo json_encode($data);
while we selecting first selectbox content, need to add some data to second select box from database, we almost done the things but the second select box didn't show any values ,please help us to resolve the above problem
I tried your code with some hard code value and it perfectly working fine:-
Html+Jquery (in single page with .html extension):-
<select name="ser" id="ser" class="form-control" onchange="getPrice(this.value);">
<option value="">--Select--</option>
<option value="Value11">Value1</option>
<option value="Value2">Value2</option>
</select>
<select name="freeitem" id="freeitem" class="form-control">
</select>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script><!-- added jquery library-->
<script type="text/javascript">
function getPrice(val) {
$.ajax({
type: 'post',
url: 'get_sales_price.php',
data: {
get_option: val
},
dataType: 'json',
success: function(response) {
console.log(response)
$('#freeitem').html(response.fritm);
}
});
}
</script>
Php (with hard-coded value):-
<?php
$option = $_POST['get_option'];
$data = array();
$data['fritm'] = ''; // you need to define it as empty string first
for($i = 0;$i<10;$i++) // hard-code started
{
$data['fritm'] .= '<option value="'.$i.'">'.$i.'</option>'; // append each option to the string one-by-one and check `.=` also
}
echo json_encode($data);
Output:-
http://prntscr.com/auyn7i
http://prntscr.com/auymzf
http://prntscr.com/auynij
Note:- problem may be occuring because either you missed jquery library of concatenation inside loop or some other error in your php file.
You need to do two things:
1) concatenate results in while loop. You are re-assigning the array variable causing latest one to overwrite the old one.
This way, only old value will be appended.
Change
$data['fritm'] = '<option value="'.$tqty['product_name'].'">'.$tqty['product_name'].'</option>';
To
$data['fritm'] .= '<option value="'.$tqty['product_name'].'">'.$tqty['product_name'].'</option>';
2) Change
$('#freeitem').html(response.fritm);
To
$('#freeitem').append(response.fritm);
As you are just appending options to drop down, not changing its HTML.

populate text boxes depend on drop-down selection in php

I research in google and stack overflow for this answer there are lot of answer but i cannot able to get what i want.
I have two drop down menus and three text boxes.
PHP Code :
<select onchange="FirstDropDownClick()"> </select>
script code :
<script type="text/javascript">
function FirstDropDownClick() {
var selectDwn = document.getElementById("ID_dwn");
var selectedValue = selectDwn.options[selectBox.selectedIndex].value;
}
In "FirstDropDownClick()" i want the codes for the following :
1.select data from database according to the selected value.
2.Fill the text boxes with that.
3.Fill second drop down according to value of first drop-down menu.
I need an example codes. Because am stuck , dont know how to do .
Thanks in Advance.
your html code
<select name="reg_number" id="reg_number">
<option value="1">Reg1</option>
<option value="2">Reg2</option>
<option value="3">Reg3</option>
</select>
<input type="text" name="first_name" id="first_name">
your jquery(make sure you include jquery file)
$(document).ready(function(){
$('#reg_number').change(function(){
var reg_number = $(this).val();
var data_String;
data_String = 'reg_number='+reg_number;
$.post('ajax_file.php',data_String,function(data){
var data= jQuery.parseJSON(data);
$('#first_name').val(data.first_name)
});
});
});
your php code (ajax_file.php)
<?php
$reg_number =$_POST['reg_number'];
//run your query here to fetch the result and store it in a variable $data
echo json_encode($data);
exit();`
?>
If you want to do it with ajax and php
HTML
<select name="select_number" id="select_number">
<option value="1">Number1</option>
<option value="2">Number2</option>
<option value="3">Number3</option>
</select>
<input type="text" name="number_value" id="number_value">
JQuery
$(document).ready(function(){
$('#select_number').change(function(){
var number_value = $(this).val();
$.ajax({
method: 'POST',
url: "test.php",
data: {
'number_value' : number_value
},
dataType:'json',
success: callback = function(data, textStatus, xhr)
{
$('#number_value').val(data.number_value);
}
});
});
});
php (test.php)
<?php
echo json_encode($_POST);
?>
why you need php for that you can do it only with jquery or javascript
HTML
<select name="select_number" id="select_number">
<option value="1">Number1</option>
<option value="2">Number2</option>
<option value="3">Number3</option>
</select>
<input type="text" name="number_value" id="number_value">
Jquery
$(document).ready(function(){
$('#select_number').change(function(){
var number_value = $(this).val();
$('#number_value').val(number_value);
});
});

Why does this ajax script copied selectbox?

I just trying city-state select. I think this code blocks print the posting data to screen.. but it copies selectbox and then prints the selectbox to screen. Isn't it weird?
$(document).ready(function(){
$('#ilce').change(function(){
var ilceid = $('#ilce').val();
$.ajax({
type: 'POST',
url: 'ilce/ajax',
data: 'ilceid'+ilceid,
success: function(sonuc){
$('#ilce').css('background-color','#efefef');
$('#semt').html(sonuc);
}
});
});
});
html is:
<?php echo form_open('ilce/index')?>
<select id="ilce" name="ilce">
<option value="">Select Town</option>
<?php foreach ($ilce as $x):?>
<option value="<?php echo $x['id']?>"><?php echo $x['ad']?></option>
<?php endforeach?>
</select>
<p id="semt"></p>
and, ilce/ajax controller which must print the post data???
<?php
class Ilce extends CI_Controller{
public function ajax()
{
print_r($_POST);
}
} //end of controller
As I said, this code must be print post data in <p id="semt"></p> right?
But this code just copies <select> and after .change() immediately paste to screen then there becomes 2 selectboxes.

Categories