Here is the piece of my dropdown list:
<li><label>City:</label>
<select id="car" id="city">
<option value="New York">New York</option>
<option value="Sydney">Sydney</option>
</select>
</li>
Ajax code:
$("#SaveChanges").click(function () {
var data = {
email: $('#email').val(),
firstname: $('#firstname').val(),
lastname: $('#lastname').val(),
city: $('#city option:selected').text()
};
$.ajax({
url: "<?php echo site_url('ajax/saveChanges');?>",
type: 'POST',
async: false,
data: data,
success: function(msg) {
alert(msg);
},
error: function(e) {
alert("error");
}
});
return false;
});
I want to send all the data to ajax function. I am getting all the details there except city.
Try changing to this:
$( "#city" ).val();
Your select have to look like this:
<li><label>City:</label>
<select id="city">
<option value="New York">New York</option>
<option value="Sydney">Sydney</option>
</select>
</li>
Hope it helps you!
You just need to access the val() function for the select:
$('#city').val()
That will give you the value.
Note that the value is not the same as the display text, in that case you'll want to use the text() function.
Related
I need some help and advice if possible.
I'm working on a task for an online course and I'm stumped. I have the below html, trying to send a latitude value to ajax for a php request to geonames API and return the nearest ocean. I have tried a couple of different ways as shown below in the html code.
<select id="latitude">
<option value= "3.4360">3.4360</option>
<option value="lat">133.7751</option>
<option value="lat">106.3468</option>
</select>
<select id="longitude">
<option value= 55.3781>55.3781</option>
<option value="lng">25.2744</option>
<option value="lng">56.1304</option>
</select>
And this is the ajax request that should be pulling the info from the above html.
$('#btnRun').click(function() {
$.ajax({
url: "libs/php/getCountryInfo.php",
type: 'POST',
dataType: 'json',
data: {
lat: parseInt($('#latitude').val()),
lng: parseInt($('#longitude').val())
},
success: function(result) {
console.log(JSON.stringify(result));
if (result.status.name == "ok") {
$('#txtDistance').html(result['data'][0]['distance']);
$('#txtGeonameID').html(result['data'][0]['geonameid']);
$('#txtName').html(result['data'][0]['name']);
}
},
error: function(jqXHR, textStatus, errorThrown) {
// your error code
}
});
});
I don't think the two link up at all and I had a look at the parseInt option as well but I am out of ideas now.
Thank you for any help you can give.
The <option> tags in your Html are wrong, the value attribute is set to the strings lat and lng and not the actual latitudes and longitudes.
<select id="latitude">
<option value="3.4360">3.4360</option>
<option value="133.7751">133.7751</option>
<option value="106.3468">106.3468</option>
</select>
<select id="longitude">
<option value="55.3781">55.3781</option>
<option value="25.2744">25.2744</option>
<option value="56.1304">56.1304</option>
</select>
Also, if you exclude the value attribute then the text inside the option is considered its value. The markup below is equivalent to the one above.
<select id="latitude">
<option>3.4360</option>
<option>133.7751</option>
<option>106.3468</option>
</select>
<select id="longitude">
<option>55.3781</option>
<option>25.2744</option>
<option>56.1304</option>
</select>
Latitude and longitude values aren't integers so you cannot use parseInt on them, also there is no reason to parse them as numeric values as they will be converted back to String to be sent in the ajax call
$.ajax({
url: "libs/php/getCountryInfo.php",
type: 'POST',
dataType: 'json',
data: {
lat: $('#latitude').val(),
lng: $('#longitude').val()
},
success: function(result) {
console.log(JSON.stringify(result));
if (result.status.name == "ok") {
$('#txtDistance').html(result['data'][0]['distance']);
$('#txtGeonameID').html(result['data'][0]['geonameid']);
$('#txtName').html(result['data'][0]['name']);
}
},
error: function(jqXHR, textStatus, errorThrown) {
// your error code
}
});
how can i use a set_select option on ajax part for a dynamic dependent dropdown list, this list is clearing after validation errors, so i want to use set_select option here. kindly see below code:
<script type="text/javascript">
$(document).ready(function() {
$('select[name="relegion"]').on('change', function() {
var regID = $(this).val();
if(regID) {
document.write("ok");
$.ajax({
url: '/demo/main/selectcaste/'+regID,
type: "GET",
dataType: "json",
success:function(data) {
$('select[name="caste"]').empty();
$('select[name="caste"]').append('<option value=1>'+ "Not Interested to specify" +'</option>');
$('select[name="caste"]').append('<option value=2>'+ "InterCaste" +'</option>');
$.each(data, function(key, value) {
$('select[name="caste"]').append('<option value="'+ value.id +'">'+ value.name +'</option>');
});
}
});
}else{
$('select[name="caste"]').empty();
}
});
});
Maybe you need something like this,
View code.
<select name="category" id="category">
<option>Pilih Kategori Kelas</option>
<option value="1">category 1</option>
<option value="2">category 2</option>
</select>
<select name="sub_category" id="sub_category">
<option>Pilih category Kelas</option>
</select>
AJAX code.
$(document).ready(function(){
$('#category').on('change',function(){
var category_id = $(this).val();
if(category_id){
$.ajax({
type:'POST',
url:'<?php echo base_url()."profile_kelas/get_sub_category";?>',
data: {
category_id : category_id
},
success:function(html){
$('#sub_category').html(html);
}
});
}else{
$('#sub_category').html('<option>Pilih Sub category Kelas</option>');
}
});
});
My Controller code.
public function get_sub_category(){
$data = $this->model_profile->get_sub_category($_POST['category_id']);
foreach ($data as $row) {
echo '<option value="'.$row->id.'">'.$row->sub_category.'</option>';
}
}
You can make your parent category dynamically.
This question is SOLVED - solution is on the bottom of the question.
Let's say I have this form:
<form id="form1" action="" method="POST">
<select name="cars">
<option value="">Choose a car</option>
<option value="Ferrari">Ferrari</option>
<option value="Lamborghini">Lamborghini</option>
</select>
<select name="colors">
<option value="">Choose a color</option>
<option value="Green">Green</option>
<option value="Red">Red</option>
</select>
Php:
$cars = $_POST['cars'];
$colors = $_POST['colors'];
echo "Car: ".$cars." - Color: ".$colors."";
Ajax:
<script type='text/javascript'>
$('select[name="colors"]').on('change', function(){
$.ajax({
type: "POST",
url: "phpfile.php",
data: $("#form1").serialize(),
success: function(data){
$('#target1').html(data);
}
});
return false;
})
</script>
I want to show on html the results:
<div id="target1"></div>
I want to show the results when I choose the color (The 2nd dropdown):
onchange="this.form.submit()"
IT IS DONE:)
I used this code and it I am getting what I want:
<script type='text/javascript'>
$("#colorID").on("change", function() {
var $form = $("#form1");
var method = $form.attr("method") ? $form.attr("method").toUpperCase() : "GET";
$.ajax({
url: 'phpfile.php',
data: $form.serialize(),
type: method,
success: function(data){
$('#target1').html(data);
}
});
});
</script>
Technically you dont need ajax to get what your asking for but heres jQuery ajax example:
Change your HTML to:
<select name="colors" onchange="this.form.submit()">
<option value="">Choose a color</option>
<option value="Green">Green</option>
<option value="Red">Red</option>
</select>
$( "#form1" ).submit(function( event ) {
event.preventDeafault();
alert('form submitted');
$.ajax({
type: "POST",
url: "<YOUR PHP FILE PATH>",
data: $("#form1").serialize(),
success: function(data){
alert('ajax success');
$('#target1').html(data);
}else{
alert('ajax error');
}
});
return false;
})
In your PHP:
print_r($_POST);
$car = $_POST['car'];
$color = $_POST['color'];
echo "<p>Car: ".$car." - Color: ".$color."</p>";
This is untested - I've just typed it out on my phone during my lunch break!
To debug the php add this line ( to unsure the post worked):
print_r($_POST);
Use your browser developer tools to debug your AJAX and JS
I've add alerts to help you debug - you can remove these when its working
So I have this select field:
<select name="year" id = "year" class="dropdown-select">
<option value="2005">All Years</option>
<option value="2013">2013</option>
<option value="2012">2012</option>
<option value="2011">2011</option>
<option value="2010">2010</option>
<option value="2009">2009</option>
<option value="2008">2008</option>
<option value="2007">2007</option>
<option value="2006">2006</option>
</select>
And I have this jquery to get the selected value any time a new value is selected:
$("#year").change(function() {
input_year = parseInt($(this).val());
});
My question is how would I go about posting the 'input_year' variable to PHP every time the value changes?
The end goal is to do something with $_POST['year'] in PHP and return the result to JavaScript e.g echo "var res = " . $_POST['year'] . ";";
A very simple implementation
$.ajax({
type:'POST',
url:'your_url.php',
data:'input_year='+input_year,
success: function(msg) {
console.log(msg);
}
});
data string may need a ? before it, I can't remember off the top of my head
Use AJAX, specifically the jQuery .post() function:
$("#year").change(function() {
input_year = parseInt($(this).val());
$.post('/path/to/file', year: input_year, function(data, textStatus, xhr) {
/*optional stuff to do after success */
});
});
$("#year").change(function() {
var input_year = parseInt($(this).val());
$.post('server.php',{year:input_year}, function(result,status){});
});
Using ajax. With jquery, it would be like this:
$.ajax({
type: 'POST',
dataType: 'text',
url: "(your php filename)",
data: $.param({'year': input_year}),
success:function(data){
//do whatever you need to do with the received result
}
error: function (request, status, error) {
alert(request.responseText);
}
});
Here is what I have done so far:
<label for="popupDatepicker">DOB<span class="red">*</span></label>
<input class="text1" type=text id="popupDatepicker" name="popupDatepicker" maximun=30>
<label for="gender">I am<span class="red">*</span></label>
<select name="gender" id="gender">
<option value="M">Male</option>
<option value="F">Female</option>
</select>
jQuery code:
$(document).ready(function() {
$("#gender").blur(function() { // when focus out
//$("#message").html(''); //before AJAX response
var form_data = {
action: 'gender',
gender: $(this).val(),
popupDatepicker: $(this).val(),
};
$.ajax({
type: "POST",
url: "functions.php",
data:form_data,
success: function(result) {
$("#genders").html(result);
//alert("Hiiiiiiiiiiiiiiiii");
}
});
});
});
I want to pass both birthdate and gender after selecting the gender.
Another way of doing this, is simply adding the individual post variables within the data blob directly within the ajax call.
For example (not tested - may break):
data: ({
a:'gender',
g:$('#gender').val(),
d:$('#popupDatepicker').val()
}),
On the server side you'll see the 'a', 'g' and 'd' post variables!