AJAX Receive multiple data - javascript

I am trying to populate some drop down fields. I have the following dropdown:
Continent
Country
Sport
I want to select first Continent, after that the Country and Sport to populate dynamically. Example:
Europe -> (All Europe countries appear correctly, they are in db).
I choose Algeria; the Sport names should appear on drop down. The json is correct but the ajax, I know, is wrong!
Here is my code:
$(document).ready(function(){
$('#select_continents').on('change', function(){ //continent drop down ID
$('#select_countries').empty();// country drop down ID
$('#select_sport').empty();// sport drop down ID
$.ajax({
method: 'GET',
url: './json.php',
data: { json_continent_country : 1, continent : $('#select_continents').val(), json_country_sport : 1, country : $('#select_countries').val() }
})
.done(function(data){
$.each(JSON.parse(data), function(i, val)
{
$('#select_countries').append('<option value="'+val.id+'">'+val.country_name+'</option>');
$('#select_sport').append('<option value="'+val.id+'">'+val.sport_name+'</option>');
})
})
.fail(function(){
alert('error');
})
})
})
This is what I get:
Any advice?

Why are you reloading the sports list only in case the continent is changed? You are saying that you wish to update the sports list when the country changes, that's not what your code is doing.
Try this instead (omitting any formatting or text elements):
<script type="text/javascript">
$('#continent').on('change', function() {
var continent= $('#continent').val();
// update sport list
$.ajax('./json.php', {
data: {
"continent": continent
}, success: function(data) {
// clear and update sports SELECT
$('#country').html('');
for (var i in data) {
$('#country').append($('<option>').val(data[i].val_id).text(data[i].country_name)
}
}
});
});
$('#country').on('change', function() {
var continent= $('#continent').val();
var country= $('#country').val();
// update sport list
$.ajax('./json.php', {
data: {
"continent": continent, // most likely not relevant, country itself should suffice
"country": country
}, success: function(data) {
// clear and update sports SELECT
$('#sport').html('');
for (var i in data) {
$('#sport').append($('<option>').val(data[i].val_id).text(data[i].sport_name)
}
}
});
});
</script>
<body>
<select id="continent">
<option value="Europe">Europe</option>
</select>
<select id="country">
</select>
<select id="sport">
</select>
</body>
besides, your val.id in your code is the same for country and sport?

Related

Facing Issue in ajax

I am new to laravel and ajax... i want to show the state of the selected country in dropdown list but when i select the country from the dropdown list it get data from the laravel perfectly and get it in ajax also.. but it is not able to append the data in html option tag.. for more details i am attaching the code of ajax also...`
$("#country").change(function(e){
var countryid = $(this).val();
console.log("Change Event Happpened on id : "+ countryid);
$.ajax({
type :"GET",
url :"GetStates/"+countryid,
success : function(statelist){
$("#state").empty();
$("#state").append('<option> Select State...</option>')
$.each(statelist,function (statename,stateid) {
**$("#state").append('<option>' + statename + ' </option>') // This line of code is not working**
console.log("in each function");
});
}
});
})
`
You're using jQuery.each function wrongly. jQuery.each callback function accepts two arguments:
Function( Integer indexInArray, Object value )
So according to your (wrong) code:
$.each(statelist,function (statename,stateid)
statename holds index of item and stateid receives statelist item, which clearly is against your idea.
Assuming that statelist has the following structure:
statelist = [
{
statename: 'LA',
stateid: 1
}
]
callback function should look like the following:
$.each(statelist,function (index, state) {
$("#state").append(`<option value="${state.stateid}">${state.statename}</option>`)
});
You can use javascript object destructuring to make this simpler:
$.each(statelist,function (index, {stateid, statename}) {
$("#state").append(`<option value="${stateid}">${statename}</option>`)
});
Working code:
const statelist = [{
statename: "LA",
stateid: 1
},
{
statename: "MA",
stateid: 2
},
];
$("#state").empty();
$("#state").append("<option value=''>Please select a state...</option>");
$.each(statelist, (index, {
statename,
stateid
}) => {
$("#state").append(`<option value="${stateid}">${statename}</option>`);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="state">
<option>This will be removed</option>
</select>

how to populate two <selects> via ajax with a json

I am making a system and I came across the following doubt .. I have two being the first to select the brand of the vehicle and the second would be to select the model of the vehicle. but I would like to select the brand of the vehicle and the of the model to load the models of the vehicles for the selected brand.
i have onde archive .json with brand and models of cars.
exemple format json
"value":"ACURA","title":"Acura","models":[{"value":"CL_MODELS","title":"CL Models (4)"}]}
<select id="brand"></select>
<select id="models"></select>
so I populate the first with the tags so the second would be populated with the models referring to the selected brand.
I need it when I select, for example BMW, the second select only the models referring to BMW, and not all models.
How do you do this?
thanks :)
I don't know enough about how the data is being fetched, but I believe you're asking about manipulating it in a way that makes it usable by the 2 selects. Take a look at the example below:
var json = [{
"value": "ACURA",
"title": "Acura",
"models": [{
"value": "CL_MODELS",
"title": "CL Models (4)"
}]
},
{
"value": "TOYOTA",
"title": "Toyota",
"models": [{
"value": "TOYOTA_MODELS",
"title": "Toyota Models (4)"
}]
}
];
$(document).ready(function() {
$('#models').prop('disabled', true);
$('#brand')
.append($("<option></option>")
.attr("value", "")
.text(""));
$.each(json, function(index) {
$('#brand')
.append($("<option></option>")
.attr("value", json[index]["value"])
.text(json[index]["title"]));
});
$('#brand').change(function() {
process($(this).children(":selected").html());
});
});
function process(brand) {
$('#models').prop('disabled', false).find('option')
.remove()
.end();
var models = $.map(json, function(entry) {
if (entry["title"] === brand) {
return entry["models"];
}
});
$.each(models, function(index) {
$('#models')
.append($("<option></option>")
.attr("value", models[index]["value"])
.text(models[index]["title"]));
});
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="brand"></select>
<select id="models"></select>
//YOUR_JSON_DATA
//{"value":"ACURA","title":"Acura","models":[{"value":"CL_MODELS","title":"CL Models (4)"}]}
$.get( YOUR_JSON_DATA, function( data ) {
// Did you want data to be an array of brands?
for (let brand of data) {
$("#brand").append(`<option>${ brand.value }</option>`)
for (let models of brand.models) {
$("#models").append(`<option> ${ models.value } </option>`)
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="brand"></select>
<select id="models"></select>
Here is an example code snippet for ya. I hope it provides some clarity. Did you want the JSON data be an array?

How to change the value of the drop-down on change event?

I have two drop-down lists which are from same table. One contains employee code and second one contains employee name. If I change the employee code then other drop-down should show the employee name relevant to code and if I change the employee name then it should show the code. I am able to successfully retrieve the values but I am unable to show value in the drop-down. Following is my code:
$("select#code").on("change", function () {
getNameFunc($(this).val())
});
$("select#empName").on("change", function () {
getCodeFunc($(this).val())
});
function getNameFunc(value) {
$.ajax({
url: '#Url.Action("getName", "Employees")',
data: { id: value },
cache: false,
type: "GET",
success: function (data) {
$("#empName").val(data.Name);
}
});
}
function getCodeFunc(value) {
$.ajax({
url: '#Url.Action("getCode", "Employees")',
data: { id: value },
cache: false,
type: "GET",
success: function (data) {
$("#code").val(data.Code);
}
});
}
My drop-down list:
#Html.DropDownList("EmpCode", null, htmlAttributes: new { id = "code" })
#Html.DropDownList("EmpName", null, htmlAttributes: new { id = "empName" })
In alert function, I am getting expected value but the problem is displaying it in to drop-down list.
Simple , Try it , Let me assume selects render as , this is dummy test , best approch you must save value = EmpID
Emp Name dropdown
<select id="name">
<option value="EmpID1"> Name 1 </option>
<option value="EmpID2"> Name 2 </option>
</select>
Emp Code dropdown
<select id="code">
<option value="EmpID1"> Code 1 </option>
<option value="EmpID2"> Code 2 </option>
</select>
Inside your ajax , if you want change/load name front the of the dropdown then
Value set by value
$('#name').val(data.EmpID1)
Similarly reverse
$('#code').val(data.EmpID1)
Value set by text / name
$('#name option:selected').text(data.Name)
Check this code. You might get help from this.
Note that I have not implemented ajax call in this code.
$("#emp_code").on("change",function(){
$("#emp_name").val($("#emp_code").val());
});
$("#emp_name").on("change",function(){
$("#emp_code").val($("#emp_name").val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Emp Code:</label>
<select id="emp_code">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<br/>
<label>Emp Name:</label>
<select id="emp_name">
<option value="1">ABC</option>
<option value="2">XYZ</option>
<option value="3">PQR</option>
<option value="4">JKL</option>
</select>

How to get Select2 to update a ajax call when country value is changed

I can't seem to find an easy example of how to update the states list when the country list has changed. All examples I've seen to be using all sorts of bits and peices that work depending on version and who is giving the solution.
Can someone help me how this can be easily done without ugly hacks. I've tried this so far and whilst it works, if I change the drop down for the second time, the new values just get appended to the old ones instead of replacing them. I've tried destroying and rebuilding but old values remain.
The data coming back from the server is valid json with id and text values. So far I've had no luck in getting the state list to update with new country state values when the country is changed
<select id="country" name="country" class="form-control" data-placeholder="Select...">
<optgroup label="Country">
<option></option>
<option value="US" > United States</option>
<option value="AU" > Austrailia</option>
</optgroup>
</select>
<select id="state" name="state" class="form-control" data-placeholder="Select...">
<optgroup label="State">
<option></option>
</optgroup>
</select>
$("#country").select2().on("change", function(e) {
var country = e.val;
$.post("states", {
country_id: country
}, function(e) {
if (e)
$("#states").select2({
data: e
});
})
});
$("#state").select2();
These are the values sent back from server
[{ id: 'ALB', text: 'ALABAMA' }, { id: 'ALS', text: 'ALASKA' }, { id: 'ARI', text: 'ARIZONA' }]
You have to remove the <option> tags from the select before setting the new data:
$.post("states", {
country_id: country
}, function(e) {
if (e){
$("#states option").remove();
$("#states").select2({
data: e
});
}
})
You may want to refine my example to avoid removing placeholders, if any.
See also this JSFiddle: https://jsfiddle.net/drj84go5/
The best option is to have an input (text) not a select2 and then convert it through select2 function using ajax.
Input:
<input type="text" id="states">
Javascript:
$('#states').select2({
placeholder: "States...", // placeholder
allowClear: true,
minimumInputLength: 0,
dropdownCssClass: "bigdrop",
width: '100%',
ajax: {
quietMillis: 2500,
url: "/Search/_SearchStates", // Server-side action
dataType: 'json',
data: function (term, page) {
return {
Text: term, // Text to search for
CountryId: $("#country").val(), // CountryId from #countries
};
},
results: function (data, page) {
return { results: data };
},
},
formatResult: function (item) {
return item.StateName; // Table name/description
},
id: function (element) {
return element.StateId; // Table id/code
},
formatSelection: function (item) {
return item.StateName; // Table name/description
}
});
You need to have a server-side action that will give you the list of states.
To get the StateId you need to do:
$("#states").select2('val');

Change or Focus in jQuery? Which event should I use with select dropdown to give a call to jQuery-AJAX function?

I've one select dropdown control in HTML as follows :
<select id="student" name="student" class="form-control"></select>
I want to call a jQuery-AJAX function which will add the option values to the above HTML select control.
Following is the code for I've written for it:
$.ajax({
url : "http://google.com",
cache: false,
dataType: "json",
type: "GET",
async: false,
data: {
'request_type':'ajax',
'op':'get_all_students'
},
success: function(result, success) {
$('#student').html(result);
},
error: function() {
alert("Error is occured");
}
});
My issue is on which event of HTML select dropdown should I call the above jQuery-AJAX function in order to add the option values dynamically?
Please suggest me the proper way to do this.
on page load is a good option.
jQuery(function($) {
// Ajax call populate select options
$.ajax({ /* ... */ });
});
if it depends on other selected elements, then bind change event on first dropdownlist
e.g. nested dropdown list
<select id="teacher" name="teacher" class="form-control">
<option value="">Please select</option>
<option value="1">Teacher 1</option>
<option value="2">Teacher 2</option>
</select>
<select id="student" name="student" class="form-control"></select>
<script type="text/javascript">
jQuery(function($) {
$("#teacher").on('change', function() {
// Ajax call populate select options
$.ajax({ /* ... */ });
});
});
</script>
Listen for change event on select and then create the the dynamic <option> elements poulating the #student element with them:
var data = {
1: [{name: "Alice", id: 1}, {name: "Bob", id: 2}],
2: [{name: "Carol", id: 2}, {name: "Dave", id: 3}]
};
function getStudents() {
var result = data[$("#school").val()];
var $options = [];
$.each(result, function (i, c) {
var $opt = $("<option>");
$opt.attr({
value: c.id
}).text(c.name);
$options.push($opt);
});
$("#students").append($options);
}
$("#school").on("change", getStudents);
getStudents();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="school">
<option value="1">School 1</option>
<option value="2">School 2</option>
</select>
<select id="students"></select>

Categories