How to transfer data from javascript to php with OnChange - javascript

im trying to get some data from a DropDown menu and i want to use that value when it change to make a Query in a secound DropDown but until now, i was unable to send the Value to my php with the javascript.
Im using this code:
<script type="text/javascript" language="javaScript">
function flow() {
var x = document.getElementById("txt_maq").value;
document.getElementById("demo").innerHTML = x;
var maq = document.getElementById('txt_maq').value;
var cat = document.getElementById('txt_catmaterial').value;
if (maq != "")
{
document.getElementById('txt_catmaterial').disabled=false;
}
if (cat == "")
{
document.getElementById('txt_material').disabled=true;
}
if (cat != "")
{
document.getElementById('txt_material').disabled=false;
}
}
</script>
<div class="col-2">
<div class="input-group">
<label class="label">Maq. Destino</label>
<div class="rs-select2 js-select-simple select--no-search">
<select id="txt_maq" name="txt_maq" onchange="flow()">
<option value="">Selecione</option>
<option value="E02">E02</option>
<option value="E03">E03</option>
<option value="E04">E04</option>
<option value="E05">E05</option>
<option value="E06">E06</option>
<option value="E07">E07</option>
<option value="E08">E08</option>
<option value="E04/E07">E04/E07</option>
<option value="E04/E08">E04/E08</option>
<option value="E03/E04">E03/E04</option>
<option value="E03/E07">E03/E07</option>
<option value="E04/E07/E08">E04/E07/E08</option>
<option value="E03/E07/E08">E03/E07/E08</option>
<option value="E07/E08">E07/E08</option>
<option value="E09">E09</option>
</select>
<div class="select-dropdown"></div>
</div>
</div>
</div>
</div>
<div class="row row-space">
<div class="col-2">
<div class="input-group">
<label class="label">Cat. Material</label>
<div class="rs-select2 js-select-simple select--no-search">
<select id="txt_catmaterial" disabled="true" name="txt_catmaterial" onchange="flow()">
<option value=""></option>
<?php
$maquina = $_POST['txt_maquina'];
$type_te = "";
if ($maquina == "E09"){
$type_te= "ET";
} else {
$type_te= "EP";
}
echo $type_te;
$selecione = "";
$consulta = "SELECT Cat_Material FROM cat_mat where TE = '".$type_te."' "; //código SQL
$resultado = mysqli_query($ligacao,$consulta);
while ($listar = mysqli_fetch_array($resultado)){
$catmat = $listar['Cat_Material'];
echo "<option value=".$catmat.">$catmat</option>";
}
?>
</select>
<div class="select-dropdown"></div>
</div>
</div>
</div>
</div>
All I try to do is make a If if the txt_maq is E09 so I can do the query in the txt_catmaterial but the value doesn't come from the javascript.

Use Ajax to send data from Javascript to PHP
function testEndpoint(){
$.ajax({
url: "https://path/to/your-php-script.php",
type: "POST",
crossDomain: true,
data: {"txt_maq": $("#txt_maq").val()},
dataType: "json",
error: function(xhr, status, error){
console.log("Error: " + error);
},
success: function(result, status, xhr){
console.log(result);
}
});
}
testEndpoint();
At your PHP script your-php-script.php
You can use txt_maq as a POST variable:
$useTxtMag = $_POST['txt_maq'];

The Ajax should be used after the jQuery is included or you can simply include the jQuery in your head element

Related

Laravel Dynamic Ajax Dependent Dropdown

I Dont know whats wrong with this code but when i choose one of it no option value shown
Here my Blade View
<div style="overflow:hidden; float:left; width:250px;">
<select id="division" class="" name="">
<option value="groups">-- Division --</option>
<option value="Male">Male</option>
<option value="Female">Femmaleale</option>
</select><br>
<select id="participant">
<option value="choosetools">-- Choose Participant --</option>
</select>
</div>
here my script
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#division').change(function(){
var division = $('#division').val();
$('#participant').html('');
$.ajax({
url:'getParticipant/{id}',
type:'GET',
data:{myID:division},
dataType: "json",
success:function(data)
{
$.each(data, function(key, participant)
{
// alert(city.city_name)
$('#participant').prop('disabled', false).css('background','aliceblue').append('<option value="'+participant.gymnastid+'">'+'participant.FULLNAME'+'</option>');
});
}
});
});
});
</script>
here my route
Route::get('/getParticipant/', 'App\Http\Controllers\ScoreController#getParticipant');
here my controller
public function getParticipant()
{
$getdiv = $_GET['divSelect'];
if ($getdiv == 'Male') {
$res = Magmodel::all();
return Response::json($res);
}else{
$res = Wagmodel::all();
return Response::json($res);
}
}
Can Someone please help me so all data from model Magmodel or Wagmodel showup based on dropdown choose

append() in jquery not woring

I am new to jquery and ajax. I really need you help.
I have two select box, one dynamically add options to a select when the first select box is checked. I used ajax to dynamically get those values. I am getting values correctly from database. But when I try to append these options inside second select box it is not working. My code is below
$(document).ready(function() {
$("#categories").change(function() {
var categoryId = $("#categories").val();
//alert(categoryId);
if(categoryId == 2) {
$.ajax({
url: "<?= base_url();?>Web/getRateType",
method: "POST",
dataType: "json",
success:function(data) {
//alert(data[0].status);
$("#rate_container").css('display', 'block');
$("#expected_salary_container").css('display', 'none');
$("#rate_categories").empty();
// var str = '<label>Rate*</label></br>';
//str += '<select name="rate_categories" style="font-size:15px" id="rate_categories"><option value="0">Select</option>';
var str = '';
$.each(data, function(key, value) {
//alert(value['rate_id']);
str +='<option value="'+ value['rate_id'] +'">'+ value['rate_cat_name'] +'</option>';
});
alert(str);
//str += '</select>';
var x = $("#rate_categories").append(str);
if(x){
alert(x);
}
}
});//$("#rate_categories").append('<option value="'+ value.rate_id +'">'+ value.rate_cat_name +'</option>');
}
else if (categoryId == 1) {
document.getElementById("expected_salary_container").style.display = "block";
document.getElementById("rate_container").style.display = "none";
}
else{
document.getElementById("expected_salary_container").style.display = "none";
document.getElementById("rate_container").style.display = "none";
}
});
<div class="col-lg-6 col-md-6">
<div class="form-group">
<label>Job Type*</label>
<select name="categories" id="categories">
<option value="0">Select</option>
<?php foreach($categories as $key => $value) { ?>
<option value="<?php echo $value['type_id']; ?>"><?php echo $value['cat_name']; ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="form-group">
<label>Rate*</label>
<select id="rate_categories" name="rate_categories">
<option value="0">Select</option>
</select>
</div>
here alert(x) is working fine. but the html is not appending inside select box. could anybody please help
jQuery is referenced in the header:
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
You are calling the ready function before the jQuery JavaScript is included. Reference jQuery first. However please check the network tab JS file load.
You should put the references to the jquery scripts first.
<script language="JavaScript" type="text/javascript" src="/js/jquery-1.2.6.min.js"></script>
Please use compatible new jquery CDN Url in above script tag.
Examine the code below and see if that works for you. I've changed the vanilla JS to jQuery. You may need to re-insert your php code back in.
$(document).ready(function() {
//Hide everything
$("#expected_salary_container, #rate_container").hide();
$("#categories").change(function() {
var categoryId = $("#categories").val();
console.log(categoryId);
//alert(categoryId);
if (categoryId == 2) {
let data = ["Item 1", "Item 2", "Item 3"];
str = "";
$.each(data, function(key, value) {
//alert(value['rate_id']);
str += '<option value="' + value + '">' + value + '</option>';
console.log(str);
});
var x = $("#rate_categories").append(str);
$("#expected_salary_container").hide();
$("#rate_container").show();
} else if (categoryId == 1) {
$("#expected_salary_container").show();
$("#rate_container").hide();
} else {
$("#expected_salary_container").hide();
$("#rate_container").show();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-lg-6 col-md-6">
<div class="form-group">
<label>Job Type*</label>
<select name="categories" id="categories">
<option value="0">Select</option>
<option value="2">Cat 1</option>
<option value="1">Cat 2</option>
<option value="2">Cat 3</option>
</select>
</div>
</div>
<div id="rate_container">
<div class="form-group">
<label>Rate*</label>
<select id="rate_categories" name="rate_categories">
<option value="0">Select</option>
</select>
</div>
</div>
<div id="expected_salary_container">
<div class="form-group">
<label>Salary*</label>
<select id="rate_categories" name="rate_categories">
<option value="0">Select</option>
</select>
</div>
</div>

Selecting a specific element from multiple forms

I'm trying to select a specific element from multiple forms but it's not working properly:
So my javascript code is:
function makeActive(target)
{
$("div.interactive").removeClass("interactive");
$("#form" + target).addClass("interactive");
}
$(document).ready(function () {
$('.interactive option[name=bu]').on('change', function () {
$('.interactive option[name=discipline]').empty();
$('.interactive option[name=project]').empty();
$('.interactive option[name=role]').empty();
$.ajax({
type: 'GET',
url: '#Url.Action("GetList", "Central")',
dataType: 'Json',
data: { InitiateId: $('.interactive option[name=bu]').val(), InitiateType: "BU" },
success: function (data) {
console.log("That was calling")
$('.interactive option[name=discipline]').append('<option value="">Select</option>');
$.each(data, function (index, value) {
$('.interactive option[name=discipline]').append('<option value="' + value.Id + '">' + value.Name + '</option>');
});
$('.interactive option[name=project]').append('<option value="">Select Discipline firt</option>');
$('.interactive option[name=role]').append('<option value="">Select Project first</option>');
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
And cshtml struct page is:
<div id="faq" role="tablist" aria-multiselectable="true">
#foreach (var actor in Model)
{
string areacontrol = "answer" + actor.Id;
count +=1;
bool open = false;
if (ViewBag.actor != null)
{
if (actor.Id == ViewBag.actor.Id)
{
open = true;
}
}
else
{
if (count == 1)
{
open = true;
}
}
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="questionOne">
<h5 class="panel-title">
<a data-toggle="collapse" data-parent="#faq" href="##areacontrol" aria-expanded="false" aria-controls="answerOne"
onclick=" makeActive(#actor.Id)">
#actor.Name (#actor.Email)
</a>
</h5>
</div>
<div id="#areacontrol" class="panel-collapse collapse #(open?" in":"")" role="tabpanel" aria-labelledby="questionOne">
<div class="panel-body">
#using (Html.BeginForm("Assign", "Central", FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
string form = "form" + actor.Id;
<div class="row form-group #(open?" interactive":"")" id="#form">
<div class="col-md-3 col-md-offset-0">
<label for="bu">Business Unit</label>
<select name="bu" class="form-control">
<option value="">--Select--</option>
#foreach (var item in flowcontext.ContiBusinessUnits.ToList())
{
if (ViewBag.bu != null && actor.Id == ViewBag.actor.Id)
{
bool selected = false;
if (ViewBag.bu.Name == item.Name)
{
selected = true;
}
if (selected)
{
<option value="#item.Id" selected>#item.Name</option>
}
else
{
<option value="#item.Id">#item.Name</option>
}
}
else
{
<option value="#item.Id">#item.Name</option>
}
}
</select>
</div>
<div class="col-md-3">
<label for="discipline">Discipline</label>
<select name="discipline" class="form-control">
#if (ViewBag.discipline != null && actor.Id == ViewBag.actor.Id)
{
<option value="#ViewBag.discipline.ID">#ViewBag.discipline.Name</option>
}
else
{
<option value="">Select Business Unit first</option>
}
</select>
</div>
<div class="col-md-3">
<label for="project">Project</label>
<select name="project" class="form-control">
#if (ViewBag.project != null && actor.Id == ViewBag.actor.Id)
{
<option value="#ViewBag.project.ID">#ViewBag.project.Name</option>
}
else
{
<option value="">Select Discipline first</option>
}
ViewBag.role_id = contiRole;
</select>
</div>
<div class="col-md-3">
<label for="destination">Role</label>
<select name="role" class="form-control">
#if (ViewBag.role != null && actor.Id == ViewBag.actor.Id)
{
<option value="#ViewBag.role.ID">#ViewBag.role.Name</option>
}
else
{
<option value="">Select Project first</option>
}
</select>
</div>
<div class="col-md-3" style="display:none">
<label for="destination">User Id</label>
<select name="userid" class="form-control">
<option value="#actor.Id" selected>#actor.Name</option>
</select>
</div>
</div>
<div class="row form-group">
<div class="col-md-3 col-md-offset-8">
<input type="submit" class="btn btn-primary btn-block" value="Add">
</div>
</div>
}
</div>
</div>
</div>
}
</div>
<!--end language: lang-html -->
In that inside a foreach loop, I load/ generate a form.
First: The bootstrap collapse will be open for the first user(actor);
Inside, I have a form with is necessary to be similar and be a cascade drop select!
When I make a change[ $('.interactive option[name=bu]').on('change', function (){}]that calls for me a controller method which returns me a list and with that list a generate the second field and again for other 2 field!
That helps me to make a cascade select for a form and that works well but only for the first one!
I think either I'm not making the selections properly or using ajax, "$ (document) .ready" does not get the data properly.
How I can select properly or tell others methods!
How can improve that and make it work for all form elements?
Hi in this example we get the selected value from a dropdown list in different forms using a commun class the elements share and then we save that value inside an array which contains the name of the dropdown list, the selected value and the selected value text.
let options = document.querySelectorAll('.cmbMsg');
//get all select boxes with the same class
var values = [];
options.forEach(function(option) {
values.push({"item":option.getAttribute("name"),"value":option[option.selectedIndex].value,"text":option[option.selectedIndex].text});
});
console.log(values);
.cmbMsg {
font-size:14px;
}
<form action="" id="form1">
<select name="select1" id="select1" class="cmbMsg">
<option value="1" selected>Hello </option>
<option value="2">My friend</option>
</select>
</form>
<br>
<form action="" id="form2">
<select name="select2" id="select2" class="cmbMsg">
<option value="1">Hola</option>
<option value="2" selected>Mundo</option>
</select>
</form>
<br>
<form action="" id="form3">
<select name="select3" id="select3" class="cmbMsg">
<option value="1">Viva</option>
<option value="2" selected>la France</option>
</select>
</form>
Hope it helps
I found the solution!
The problem was that I did not recognize my selections after we came up with a change using ajax and I just load all my field immediately after the page load and group them for each form!
$(form + 'select[name=bu]').on('change', function (){};
And I just call a function for getting all actorid and pushing on a list and "leasing" for all field;

i want to display the images according to the number selected from the select box in codeigniter

Here I want to display the images according to the numbers selected from the select box and my values in select box are 9,12,18 and here is my code
my view page looks like this...
<form action="<?php echo base_url();?>roxcontrol/numberdisplay" id="numberdisplay" method="post">
<div class="col-md-4 col-sm-4 none-xs text-center">
<div class="limiter hidden-xs">
<label>Show</label>
<select name="gallery" id="gallery">
<option selected="selected" value="9">9</option>
<option value="12">12</option>
<option value="24">24</option>
<option value="36">36</option>
</select>
per page
</div>
</div>
</form>
<script type="text/javascript">
$(document).ready(function() {
//alert();
$("#numberdisplay").change(function() {
var parent = $(this).val();
//alert(parent);
var url = '<?php echo base_url(); ?>roxcontrol/ajax_get_sub';
$.post(url, {
parent: parent
}, function(data)
{
$('#gallery').html(data);
});
});
});
</script>
My control page looks like this
public function ajax_get_sub()
{
$gal_id=$this->input->post('parent');
$data['galery']=$this->roxmodel->get_gallery_by_number($gal_id);
$this->load->view('ajax_get_sub',$data);
}
My model page looks like this.
public function get_gallery_by_number($gal_id)
{
$this->db->order_by("gallery.id","desc");
$query=$this->db->limit($gal_id)->get('gallery');
return $query->result();
}
Here I am not getting any images
In controller Just get Post value from ajax call and try this
public function ajax_get_sub()
{
$gal_id=$this->input->post('gal_id');
$this->db->order_by("id","desc");
$query=$this->db->limit($gal_id)->get('gallery');
$var="";
foreach($query->result() as $row)
{
$var .= "<img src=".$row->img_url."/> </br>"; //your table image url(path)
}
echo $var;
}
In view File
<div class="col-md-4 col-sm-4 none-xs text-center">
<div class="limiter hidden-xs">
<label>Show :</label>
<select name="gallery" id="gallery">
<option selected="selected" value="9">9</option>
<option value="12">12</option>
<option value="24">24</option>
<option value="36">36</option>
</select>
per page
</div>
<div id="img_display">
<script type="text/javascript">
$(document).ready(function() {
$("#gallery").change(function() {
var gal_id = $("#gallery").val();
alert(gal_id);
$.ajax({
type: "post",
url: base_url+'sample_controller/ajax_get_sub',
cache: false,
data: {gal_id:gal_id},
success: function(get_img){
try{
$("#img_display").append(get_img);
}catch(e) {
alert('Exception while request..'+JSON.stringify(e));
}
},
error: function(e){
alert('Error while request..'+JSON.stringify(e));
}
});
});
});
Dont forget to give value for gallery select option.
This is one of the way to append the element.

how to use a json function for filling combo box with database?

I am new at html and trying to relation between database.And i want to fill box with database
I have a code like
<div class="content" data-role="content" id="content" >
<div id="car">
<select name="selectCar" class="span12" id="Options" >
<option value="-1">Bir istasyon seçiniz.</option>
<option value="1">Mimarlık</option>
<option value="2">Yurtlar</option>
<option value="3">Bilgisayar Mühendisliği</option>
<option value="4">Kimya Mühendisliği</option>
<option value="5">Rektörlük</option>
</select>
</div>
<div id="cinfo"></div>
<button onclick="javascript:callCarInfo.call(this,document.getElementById('Options').value);">Call Podcar</button>
</div>
here
<option value="1">Mimarlık</option>
<option value="2">Yurtlar</option>
<option value="3">Bilgisayar Mühendisliği</option>
<option value="4">Kimya Mühendisliği</option>
<option value="5">Rektörlük</option>
i want to fill this values and names of stations with database
I also have a station function which is
function getStationList()
{
$db = new DBManager();
$mysqli = $db->db_connect();
$query = "SELECT stationId FROM Station";
$stmt = $mysqli->prepare($query);
$stmt->execute();
$result = $stmt->get_result();
$list = array();
while($row = $result->fetch_assoc())
{
$list[] = $row['stationId'];
}
return json_encode($list);
}
I tried to use ajax function but i couldnt do it which is
$.ajax({
url:'Stations.php',
type:'POST',
data: 'q=' + str,
dataType: 'json',
success: function( json ) {
$.each(json, function(i, value) {
$('#myselect').append($('<option>').text(value).attr('value', value));
});
}
});
JS (page.html):
$(document).ready(function() {
$.ajax({
url:'Stations.php',
type:'POST',
data: 'q=' + str, // not sure you need that as you are not filtering on server side
dataType: 'json',
success: function( json ) {
$.each(json, function(i, value) {
$('#myselect')
.append($('<option></option>', {text:value})
.attr('value', text);
});
}
});
})
HTML (page.html):
<div class="content" data-role="content" id="content" >
<div id="car">
<select name="selectCar" class="span12" id="Options" ></select>
</div>
<div id="cinfo"></div>
<button onclick="javascript:callCarInfo.call(this,document.getElementById('Options').value);">Call Podcar</button>
</div>
Stations.php :
<?php
getStationList();
?>
Quick explanation : when page.html is loaded and ready, it makes an ajax call to Stations.php to get the list of Stations. On response, it iterates on results and add an option element for each result to the select element which have id "Options".

Categories

Resources