JQuery Select Populate - ajax

i have to items on my html
a Input text (company) field and a select (Company_List)
when user types in the text field i want jQuery to use /Home/SearchSynonym/ to get the names and display it in select (the SearchSynonym takes the value user types and do a wildcard search and returns ID and NAME )
can some one help , am new ti jQuery
Leb

You need to clarify as to in which format does SearchSynonym return the IDs and NAMEs? Is it in JSON? If it is in JSON, then try the following:
var companyList = $("#Company_List");
$("#company").change( function(){
$.getJSON("/Home/SearchSynonym/",{ query: $(this).val() }, function(response){
var responseList = "";
$.each(result, function(index, item){
responseList += "<option value='" + item.id + "'>" + item.name + "</option>";
});
companyList.html(responseList);
});
});
This would work if your 'company' text field bears the id="company" in the tag decleration, your 'Company_List' dropdown bears the id="Company_List" in the tag decleration and your server end receives the parameter "query" for pulling records.

You can use setTimeout. Try this:
var companyList = $("#Company_List");
$("#company").change( function(){
setTimeout( function() {
$.getJSON("/Home/SearchSynonym/",{ query: $(this).val() }, function(response){
var responseList = "";
$.each(result, function(index, item){
responseList += "<option value='" + item.id + "'>" + item.name + "</option>";
});
companyList.html(responseList);
});
}, 2000);
});
The value of 2000 indicates a 2 second delay.

Related

AJAX dropdown list down not update with var string variable

I have a test script to update a county drop down list whenever the year or state is updated. When I used a literal string when year is selected, the county list updated fine. However when I tried to the county list using an ajax call and used a (var options) to build the list, the drop down list value changed to an empty list even though I verified the value of (var options) contains valid drop down list options.
Please help!
Thanks,
$('#State').on("change", function () {
var state = $('#State').val();
var year = $('#Year').val();
var obj = {
state: state,
year:year
};
alert("State changed:" + state + ":" + year);
AjaxCall('/RIC/GetCounties', JSON.stringify(obj), 'POST').done
(function (response) {
if (response) {
$('#DataId').html("<option value='test'>Test</option>");
var options = '';
options += "<option value='Select'>Select</option>\n";
for (i in response) {
options += "<option value='" + response[i].DataId + "'>" + response[i].County + "</option>\n";
}
$('#DataId').html("<option value='Select'>Select-S</option><option value='16'>Alameda-S</option>");
alert("Statitical Areas(S): " + options);
//$('#DataId').html(options); //This should work. How to get the value of options into the string
//$('#DataId').append(options);
}
}).fail(function (error) {
alert("County Error:" + error.StatusText);
});
});
$('#Year').on("change", function () {
var state = $('#State').val();
var year = $('#Year').val();
var obj = {
state: state,
year: year
};
alert("Year changed:" + state +":"+ year);
AjaxCall('/RIC/GetCounties', JSON.stringify(obj), 'POST').done
(function (response) {
if (response) {
$('#DataId').html("<option value='test'>Test</option>");
var options = '';
options += "<option value='Select'>Select</option>\n";
for (i in response) {
options += "<option value='" + response[i].DataId + "'>" + response[i].County + "</option>\n";
}
//$('#DataId').html("<option value='Select'>Select-Y</option><option value='16'>Alameda-Y</option>");
$('#DataId').html(options); //This should work. How to get the value of options into the string
alert("Statitical Areas(Y): " + options);
//$('#DataId').append(options);
}
}).fail(function (error) {
alert("County Error:" + error.StatusText);
});
});
});
function AjaxCall(url, data, type) {
  return  $.ajax({
     url:  url,
     type:  type  ?  type  :  'GET',
     data:  data,
     contentType:  'application/json'
   });
}  
Instead of using another function to call your $.ajax why not call it immediately. There’s no performance improvement on what you had done. Try to revert your code and just add async property if you want to wait the response before proceeding to your lower conditions.
I hope this will help you

Parsing JSON with AJAX - show random item of the JSON and update after an amount of time

I'm able to parse JSON with ajax, but at the moment it shows all the names out of the JSON.
I want only one name viewed and after an amount of time I want another one viewed and so on..
Ajax code:
$(document).ready(function(){
parseJson();
});
function parseJson(){
$.ajax({
url : 'data/members.json',
dataType : 'json',
success : function(data) {
succes(data);
},
error: function(){
window.alert("error");
}
});
};
function succes(dataObj){
var counter = 1;
$.each(dataObj.Members.Member, function(indexData, valueData){
var htmlString = "";
htmlString += '<article class="memberInfo" data-object="' + counter + '">';
htmlString += "<div class=''><p>" + valueData.Firstname + ' ' + valueData.Surname + "</p></div>";
htmlString += "</article>";
$("#members").append(htmlString);
counter++;
});
}
Rather than use .append you can use .html and set a staggering timeout so that it cycles through the names that get displayed:
var timer = 0;
$.each(...
setTimeout(function () {
var htmlString = "";
/* snip */
$("#members").html(htmlString);
}, timer + (indexData * 2000));
});

how to use cascading dropdownlist in mvc

am using asp.net mvc3, i have 2 tables in that i want to get data from dropdown based on this another dropdown has to perform.for example if i select country it has to show states belonging to that country,am using the following code in the controller.
ViewBag.country= new SelectList(db.country, "ID", "Name", "--Select--");
ViewBag.state= new SelectList("", "stateID", "Name");
#Html.DropDownListFor(model => model.Country, (IEnumerable<SelectListItem>)ViewBag.country, "-Select-")
#Html.DropDownListFor(model => model.state, (IEnumerable<SelectListItem>)ViewBag.state, "-Select-")
but by using this am able to get only the countries.
There is a good jQuery plugin that can help with this...
You don't want to refresh the whole page everytime someone changes the country drop down - an ajax call to simply update the state drop down is far more user-friendly.
Jquery Ajax is the best Option for these kind of questions.
Script Code Is Given below
<script type="text/javascript">
$(function() {
$("##Html.FieldIdFor(model => model.Country)").change(function() {
var selectedItem = $(this).val();
var ddlStates = $("##Html.FieldIdFor(model => model.state)");
$.ajax({
cache:false,
type: "GET",
url: "#(Url.Action("GetStatesByCountryId", "Country"))",
data: "countryId=" ,
success: function (data) {
ddlStates.html('');
$.each(data, function(id, option) {
ddlStates.append($('<option></option>').val(option.id).html(option.name));//Append all states to state dropdown through returned result
});
statesProgress.hide();
},
error:function (xhr, ajaxOptions, thrownError){
alert('Failed to retrieve states.');
statesProgress.hide();
}
});
});
});
</script>
Controller:
public ActionResult GetStatesByCountryId(string countryId)
{
// This action method gets called via an ajax request
if (String.IsNullOrEmpty(countryId))
throw new ArgumentNullException("countryId");
var country = GetCountryById(Convert.ToInt32(countryId));
var states = country != null ? GetStatesByConutryId(country.Id).ToList() : new List<StateProvince>();//Get all states by countryid
var result = (from s in states
select new { id = s.Id, name = s.Name }).ToList();
return Json(result, JsonRequestBehavior.AllowGet);
}
Try this,
<script type="text/javascript">
$(document).ready(function () {
$("#Country").change(function () {
var Id = $("#Country").val();
$.ajax({
url: '#Url.Action("GetCustomerNameWithId", "Test")',
type: "Post",
data: { Country: Id },
success: function (listItems) {
var STSelectBox = jQuery('#state');
STSelectBox.empty();
if (listItems.length > 0) {
for (var i = 0; i < listItems.length; i++) {
if (i == 0) {
STSelectBox.append('<option value="' + i + '">--Select--</option>');
}
STSelectBox.append('<option value="' + listItems[i].Value + '">' + listItems[i].Text + '</option>');
}
}
else {
for (var i = 0; i < listItems.length; i++) {
STSelectBox.append('<option value="' + listItems[i].Value + '">' + listItems[i].Text + '</option>');
}
}
}
});
});
});
</script>
View
#Html.DropDownList("Country", (SelectList)ViewBag.country, "--Select--")
#Html.DropDownList("state", new SelectList(Enumerable.Empty<SelectListItem>(), "Value", "Text"), "-- Select --")
Controller
public JsonResult GetCustomerNameWithId(string Country)
{
int _Country = 0;
int.TryParse(Country, out _Country);
var listItems = GetCustomerNameId(_Country).Select(s => new SelectListItem { Value = s.CountryID.ToString(), Text = s.CountryName }).ToList<SelectListItem>();
return Json(listItems, JsonRequestBehavior.AllowGet);
}

How can i define a variable in Json?

i want define a variable in Json callback.
Code;
$("select").change(function () {
var $variable = "";
$("select option:selected").each(function () {
$variable += $(this).text() + " ";
});
$("div.yaz").text($variable);
$('#result').html('loading...');
$.getJSON('program-bilgileri.php', function(JSON){
$('#result').empty();
$.each(JSON.$variable, function(i, program){
$('#result')
.append(program.isim +'<br />')
.append(program.bilgi+'<br />')
.append(program.adres+'<hr />');
});
});
})
.trigger('change');
program-bilgileri.php returns;
{
"programlar":[
{
"isim":"Zone Alarm",
"bilgi":"bilgisayarın güvenliğini sağlar",
"adres":"www.zonealarm.com"
},
{
"isim":"Opera",
"bilgi":"güvenli ve hızlı bir web tarayıcısıdır",
"adres":"www.opera.com"
},
{
"isim":"Photoshop",
"bilgi":"güçlü bir imaj işleme yazılımıdır",
"adres":"www.adobe.com"
}
]
}
The problem is here "$.each(JSON.$variable, function(i, program)" if I define $variable in JSON it isn't working.
Any idea?
The problems i see are
Inside the change event you are using $("select option:selected") which finds all select elements in the page, and not the changed one only.
use $(this).children('option:selected') instead.
I am assuming that you are allowing multiple selection on the select element and that is why you are doing += with the $variable.. (you are also adding a space at the end). That means, though, that the variable will be something like "programlar " or "programlar somethingelse".
Your returned JSON though has a key of programlar. A single word, no spaces.. so when you do JSON[$variable] which is the correct way to access an element based on the name in a variable, it does not match.
If the <select> element does not allow multiple selection then the solution is
$("select").change(function() {
var $variable = $(this).children("option:selected").text();
$("div.yaz").text( $variable );
$('#result').html('loading...');
$.getJSON('program-bilgileri.php', function(JSON) {
$('#result').empty();
$.each(JSON[$variable], function(i, program) {
$('#result')
.append(program.isim + '<br />')
.append(program.bilgi + '<br />')
.append(program.adres + '<hr />');
});
});
}).trigger('change');
If indeed it is a multiselect and each option can appear in the JSON then you must check for each option found in the variable.
$("select").change(function() {
var $variable = $(this).children("option:selected").map(function(){
return $(this).text();
}).get();
$("div.yaz").text( $variable.join(' ') );
$('#result').html('loading...');
$.getJSON('program-bilgileri.php', function(JSON) {
$('#result').empty();
for (index=0, length = $variable.length; index < length; index ++) {
$.each(JSON[$variable[index]], function(i, program) {
$('#result')
.append(program.isim + '<br />')
.append(program.bilgi + '<br />')
.append(program.adres + '<hr />');
});
}
});
}).trigger('change');
Try
$.each(JSON['programlar'], function(i, program) ... );
This will iterate over this part of your returned JSON object from PHP:
{
"isim":"Zone Alarm",
"bilgi":"bilgisayarın güvenliğini sağlar",
"adres":"www.zonealarm.com"
},
{
"isim":"Opera",
"bilgi":"güvenli ve hızlı bir web tarayıcısıdır",
"adres":"www.opera.com"
},
{
"isim":"Photoshop",
"bilgi":"güçlü bir imaj işleme yazılımıdır",
"adres":"www.adobe.com"
}

.setPostData jqgrid not working

I want to reload jqgrid with new parameters.I'm using .setPostData().Please look at my code below.It always give me error at .setPostData().M I missing something? format?
$('table[id$="'+tabID+'_BBGrid"]').jqGrid({
url:'/Controls/Advertiser/BBControlNew.ascx.ashx?action=getBBData&advertiserID=' + $('#advertiser_id').text() + '&startDate=' + $('input[id$="' + tabID +
'_FromCalBuyBack_CalendarTbx"] ').val() + '&endDate=' + $('input[id$="' + tabID + '_ToCalBuyBack_CalendarTbx"] ').val(),
datatype: 'json',
mtype: 'POST',
height:'100%',
width:'100%',
colNames: result.colNamesData,
colModel: result.colModelData,
//pager: '#RequestLeadspager',
rowNum : 100,
shrinkToFit :false,
...........
function BuyBackGridReload(tabID,NoSelectedValues)
{
$('table[id$="'+tabID+'_BuyBackGrid"]').setPostData({
advertiserID:$('#advertiser_id').text(),
CampaignsDdlSelectedValue: $('select[id$="CampaignDdl"] option:selected').val(),
startDate: $('input[id$="'+tabID+'_FromCalBuyBack_CalendarTbx"] ').val(),
endDate: $('input[id$="'+tabID+'_ToCalBuyBack_CalendarTbx"] ').val(),
NoSelectedValue: NoSelectedValues
}).trigger("reloadGrid");
};
I have search btn.I'm getting values for NoSelectedValues inside that search btn. here is the code for button click.
$('input[id$="'+tabID+'_BuyBackSearchBtn"]').click(function(){
var values = [];
$('div[id$="' + tabID + '_SelectedBuyBackFilterDiv"] .children').each(function (){
$(this).find('option').each(function (){
var attr = $(this).attr('rel');
if (typeof attr == 'undefined' ){
values.push($(this).val());
}
});
});
BuyBackGridReload(tabID,values);
}); //End search click
ERROR:
$("table[id$=\"" + tabID +
"_BuyBackGrid\"]").setPostData({advertiserID:
$("#advertiser_id").text(),
CampaignsDdlSelectedValue:
$("select[id$=\"CampaignDdl\"]
option:selected").val(), startDate:
$("input[id$=\"" + tabID +
"_FromCalBuyBack_CalendarTbx\"]
").val(), endDate: $("input[id$=\"" +
tabID + "_ToCalBuyBack_CalendarTbx\"]
").val(), NoSelectedValue:
NoSelectedValues}) is undefined
I also don't want to pass as a querystring for new parameters.
Any suggestion?
Thanks
A
You don't need to use setPostData to set the postData parameter. You can use setGridParam function instead. See here examples.
I suppose if you will use postData parameter which contain functions you will not need to set any postData parameter at all. The url and postData parameters of jqGrid can look like
url:'/Controls/Advertiser/BBControlNew.ascx.ashx",
postData: {
action: "getBBData"
advertiserID: function() { return $('#advertiser_id').text(); },
startDate: function() { return $('input[id$="' + tabID + '_FromCalBuyBack_CalendarTbx"] ').val(); },
endDate: function() { return $('input[id$="' + tabID + '_ToCalBuyBack_CalendarTbx"] ').val(); },
advertiserID: function() { return $('#advertiser_id').text(); },
CampaignsDdlSelectedValue: function() { return $('select[id$="CampaignDdl"] option:selected').val(); },
startDate: function() { return $('input[id$="'+tabID+'_FromCalBuyBack_CalendarTbx"] ').val(); },
endDate: function() { return $('input[id$="'+tabID+'_ToCalBuyBack_CalendarTbx"] ').val(); },
NoSelectedValue: function() { return NoSelectedValues; }
}
The variables tabID and NoSelectedValues must be defined before. On every grid reloading the function from every postData property will be called and you can read the current values from the corresponding controls.

Resources