Jquery get values from select boxes and make AJAX call - javascript

I have multiple select boxes, where I want to get the value of each selected option and make an AJAX call based on the selected options. How can I achieve that?
I have this so far:
$('select[name="restaurant_chosen"]').on('change', function() {
var restaurant_id = $(this).val();
});
$('select[name="date_chosen"]').on('change', function() {
var date_chosen = $(this).val();
});
$.ajax({
type: 'GET',
url: '/api/' + restaurant_id + '/' + date_chosen +
success: function(data) {
console.log(data)
},
error: function(data){
console.log('error')
}
});
the 2 variables restaurant_id and date_chosen I get the error not defined. What am I doing wrong?

function sendToServer(values, onSuccess, onError){
var restaurant_id, date_chosen;
//here fill restaurant_id and date_chosen using values
$.ajax({
type: 'GET',
url: '/api/' + restaurant_id + '/' + date_chosen, //replace the plus by a comma
success: function(data) {
onSuccess(data);
},
error: function(data){
onSuccess(data);
}
});
}
$('select').on('change', function() {
var values = [];
$('select').each(function(index){
v = $(this).val();
n = $(this).attr("name");
values.push( {"name":n, "value":v} );
});
console.log("values: ", values);
sendToServer(values,
function(data){
console.log(data);
},
function(data){
console.log('error', data);
}
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="brand">
<option value="volvo">Volvo</option>
<option value="audi">Audi</option>
</select>
<select name="color">
<option value="red">Red</option>
<option value="blue">Blue</option>
</select>

And that is how it should be. You're declaring your variable within a private function context, which you cannot (and must not) access from the outside.
Simple solution, move the declaration of your two variable out of the onchange event handlers (make it more global).
var restaurant_id;
date_chosen;
$('select[name="date_chosen"]').on('change', function() {
date_chosen = $(this).val(); // skip the var here
});

Related

Dynamic populating dropdown using jquery/ajax

I am trying to dynamically populat the drop down list based on the selected value of first list.
NOTE: Both dropdowns are multiple selection dropdown:
This is the code for my dropdowns:
<select id="dis" name="dis[]" onChange="AjaxFunction();" class="form-control selectpicker show-menu-arrow" multiple title="Select a City or Division">
// my discrictes goes here
</select>
<select id="zone" name="zone[]" class="form-control show-menu-arrow" multiple title="Choose Educational Zone" ></select>
To do this I found AjaxFunction() javascript function. And its as below:
function AjaxFunction(){
var httpxml;
try {
// Firefox, Opera 8.0+, Safari
httpxml=new XMLHttpRequest();
} catch (e) {
// Internet Explorer
try {
httpxml=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
httpxml=new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("Your browser does not support AJAX!");
return false;
}
}
}
function stateck() {
if(httpxml.readyState==4) {
var myarray = JSON.parse(httpxml.responseText);
// Before adding new we must remove previously loaded elements
for(j=document.getElementById('s2').length-1;j>=0;j--) {
document.getElementById('s2').remove(j);
}
for (i=0;i<myarray.data.length;i++) {
var optn = document.createElement("OPTION");
optn.text = myarray.data[i].name_si;
optn.value = myarray.data[i].zone_id;
document.getElementById('s2').options.add(optn);
}
}
}
var str='';
var s1ar=document.getElementById('s1');
for (i=0;i< s1ar.length;i++) {
if(s1ar[i].selected) {
str += s1ar[i].value + ',';
}
}
//alert (s1ar);
var str=str.slice(0,str.length -1); // remove the last coma from string
//alert(str);
//alert(str);
var url="../includes/dropdown-zones.php";
url=url+"?dis_id="+str;
url=url+"&sid="+Math.random();
//alert(url);
httpxml.onreadystatechange=stateck;
httpxml.open("GET",url,true);
//httpxml.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
httpxml.setHeader('Content-type', 'application/json');
httpxml.send(null);
}
My question is, now I need to convert above function to jquery, because I am looking for a jQuery/Ajax solution for this:
This is how I tried it using jQuery:
$('#dis').on('change',function() {
var str='';
var s1ar=document.getElementById('dis');
for (i=0;i< s1ar.length;i++) {
if(s1ar[i].selected) {
str += s1ar[i].value + ',';
}
}
var str=str.slice(0,str.length -1);
var url="../includes/dropdown-zones.php";
url=url+"?dis_id="+str;
url=url+"&sid="+Math.random();
$.ajax({
type: "GET",
url: url,
contentType: "application/json; charset-utf-8",
dataType: "json",
success: function(data) {
$('#zone').empty();
$('#zone').append("<option value=''>- Select Zone-</option>");
$.each(data, function(i,item){
var selecting;
if (selected === data[i].id) {
selecting = ' selected="selected"';
} else {
selecting = '';
}
$('#zone').append('<option '+selecting+' value="'+data[i].id+'">'+data[i].name+'</optoin>');
});
},
complete: function() {}
});
});
But is not working for me. Can anybody help me out to figure this out?
Thank you
The code is fine, I am getting error with "selected" is undefined
You can see if(selected === data[i].id) here "selected" variable is not assigned to selected value from first dropdown.
also you need to remove onChange="AjaxFunction();" from first dropdown because now your are using jQuery
Check below code:
$(document).ready(function(){
$('#dis').on('change',function() {
var str='';
var s1ar=document.getElementById('dis');
for (i=0;i< s1ar.length;i++) {
if(s1ar[i].selected) {
str += s1ar[i].value + ',';
}
}
var str=str.slice(0,str.length -1);
var url="dropdown-zones.php";
url=url+"?dis_id="+str;
url=url+"&sid="+Math.random();
$.ajax({
type: "GET",
url: url,
contentType: "application/json; charset-utf-8",
dataType: "json",
success: function(data) {
$('#zone').empty();
$('#zone').append("<option value=''>- Select Zone-</option>");
$.each(data, function(i,item){
var selecting='';
if ($('#dis').val().findIndex(x => x==data[i].id)>=0) {
selecting = ' selected="selected"';
} else {
selecting = '';
}
$('#zone').append('<option '+selecting+' value="'+data[i].id+'">'+data[i].name+'</optoin>');
});
},
complete: function() {}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="dis" class="form-control selectpicker show-menu-arrow" multiple title="Select a City or Division">
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
</select>
<select id="zone" class="form-control show-menu-arrow" multiple title="Choose Educational Zone" ></select>
The result is some like this:
jSon file value is :
[{
"id": 1,
"name": "New"
},
{
"id": 2,
"name": "Open"
},
{
"id": 3,
"name": "Close"
}
]

Add ajax return value to selectbox?

I am trying to insert a value from my database to select box using it's ID. this my code for that
<select id="branch_name">
<option value="0">Select branch Name</option>
</select>
$.ajax({
url : 'get_savac_member_data.php',
method : "POST",
data : data,
success : function(response){
// window.location.replace("items_insert_form.php");
var res = response;
var segments = response.split(",");
$("#brnch_name").val(segments[17].trim());
}
});
My value has returned successfully. But, it shows nothing to my select box. Can anyone help me please?
You need to add proper html to select. Something like
for(var key in obj) {
html += "<option value=" + key + ">" +obj[key] + "</option>"
}
And then $("#brnch_name").html(html).
For this example, I assume you are getting response in json format
Here is my solution:
$("#brnch_name").empty(); //clear the drop down box
for (var i=0;i<segments.length;i++)
{
html="<option value=\""+segments[i]+"\">"+segments[i]+"</option>";
$("#brnch_name").append(html);
}
You can loop the response and append to select with $('#branch_name').append($('<option>', { value: item.value, text : item.text })); here value is the value of option and text is text to be displayed on dorpdown.
$.ajax({
url : 'get_savac_member_data.php',
method : "POST",
data : data,
success : function(response){
// window.location.replace("items_insert_form.php");
var res = response;
var segments = response.split(",");
$.each(res, function (i, item) {
$('#branch_name').append($('<option>', {
value: item.value,
text : item.text
}));
});
});
<select id="branch_name">
<option value="0">Select branch Name</option>
</select>
Use $.each like below:
$.ajax({
url : 'get_savac_member_data.php',
method : "POST",
data : data,
success : function(response){
// window.location.replace("items_insert_form.php");
var res = response;
var segments = response.split(",");
$.each(res, function (key, value) {
$("#brnch_name").append($("<option></option>").val(segments[key].trim());
});
}
});
You need to iterate through each branch names from response and append the same as individual <option> tags. However you have already got several solutions for the same, while mine uses simple string replace.
/* this is only relevant script */
var response = 'Branch 1,Branch 2,Branch 3,Branch 4';
$('<option>' + response.replace(/\,/g, '</option><option>') + '</option>').appendTo('#branch_name');
/*in-case you wish to show a default selection */
$('#branch_name').prop('selectedIndex', 3);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="branch_name"><option value="0">Select branch Name</option></select>

how to insert/pass an result value city into input field value=“city”

This script works well, the town that it generates function must register in but he generates so city
how to insert/pass value #city into input field
value="cityname"
<input id="city" name="input" value="cityname" />
<script>
$(document).ready( function () {
var lat = 37.42;
var long = -122.08;
$.ajax({
type: 'GET',
dataType: "json",
url: "http://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+long+"&sensor=false",
data: {},
success: function(data) {
$('#city').html(data);
$.each( data['results'],function(i, val) {
$.each( val['address_components'],function(i, val) {
if (val['types'] == "locality,political") {
if (val['long_name']!="") {
$('#city').html(val['long_name']);
}
else {
$('#city').html("unknown");
}
console.log(i+", " + val['long_name']);
console.log(i+", " + val['types']);
}
});
});
console.log('Success');
},
error: function () { console.log('error'); }
});
});
</script>
Directly write :
$('#city').val(val['long_name']);
To assign a value to an input field use .val():
$('input#city').val(newValue);
Substitute
$("#city").val(/* value to set */)
for each occurrence of
$("#city").html(/* value to set */)

How to extract and add the JSON data received as a AJAX response to the HTML select drop down using jQuery?

I've following HTML code :
<select id="student" name="student" class="form-control"></select>
The jQuery-AJAX function I've written for adding the options to the above HTML select control is as follows :
var mod_url = $('#mod_url').val();
$.ajax({
url : mod_url,
cache: false,
dataType: "json",
type: "GET",
async: false,
data: {
'request_type':'ajax',
},
success: function(result, success) {
$('#student').html(result);
},
error: function() {
alert("Error is occured");
}
});
From PHP file I've received a big array encoded into JSON format(i.e. the result variable from jQuery-AJAX function). For your reference I'm showing below only the first four records from that array. In HTML select control actually I want to show all the elements from this array.
[{"id":2,"stud_name":"John Dpalma","stud_address1":"277 Eisenhower Pkwy","stud_address2":"","stud_city":"Edison","stud_state":"New Jersey","stud_country":"USA","stud_zipcode":"07039","stud_email":"abc#gmail.com","created_at":1409739580,"updated_at":1410253832},
{"id":3,"stud_name":"Anthony Gonsalvis","stud_address1":"520 Division St","stud_address2":"","stud_city":"Piscataway","stud_state":"NJ","stud_country":"USA","stud_zipcode":"07201","stud_email":"pqr#gmail.com","created_at":1409740530,"updated_at":1410255590},
{"id":4,"stud_name":"James Bond","stud_address1":"6 Harrison Street, 6th Floor","stud_address2":"Ste-2324","stud_city":"New York","stud_state":"NY","stud_country":"USA","stud_zipcode":"10013","stud_email":"xyz#gmail.com","created_at":1409757637,"updated_at":1412263107},
{"id":9,"stud_name":"Mary Jane","stud_address1":"2112 Zeno Place","stud_address2":"CA","stud_city":"Venice","stud_state":"CA","stud_country":"","stud_zipcode":"90291","stud_email":"utp#gmail.com","created_at":1409908569,"updated_at":1410254282}]
In HTML select control I want to set the values in following manner(consider first two records from above array)
<select id="student" name="student" class="form-control">
<option value="">Select Store</option>
<option value="2">John Dpalma, 277 Eisenhower Pkwy, Edison</option>
<option value="3">Anthony Gonsalvis, 520 Division St, Piscataway</option>
</select>
You might have observed from the expected output above that I want to set the value of option as a id from array and the text that I want to display is comprising of stud_name+stud_address1+stud_city
How should I manage this for all the elements from the JSON data in my code?
Also please guide me in showing the loading option into the select control until the response from PHP comes.
Please provide me some help.
success: function(result, success) {
var $select = $('#student');
$.each(result, function (i, option) {
var txt = [option.stud_name, option.stud_address1, option.stud_city];
if (option.stud_address2)
txt.splice(2, 0, option.stud_address2);
$('<option>', {
value: option.id,
text: txt.join(', ')
}).appendTo($select);
});
},
or with $.map (slightly more efficient):
success: function(result, success) {
var options = $.map(result, function (option) {
var txt = [option.stud_name, option.stud_address1, option.stud_city];
if (option.stud_address2)
txt.splice(2, 0, option.stud_address2);
return $('<option>', {
value: option.id,
text: txt.join(', ')
});
});
$('#student').append(options);
},
In PHP file echo the following in a loop:
echo '<option value="">'.$stud_name.', '.$stud_address1.', '.$stud_address2.', '.$stud_city.', '.$stud_state.', '.$stud_country.'</option>';
Then attach this result to the select dropdown with jQuery through the ajax success.
Here is my solution. This checks address 2 and adds it to the options accordingly.
JS code:
for(var i=0;i<result.length;i++){
if(result[i]["stud_address2"]==""){
$('#student').append('<option value="' + result[i]["id"] + '">' + result[i]["stud_name"] + ', ' + result[i]["stud_address1"]+ ', ' +result[i]["stud_city"] +'</option>');}
else{
$('#student').append('<option value="' + result[i]["id"] + '">' + result[i]["stud_name"] + ', ' + result[i]["stud_address1"]+ ', '+ result[i]["stud_address2"]+ ', ' +result[i]["stud_city"] +'</option>');
}
}
Here is a working DEMO
This is exactly what you need!
$(document).ready(function(){
var mod_url = $('#mod_url').val();
$.ajax({
url : mod_url,
cache: false,
dataType: "json",
type: "GET",
async: false,
data: {
'request_type':'ajax',
},
success: function(result, success) {
$.each(result,function(index,item){
$label = item.stud_name +', ' + item.stud_address1 +', ' + item.stud_city;
$('#student').append('<option value="'+ item.id +'">'+ $label +'</option>');
});
},
error: function() {
alert("Error is occured");
}
});
});
It's a matter of iterating over the JSON you receive from the server, creating option tags for each record, then appending them to the select element:
var response = [{"id":2,"stud_name":"John Dpalma" ... }]
$.each(response, function (index, record) {
if (!record.stud_address2){
var stud_address2 = "";
} else {
var stud_address2 = record.stud_address2;
}
$('<option>', {
value: record.id,
text: record.stud_name + ", " + record.stud_address1 + ", " + record.stud_city + ", " + stud_address2
}).appendTo("#student");
});
Demo
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<script>
function __highlight(s, t) {
var matcher = new RegExp("(" + $.ui.autocomplete.escapeRegex(t) + ")", "ig");
return s.replace(matcher, "<strong>$1</strong>");
}
$(document).ready(
function() {
$("#suggest").autocomplete(
{
source : function(request, response)
{
$.ajax({
url : 'URL',
dataType : 'json',
data : { term : request.term },
success : function(data)
{
//alert(data[0].title);
response($.map(data, function(item) {
//alert(item);
return {
label : __highlight(item.title, request.term),
value : item.title
};
}));
}
});
},
minLength : 3,
select : function(event, ui)
{
if(ui.item){
$(event.target).val(ui.item.value);
}
//submit the form
$(event.target.form).submit();
}
}).keydown(function(e) {
if (e.keyCode === 13)
{
$("#search_form").trigger('submit');
}
}).data("autocomplete")._renderItem = function(ul, item)
{
return $("<li></li>").data("item.autocomplete", item).append(
$("<a></a>").html(item.label)).appendTo(ul);
};
});
</script>

Optionset change event is not being triggered via JQuery

Here is the html:
<select id="langOptionSet">
<option value="english">English</option>
<option value="spanish">Spanish</option>
</select>
Here is the script which i have written for language change:
$(function(){
SetSelectedLanguageText();
});
var SetSelectedLanguageText = (function ($){
var language = $("#langOptionSet option:selected").val();
alert(language);
$.ajax({
url: 'languages.xml',
success: function(xml) {
$(xml).find('translation').each(function(){
var id = $(this).attr('id');
var text = $(this).find(language).text();
$("." + id).html(text);
});
}
});
$("#langOptionSet").change(function() {
SetSelectedLanguageText();
});
But the function SetSelectedLanguageText is not being triggered even on page load. What's wrong with this script?
thanks

Categories

Resources