I have a form on my page which contains two select dropdowns. The first one lets the user choose a country, and the second one lets the user choose a city from that country. I would like for the second dropdown options to be filled with cities based on the previously selected country. Currently, I have an onChange event that leads to an AJAX script which populates the cities from an external php file. Here is my code so far:
HTML Form
<form method="post">
<select name="country" onchange="dynamic_Select('city.php', this.value)" />
<option value="#">-Select-</option>
<option value="India">India</option>
<option value="USA">USA</option>
</select>
<div id="txtResult">
<select name="cityList">
<option></option>
</select>
</div>
</form>
AJAX Script in Header (dynamic_Select)
<script>
function dynamic_Select(ajax_page, country) {
$.ajax({
type: "GET",
url: ajax_page,
data: "ch=" + country,
dataType: "text/html", //<--UPDATE: DELETING THIS LINE FIXES EVERYTHING
//<--UPDATE2: DON'T DELETE; REPLACE "test/html" with "html"
success: function(html){ $("#txtResult").html(html); }
});
}
</script>
//I also have a link to the jquery file
<script src="js/jquery.js" type="text/javascript"></script>
External PHP File (city.php)
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
// List of cities for India
if ($_GET['ch'] == 'India') {
?>
<select name="cityList">
<option value="Mumbai">Mumbai</option>
<option value="Delhi">Delhi</option>
<option value="Bangalore">Bangalore</option>
<option value="Patna">Patna</option>
</select>
<?php
}
// List of cities for USA
if ($_GET['ch'] == 'USA') {
?>
<select name="cityList">
<option value="Albama">Albama</option>
<option value="Alaska">Alaska</option>
<option value="Arizona">Arizona</option>
<option value="Florida">Florida</option>
</select>
<?php
}
?>
The above set of code isn't working, and I can't figure out why. Two dropdown lists appear on the page (the second one is initially blank), but after choosing a country from the first dropdown the second dropdown remains blank. Any help would be much appreciated!
Change your dataType parameter from "text/html" to "html".
Also, you could have shortened all of this:
function dynamic_Select(ajax_page, country) {
$.ajax({
type: "GET",
url: ajax_page,
data: "ch=" + country,
dataType: "text/html", //<--UPDATE: DELETING THIS LINE FIXES EVERYTHING
//<--UPDATE2: DON'T DELETE; REPLACE "test/html" with "html"
success: function(html){ $("#txtResult").html(html); }
});
}
To:
function dynamic_Select(ajax_page, country) {
$.get(ajax_page, {ch: country}, function(h) {
$('#txtResult').html(h);
});
}
Related
I have the following 3 checkboxes which are populated from a php database. I need assistance with JQUERY that once any select box is changed the value is posted to a php file and able to return a response through JQUERY.
Each select box should be standalone to only send that checkbox value & name to the PHP file.
I have the below JQUERY to start with to send the first checkbox but am getting no response back.
What amendments need to be made to the JQUERY to receive the input of the other checkboxes and then send the data correctly?
The php file will simply have echo "WHAT EVER THE RESPONSE IS" using if statements.
Any help grately appreciated with thanks.
$(document).ready(function() {
$('select.person-1').change(function() {
$.ajax({
type: 'POST',
url: 'lib/positionMarshalProcess.php',
data: {
selectFieldValue: $('select.person-1').val(),
changeCol1: $('input[name$="changeCol1"]').val()
},
dataType: "html",
},
success: function(data) {
var a = data.split('|***|');
if (a[1] == "update") {
$('#msg').html(a[0]);
}
}
});
return false;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name='person-1' class='marshal-select'>
<option value='1'>John Smith</option>
</select>
<input type='hidden' name='changeCol1' value='person-1'>
<select name='qty' class='marshal-select'>
<option value='1'>1</option>
</select>
<input type='hidden' name='changeCol2' value='qty'>
<select name='person-2' class='marshal-select'>
<option value='1'>John Smith</option>
</select>
<input type='hidden' name='changeCol3' value='person-2'>
The selectors you've used are incorrect for the HTML displayed. .person-1 is a class selector, yet the select elements have that value in their name.
In addition your success property is outside the options object of the $.ajax call - it needs to be inside.
You can fix this issue and DRY up the code to make it more extensible by removing the hidden fields, hooking the change event handler to the common marshal-select class on all the select elements, and by using the name attribute of the select elements to fill the changeCol property of the data you send in the AJAX request. Try this:
$(document).ready(function() {
$('select.marshal-select').change(function() {
let $select = $(this);
// in your AJAX request...
let data = {
selectFieldValue: $select.val(),
changeCol: $select.prop('name')
};
console.log(data);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="person-1" class="marshal-select">
<option value="1">John Smith</option>
<option value="2">Jane Doe</option>
</select>
<select name="qty" class="marshal-select">
<option value="1">1</option>
<option value="2">2</option>
</select>
<select name="person-2" class="marshal-select">
<option value="1">John Smith</option>
<option value="2">Jane Doe</option>
</select>
As an aside, the logic in the success handler implies that you're returning plain text and then hacking the string around using split(). Do not do this. Return a serialised data structure, such as JSON instead. This is more extensible and makes the code far more robust.
Update:
With your code you have added could you just add an edit where how you would receive a response ideally I want a positive response to show the msg div and where you would call the php file?
Sure, here you go:
$(document).ready(function() {
$('select.marshal-select').change(function() {
let $select = $(this);
$.ajax({
type: 'POST',
url: 'lib/positionMarshalProcess.php',
data: {
selectFieldValue: $select.val(),
changeCol: $select.prop('name')
},
dataType: "html",
success: function(data) {
// assuming a JSON response:
if (data[1] === 'update') {
$('#msg').html(data[0]).show();
}
}
});
});
});
Note that I've not included the PHP which would generate the JSON response as I'm not a PHP dev. I'm sure there are lots of topics covering that if you search.
So I am making an assignment program wherein in my database, I have a set of documents and when I want to tag it to a person, I would choose who I will tag it to. Here is the code for assigning a person to a document.
<select name="staff" value="staff" align="left" onchange="senddocu(this)">
<option selected value="">Staff</option>
<option name='chief' value='chief'>Chief User</option>
<option name='user' value='user'>User 1</option>
</select>
Now, I have a problem with getting values from another file in my PHP code. Somehow, it doesn't fetch the values from my select options. Here are the parameters for my select options. And also, my code from earlier and this code is in one file only.
<select name="document" align="left">
<option selected disabled value="">Document Type</option>
<option value="A">A</option>
<option value="C">C</option>
<option value="CO">CO</option>
<option value="Curr">Curr</option>
<option value="Scholarship">Scholarship</option>
<option value="MIS">MIS</option>
<option value="Fax">Fax</option>
<option value="E-mail">E-mail</option></select>
<input type="text" name= "datenow" id = "copy" align="center">
<input type="text" name="application" align="center" size = "3%">
And here is the code to fetch the values from those. This is in another file.
<?php
$document_type= mysqli_real_escape_string($conn, $_POST['document']);
$application_no= mysqli_real_escape_string($conn, $_POST['application']);
$today = mysqli_real_escape_string($conn, $_POST['datenow']);
echo $document_type;
echo $application_no;
echo $today;
?>
The problem is, only the $today variable fetches its value. The rest doesn't get stored into the variables from another file.It doesn't make sense at all. All the names are correct, yet its not fetching it. I already have the ajax code on my first file which is:
function senddocu(sel)
{
$.ajax({
type: "POST",
data: {staff: $(sel).val()},
url: "send.php",
dataType: "html",
success: function(response)
{
$("#responsecontainer").html(response);
console.log(response);
}
});
}
how to fetch the values?
You're not using the correct way to fetch the value of the <select> in your AJAX request. You need to give the select an id, or a name, which you target in order to get the right element. You then ask it for the selected options value.
In order to get the input field variables, you can select them by name, or by id also. I'm just going to do it by name, since that's what you have in your example snippet.
Example using id:
function senddocu()
{
$.ajax({
type: "POST",
data: {
staff: $("#sel option:selected").val(),
datenow: $("input#datenow").val(),
application: $("input#application").val()
},
url: "send.php",
dataType: "html",
success: function(response)
{
$("#responsecontainer").html(response);
console.log(response);
}
});
}
This example takes the selected value of a select that has the id sel. In order to make this work, you simply have to give your select the proper id.
Like so:
<select name="document" id="sel" align="left" onchange="senddocu();">
<option selected disabled value="">Document Type</option>
<option value="A">A</option>
<option value="C">C</option>
<option value="CO">CO</option>
<option value="Curr">Curr</option>
<option value="Scholarship">Scholarship</option>
<option value="MIS">MIS</option>
<option value="Fax">Fax</option>
<option value="E-mail">E-mail</option>
</select>
<input type="text" name= "datenow" id = "copy" align="center">
<input type="text" name="application" align="center" size = "3%">
Example by using name to get the value:
function senddocu(sel)
{
$.ajax({
type: "POST",
data: {
staff: $("select[name=document] option:selected").val(),
datenow: $("input[name=datenow]").val(),
application: $("input[name=application]").val()
},
url: "send.php",
dataType: "html",
success: function(response)
{
$("#responsecontainer").html(response);
console.log(response);
}
});
}
If the input variables are in a completely different file, you'll have to reconsider what you're trying to achieve and maybe rework your logic around that, whether there's really a reason for that. You should also consider including more coherent code in your questions so that people can get the whole picture, as well as test the code. Makes it a lot easier that way.
I have a problem on passing more than one values from a dropdown menu. What I am doing is an attendance system where a dropdown menu containing the choices of attendance status per student. User will then choose the attendance status of each student accordingly, and what I am trying to do is to pass the status that has been chosen to another page.
I am trying to insert the selected attendance status into an array using AJAX and then pass the array to another page. Here's what I have so far:
todaysattendance.php
//dropdown menu
<tr>
<td> $fetched_fName $fetched_lName </td>
<td> <select name='okselect' id='okselect'>
<option value='no'> </option>
<option value='p' name='p' style='color:green; font-weight:bold;'>Present</option>
<option value='ea' name='ea' style='color:#e1c872; font-weight:bold;'>Excused Absent</option>
<option value='ua' name='ua' style='color:#e34c4c; font-weight:bold;'>Unexcused Absent</option>
<option value='et' name='et' style='color:blue; font-weight:bold;'>Excused Tardy</option>
<option value='ut' name='ut' style='color:purple; font-weight:bold;'>Unexcused Tardy</option>
<option value='sr' name='sr' style='color:black; font-weight:bold;'>School's Representative</option>
</select></td> </tr>
todaysattendance.php
//AJAX code
var tempArr = [];
$("#okselect").change(function()
{
var output = getValues(this, function ()
{
for (var i=0;i<output.length;i++)
{
tempArr.push(output);
};
});
$.ajax({
type: "POST",
url: "add_attendance_check.php",
data: {tempArr: tempArr},
success: function(data) {
//
},
error: function(e) {
console.log(e.message);
}
});
});
add_attendance_check.php
$passed_attstatus = array();
$thestatus = $_POST['tempArr'];
array_push($passed_attstatus, $thestatus);
But from this coding, let's say I took the attendance status for 10 students, I only managed to get the last student's attendance status. I need help on this. Thank you very much in advance!
print variable dropdown_value in add_attendance_check you will get the value of selected dropdown.
<form method="post" action="" role="search">
<select name='okselect' id='okselect'>
<option value='no'> </option>
<option value='p' name='p' style='color:green; font-weight:bold;'>Present</option>
<option value='ea' name='ea' style='color:#e1c872; font-weight:bold;'>Excused Absent</option>
<option value='ua' name='ua' style='color:#e34c4c; font-weight:bold;'>Unexcused Absent</option>
<option value='et' name='et' style='color:blue; font-weight:bold;'>Excused Tardy</option>
<option value='ut' name='ut' style='color:purple; font-weight:bold;'>Unexcused Tardy</option>
<option value='sr' name='sr' style='color:black; font-weight:bold;'>School's Representative</option>
</select>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script type = "text/javascript" language = "javascript">
jQuery(document).ready(function() {
jQuery("#okselect").change(function() {
var dropdown_value = $('#okselect').val();
$.ajax({
type: "POST",
url: "add_attendance_check.php",
data: {dropdown_value: dropdown_value},
success: function(data) {
//
},
error: function(e) {
console.log(e.message);
}
});
});
});
</script>
I have a great news, I finally solved the problem. All I need to do is to change this line in todaysattendance.php from
<select name='okselect' id='okselect'>
into
<select name='okselect[]' id='okselect'>
In add_attendance_check.php, I simply changed to
$passed_attstatus = array();
$thestatus = $_POST['okselect'];
array_push($passed_attstatus, $thestatus);
No need for AJAX from the very beginning. Anyway I would like to thank everyone who responded. Have a good day!
<select name='okselect' id='okselect' onchange="abc(this.value)">
//your option
</select>
And Ajax call abc function inner abc(value)
I have two dropdowns: state and city. Both are in the same form. The goal is to somehow save the selection without clicking submit button so it could be used as a criteria to display selections of cities in the second dropdown.
For example: When california is chosen in the first dropdown, second dropdwon displays all the cities in California.
Code:
<?php $db= DB::table('states_table')->get(); ?>
<select class="form-control input-md" name="state">
<option value="" disabled selected>Choose the state</option>
<?php foreach ($db as $data) { ?>
<option value="<?php echo $data->city; ?>">
<?php echo $data->city;?>
</option><?php
}?>
</select>
just use ajax :
$('#form').on('change','select[name="state"]', function() {
var province = $('select[name=state]').val();
$.ajax({
url: './get_city.php',
method: 'post',
data: {"state": state},
success: function (data) {
$('select[name=city]').html(data);
}
})
});
and in the get_city.php connect to db , get the cities and return them on tags
$('#state_field_id').click(function(){
var state=document.getElementById('state_field_name').options[document.getElementById('state_field_name').selectedIndex].text;
});
you will get selected value
I've created a form with 3 select part and I tried to create an array with serializeArray. I want to use jquery ajax to post this array to my php file. But I don't want use submit. when I had just one select tag, I used this code
<form>
<select onchange="myfunction(str)">
<option value="">num</option>
<option value="123">123</option>
<option value="133">133</option>
</select>
</form>
In my ajax code, I used open("GET","myphpfile.php?q="+str,true) and send() without jquery. but now I have 3 select tag and I don't know how too use serializeArray()(or serialize()) with jquery.
this is my new form
<form>
<select name="num1">
<option value="">num1</option>
<option value="12">12</option>
<option value="13">13</option>
</select>
<select name="num2">
<option value="">num2</option>
<option value="123">123</option>
<option value="133">133</option>
</select>
<select name="num3">
<option value="">num3</option>
<option value="12345">12345</option>
<option value="12346">12346</option>
</select>
</form>
the second part of my question is how to write my php code to echo my array. I think it should be something like this
<?php
$myarr = array();
$myarr = $_GET["str"]//or $_POST['str']
echo $myarr[0];
?>
Thanks a lot! and by the way, English is not my native language; please excuse typing errors.
Okay, if I get your question correctly, here is what you're trying to do:
Hooking events on dynamically added fields
$("form").on("change", "select", function() {
var name = $(this).prop("name");
console.log("Select-Name: " + name);
// if you use the plugin I mentioned further down and you'll need to serialize
// all fields already here, you can use the plugin's .fieldSerialize method
})
Get detailed information here: https://api.jquery.com/on/
Serializing forms
Easiest thing here would be to work with this jQuery Form-Plugin:
http://malsup.com/jquery/form/
Create a json-dataset with almost no effort like this:
$("form").ajaxForm({
dataType: "json",
success: function(data) { sendToServer(data); }
});
Working with the data in the backend
The plugin also allows you to work on the server with the script you provided ($_POST["value"])
use
var arrayForm = $('form select').serializeArray();
and then
var paramForm = $.param(arrayForm);
like http://jsfiddle.net/LBKeQ/
then you can use
$.ajax({
type: 'POST',
async:true,
cache: false,
data: paramForm,
success:function (data, textStatus) {
console.log(data);
},
url:"myphpfile.php"
});