Add select onchange with AJAX - javascript

I'm a newbie to Javascript so I couldn't find an answer to my problem. I want to add an extra select when a previous select is changed. I know my code should look something likes this but it isn't working:
$(function(){
$('#artist').change(function(){
$.ajax({
url: "artist_field.php",
dataType:"html",
type: "post",
success: function(data){
$('#artist').append(data);
}
});
});
});
HTML
<td id="artist">
<select name="artist_1" id="artist">
<option value=""></option>
</select>
</td>
My problem is that I don't know how to get the values in artist_field.php that I'm trying to send (because I'm trying to exclude the previous selected option in the new select). I hope someone can help me! Thanks in advance.

$(document).ready(function() {
$('#select_2').hide();
$('#artist').change(function(){
$('#select_2').show();
});
});
HTML
<td id="artist">
<select name="artist_1" id="artist">
<option value=""></option>
</select>
</td>
<td>
<select name="select_2" id="select_2">
<option value=""></option>
</select>
</td>
It will only show the second select if you chose something on the first one

Update: I just noticed that you have the ID artist in the code twice. You might change the TD to <td id="artist_td"> or something for my example to work
To send the currently selected option back to the server in the post, you can do something like:
$('#artist').change(function(){
$.ajax({
url: "artist_field.php",
data: { "value": $("#artist").val() },
dataType:"html",
type: "post",
success: function(data){
$('#artist').append(data);
}
});
});
Then in the PHP document, you can get the value with $_POST["value"];, and use that value to limit the return options.
update
If you are going to fire the change event off multiple times, it's going to append the new data every time. If this is not the behavior that you want, add a div or something to put the new data into like:
<td id="artist_td">
<select name="artist_1" id="artist">
<option value=""></option>
</select>
<div id="newdata"></div>
</td>
Then edit the success function
success: function(data){
$('#newdata').empty().append(data);
}

With "artist_field.php" returning a string containing all elements to place in the <select> element separated by commas. I hope it will help ☻ ☺
window.addEventListener("load", function(){
var list = document.getElementById("artist");
var xhr = Xhr();
xhr.onreadystatechange = function(e){
if(xhr.status === 4 || xhr.status === 200)
{
var results = (xhr.responseText).split(',');
for(var i = 0; i < results.length; ++i)
{
var el = document.createElement("option");
el.innerHTML = results[i];
list.appendChild(el);
}
}
};
xhr.open("GET", "artist_field.php", false);
xhr.send(null);
}, false);
function Xhr()
{
try {
return new XMLHttpRequest();
}catch(e){}
try {
return new ActiveXObject("Msxml3.XMLHTTP");
}catch(e){}
try {
return new ActiveXObject("Msxml2.XMLHTTP.6.0");
}catch(e){}
try {
return new ActiveXObject("Msxml2.XMLHTTP.3.0");
}catch(e){}
try {
return new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){}
try {
return new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){}
return null;
}

Here is the code where you can easily understand select Tag on change with ajax request using PHP.
HTML Code
<div class="form-group">
<label>Select SMS Template</label>
<select id="sms-select" name="sms-select" onchange="smschange(this.value)" class="form-control">
<option value="">Select SMS Template</option>
<?php foreach ($sms as $row) { ?>
<option value="1">Sample SMS</option>
<option value="2">Test SMS</option>
<?php } ?>
</select>
</div>
Javascript Code
<script>
function smschange(id)
{
$.ajax({
type: 'post',
data: {'id': id},
url: 'sms.php',
dataType: 'json',
success: function(res){
alert(res);
},
error: function(res){
$('#message').text('Error!');
$('.dvLoading').hide();
}
});
}
</script>
JQuery Library Source Code:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">

Related

AJAX loaded select, select option by value

How to select option by value, if the select is loaded via AJAX
index.php
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div id="data"></div>
</body>
<script>
function LoadSelect() {
var post_data = {
token: "test"
};
$.ajax({
type: 'POST',
url: 'load_select.php',
data: post_data,
dataType: "json",
beforeSend: function() {},
success: function(data) {
$("#data").html(data["msg"]);
},
complete: function() {}
});
}
$(document).ready(function() {
LoadSelect();
});
</script>
</html>
load_select.php
<?php
// Value from the database
$gender = "female";
$html = '
<select class="form-control" id="gender" name="gender">
<option value="female">Female</option>
<option value="male">Male</option>
</select>
<script>
$("#gender").val("'.$gender.'");
</script>
';
echo json_encode(array('msg' => $html));
Tried this code, but it's not working.
The problem solved, the $gender variable gets wrong value from the database like "f" and not "female".
Typically changing the value of a select via code should be followed by triggering the change event, like this $("#gender").trigger('change');
If I understand you correctly then you override the select with html from your ajax request. In order to maintain the value you will need to store the original value, then override the html and then restore the original value. See this snippet below.
Better would be to not override the html element with your ajax call but only update the information that need to be updated.
$("#gender").val("male");
//Lets pretend this onclick handler is your ajax succes handler.
$('#MimicAjax').on('click', function(){
//Fake ajax result for demonstraion purpose
var ajaxResult = '<select class="form-control" id="gender" name="gender"><option value="female">Female</option><option value="male">Male</option></select>';
//store the original value
var originalValue = $("#gender").val();
//Do your ajax thingy
$('#data').html(ajaxResult);
//restore original value
$("#gender").val(originalValue);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="data">
<select class="form-control" id="gender" name="gender">
<option value="female">Female</option>
<option value="male">Male</option>
</select>
</div>
<button id="MimicAjax">MimicAjax</button>
If you just want to set the value after you added the html with ajax then just use that line within the succes handler after you changed the html.
$.ajax({
type: 'POST',
url: 'src/ajax/load_select.php',
data: post_data,
dataType: "json",
beforeSend: function() {},
success: function(data) {
$("#data").html(data["msg"]);
$("#gender").val("male");
},
complete: function() {
}
});

Retain select tag value if user doesn't confirm dialog box

The ajax is fired when user confirms, but if user cancels the confirm dialog still the select tag value changes though ajax isn't fired. I want something like if user cancels then select tag should retain it's previous value. I have this:
<select name="ss" id="<?=$row['id'];?>" onchange="_changeStatus(this.value,'<?=$row['id'];?>');">
<option value='Paid'>Paid</option>
<option value='Verified'>Verified</option>
<option value='Inprocess'>Inprocess</option>
<option value='Chargeback'>Chargeback</option>
</select>
script:
function _changeStatus(v,i){
if(confirm("Sure to Update")){
$.ajax({
type: 'post',
url: 'change-status.php',
data: {val:v,eid:i,actionid:1},
success: function (res) {
if(res!="scr"){
alert("Unexpected Error, Page will be refreshed !");
window.location.reload();
}
}
});
}
}
Should be something like that:
<select defaultValue="Paid" name="ss" id="<?=$row['id'];?>" onchange="_changeStatus(this,'<?=$row['id'];?>');">
<option value='Paid'>Paid</option>
<option value='Verified'>Verified</option>
<option value='Inprocess'>Inprocess</option>
<option value='Chargeback'>Chargeback</option>
</select>
function _changeStatus(vobj,i){
var v = vobj.value;
if($(vobj).attr('value_before')){
var vbefore = $(vobj).attr('value_before');
}else{
var vbefore = vobj.defaultValue;
}
if(confirm("Sure to Update")){
$.ajax({
type: 'post',
url: 'change-status.php',
data: {val:v,eid:i,actionid:1},
success: function (res){
if(res!="scr"){
alert("Unexpected Error, Page will be refreshed !");
window.location.reload();
}else{
$(vobj).attr('value_before',v);
}
}
});
}else{
$(vobj).val(vbefore);
}
}
Please note that I have left it as similar as possible, so you would get a concept. Generally it's not a good practice to bind events inline when using jQuery, as well as mixing javascript with jQuery if not necessary.

Selection OnChange change PHP Variable

Hello StackOverflow People.
I need you help. I have this code:
<select name="type" onChange="idk?" class="form-control">
<option value="H">Week 51</option>
<option value="V">Week 52</option>
</select>
And if an user change the week i want to change the file get content :s
$Week = "";
echo file_get_contents('http://rooster.farelcollege.nl/'.$Week.'/c/c00050.htm');
Thanks!
greetings from the Netherlands =)
you can send Ajax request to the "file_get_contents" url.
This is what I am using and it works fine :)
<select name="type" class="form-control">
<option value="H">Week 51</option>
<option value="V">Week 52</option>
</select>
$(document).ready(function() {
$( ".form-control" ).change(function() {
$.ajax({
data: {
// You are not sending any post variables right? Then leave this empty :-) otherwise use it as array 'var1': 'value', 'var2': 'value2' ...
},
url: 'http://rooster.farelcollege.nl/'+$(this).val()+'/c/c00050.htm',
method: 'POST',
success: function(msg) {
alert(msg); // Optional, show text that was given by URL, can be removed
}
});
});
});
jquery.com/jquery.ajax

How to use multiselect filter with ajax

Hi all I have working multiselect filter downloaded from this source http://www.erichynds.com/, I am trying to use this with Ajax, though my ajax function is working, and showing html generated by php in window.alert(html), but multiselect fileter has no effect, I really don't know how to solve it. this is what I have done so far
HTML
<table>
<tr>
<td>
<select id='pr_select' name='prj' onChange='show("pr_select","output1");' >
<option value='28'>28</option>
<option value='29'>29</option>
<option value='30'>30</option>
</select>
</td>
</tr>
<tr>
<td>
<div id='output1'></div></td>
</tr>
</table>
JAVASCRIPT
<script>
function show(sel,id) {
var selected = $("#"+sel).val();
$("#"+id).html( "" );
if (selected.length > 0 ) {
$.ajax({
type: "GET",
url: "get_data.php",
data: "select="+selected,
cache: false,
beforeSend: function () {
$("#"+id).html('<img src="loader.gif" alt="" width="24" height="24">');
},
success: function(html) {
// Ajax is success but multiselect is not working.....
window.alert(html),
$("#"+id).html( html );
}
});
}
}
$(document).ready(function(){
$("#test").multiselect();
});
</script>
Output generated in ajax success block -window.alert
<select id='test' name='multiple_data[]' multiple='multiple'>
<option value='USA'>USA</option>
<option value='UK'>UK</option>
</select>
I even tried for output1 division also like this no luck
$(document).ready(function(){
$("#output1").multiselect();
});
Try not to bind the method on doc ready instead apply in the complete method of ajax:
<script>
function show(sel,id) {
var selected = $("#"+sel).val();
$("#"+id).html( "" );
if (selected.length > 0 ) {
$.ajax({
.......
success: function(html) {
// Ajax is success but multiselect is not working.....
window.alert(html),
$("#"+id).html( html );
},
complete:function(){
$("#test").multiselect(); // add it here in the ajax
}
});
}
}
</script>
This would solve your problem try
success: function(html){
document.getElementById(id).innerHTML = html;
$("#"+id).multiselect().multiselect('refresh').multiselectfilter();
},

Assign javascript variable to php variable

How to pass javascript variable that came from select option to a PHP variable?
I want to set PHP variable depending on user selection.
I tried that code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(function(){
$("select[name='sex']").change(function () {
var submitSearchData = jQuery('#extended-search').serialize();
var selectedValue=$('#sex').val();
jQuery.ajax({
type: "POST",
data: 'selected=' + selectedValue
url: "ajax.php",
success: function () {
// alert(submitSearchData);
alert(selectedValue);
}
});
});
});
</script>
<form id="extended-search" >
<div class="input-container">
<select class="select" name="sex" id="sex">
<option value="0">All</option>
<option value="1">M</option>
<option value="2">F</option>
</select>
</div>
</form>
<?php
var_dump ($_REQUEST['selected']); //that print NULL don't know why!
?>
You are passing data in wrong format. Data is passed as an object. Please refer below.
$("select[name='sex']").change(function () {
var submitSearchData = jQuery('#extended-search').serialize();
var selectedValue=$('#sex').val();
jQuery.ajax({
type: "POST",
data: {'selected': selectedValue},
url: "ajax.php",
success: function (response) {
// alert(submitSearchData);
alert(response);
}
});
});
Is not possible in the same instance of time:
yourfile -> ajax -> yourfile (here is the value, but you can't see this in your current webpage except that instead of ajax, send post form)
I hope this will help you...
dataType: "html",
data: {'selected': selectedValue},
and then u can get it via $_POST/$_REQUEST array since you have set your type to post.
$_REQUEST is null because it is not related to the ajax request you send. Try this for example:
<?php
if (isset($_POST["selected"])) {
echo $_POST["selected"];
} else {
?>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<form id="extended-search">
<div class="input-container">
<select class="select" name="sex" id="sex">
<option value="0">All</option>
<option value="1">M</option>
<option value="2">F</option>
</select>
</div>
</form>
<script>
$(function() {
$("select[name='sex']").change(function () {
var selected = $(this).val();
$.ajax({
type: "POST",
data: {
selected: selected
},
url: "ajax.php",
success: function (data) {
alert(data);
}
});
});
});
</script>
</body>
</html>
<?php } ?>
EDIT:
I updated the script and tested it. You had some errors in your code. Hope this works for you.

Categories