JQuery code not working in IE 8 - asp.net

This code is working in firefox but on IE 8 it returns nothing
<script type="text/javascript">
$(document).ready(function(){
var pageUrl = '<%=ResolveUrl("~/test/test.aspx")%>';
// Test
$('#<%=ddlTest.ClientID%>').change(function(){
var trgId = $(this+'input:checked').val();
$.ajax({
type: "POST",
url : pageUrl+ '/getRecs',
data : '{categ: "' +trgId + '"}',
contentType:"application/json; charset=utf-8",
dataType:"json",
success:function(msg)
{
bindCategories(msg)
}
});
});
});
$('#divLoad').ajaxStart(function() {
$(this).show();
});
$('#divLoad').ajaxStop(function() {
$(this).hide();
});
function bindCategories(msg)
{
if(msg.hasOwnProperty("d"))
alert(msg.d);
else
{
$('select[id$=<%=ddlTrg.ClientID %>] > option').remove();
$.each(msg, function() {
$('#<%=ddlTrg.ClientID %>').append($('<option></option>').val(this['Id']).html(this['Name']));
});
}
}
</script>`

This line doesn't look right?
var trgId = $(this+'input:checked').val();
this is an html element so you can't just use it like you are.
Do you mean something like:
var trgId = $('#' + this.id).val();
or
var trgId = $(this).find('input:checked').val();

Related

Sometimes $(this) is not working with AJAX success code

I am using Wordpress AJAX for showing some results.
The function is working very well but while showing the result $(this) is not working.
My code is below:
<script type="text/javascript">
jQuery(document).ready(function () {
$("a.review_status").live("click", function () {
var id = $(this).attr("id");
dataString = 'id=' + id;
jQuery.ajax({
type: "POST",
url: "<?php echo $ajax_status_url; ?>",
data: dataString,
cache: false,
success: function (html) {
$(this).text(html);
}
});
});
});
</script>
In that AJAX is not give me proper result.
There's a change in context in the callback inside the ajax success. The reference to this inside the success funtion points to the success function itself and not to the element that was clicked on.
A way around this is to store a reference to this as self. For example:
<script type="text/javascript">
jQuery(document).ready(function () {
$("a.review_status").live("click", function () {
var self = this;
var id = $(this).attr("id");
dataString = 'id=' + id;
jQuery.ajax({
type: "POST",
url: "<?php echo $ajax_status_url; ?>",
data: dataString,
cache: false,
success: function (html) {
$(self).text(html);
}
});
});
});
</script>
Use this code instead of above code:
<script type="text/javascript">
jQuery(document).ready(function () {
$("a.review_status").live("click", function () {
var element = $(this);
var id = $(this).attr("id");
dataString = 'id=' + id;
jQuery.ajax({
type: "POST",
url: "<?php echo $ajax_status_url; ?>",
data: dataString,
cache: false,
success: function (html) {
$(element).text(html);
}
});
});
});
</script>
Try jQuery instead of $
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery("a.review_status").live("click", function () {
var element = jQuery(this);
var id = jQuery(this).attr("id");
dataString = 'id=' + id;
jQuery.ajax({
type: "POST",
url: "<?php echo $ajax_status_url; ?>",
data: dataString,
cache: false,
success: function (html) {
jQuery(element).text(html);
}
});
});
});
</script>

Autocomplete Web Service in ASP.Net web forms

I have a web service for multiple item selection, its working fine but i am getting Undefined data. anyone can tell me solution for it. I am attaching my error screenshot too with this post, please see them below.
Web Service JSON Code
<script type="text/javascript">
$(document).ready(function () {
SearchText();
});
function SearchText() {
$("[id*=ctl00_ContentMain_TextBoxSkills]").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '<%=ResolveUrl("WebServiceSkills.asmx/GetAutoCompleteData")%>',
data: "{'skill':'" + extractLast(request.term) + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("No Result Found");
}
});
},
focus: function () {
// prevent value inserted on focus
return false;
},
select: function (event, ui) {
var terms = split(this.value);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join(", ");
return false;
}
});
$("#ctl00_ContentMain_TextBoxSkills").bind("keydown", function (event) {
if (event.keyCode === $.ui.keyCode.TAB &&
$(this).data("autocomplete").menu.active) {
event.preventDefault();
}
})
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
}
</script>
Web Service:
[WebMethod]
public List<UserRegistration> GetAutoCompleteData(string skill)
{
List<UserRegistration> list = new List<UserRegistration>();
UserRegistrationHelper userRegistrationHelper = new UserRegistrationHelper();
using (DataTable dataTable = userRegistrationHelper.GetSkillsList(skill))
{
if (CommonFunctions.ValidateDataTable(dataTable))
{
foreach (DataRow dr in dataTable.Rows)
{
var SkillsList = new UserRegistration
{
SkillId = Convert.ToInt32(dr["SkillId"].ToString()),
Skills=dr["SkillName"].ToString()
};
list.Add(SkillsList);
}
}
}
return list;
}
Screenshot here:
I got answer for it:
1: Change SQL Query:
select concat('[', STUFF
(
(
SELECT top 15 '","'+ CAST(skillname AS VARCHAR(MAX))
from DNH_Master_Skills where SkillName LIKE '%' + #SkillName + '%'
FOR XMl PATH('')
),1,2,''
),'"]')
2: Change JSON Code:
From: response(data.d); TO: response(Array.parse(data.d));
Now its working feeling happy.

Why is async causing issues in my javascript?

Can anyone tell me why async: false; doesn't allow my spinner to display during data load?
But when I used async: true; it reverses my default display toggle?
I currently have list set up with 5 different items. 3 of those items are set up to display by default when the page loads. Then they can be clicked off or the other 2 items can be clicked on. When I use async: true; to get my spinner to display, its like it doesn't recognize the default toggles. Even though they are selected on page load, the information does not display. It only displays after they are UNselected.
$(function () {
var HistoryViewModel;
var xspinner = new Spinner();
$.ajax({
url: '/Users/GetAccountHistory',
type: 'POST',
async: false,
cache: false,
data: { accountId: #Model.Account.AccountID },
beforeSend: function () {
xspinner.showSpinner("Getting History Information...");
},
complete: function () {
xspinner.hide();
},
success: function (data) {
HistoryViewModel = new RCM.ViewModels.History.HistoryViewModel(ko.mapping.fromJS(data));
ko.applyBindings(HistoryViewModel, document.getElementById('ListPanel'));
ko.applyBindings(HistoryViewModel, document.getElementById("DetailsPanel"));
ie9HeightFix();
},
error: function (xhr, textStatus, errorThrown) {
notify.show({ type: 'error', header: 'Error!', content: 'Error fetching History, ' + xhr.statusText });
return false;
}
});
function ie9HeightFix() {
if(document.addEventListener && !window.requestAnimationFrame)
{
var eTop = $('.AccountHx').offset().top; //get the offset top of the element
var dTop = eTop - $(window).scrollTop(); //position of the ele w.r.t window
var cHeight = $(window).height() - dTop - $(".colophon").height();
$(".AccountHx").css("height", cHeight);
$(".AccountHx").css("position", "relative");
$(".AccountHx").css("overflow-x", "hidden");
$(".AccountHx-detailsPanel").css("left", "32rem");
$(".viewDetailsButton").css("right", "2rem");
}
}
$(window).resize(function() {
ie9HeightFix();
});
$("#vToggle").click();
$("#pToggle").click();
$("#sToggle").click();
$(".search-button").click(function(event){
$(".subHeader").toggleClass("search-visible");
$(".AccountHx-items").toggleClass("search-visible");
$(".search-button").toggleClass("search-visible");
});
$(".filter-button, .modal-close").click(function(event){
$(".AccountHx-filtersPanel").toggleClass("filters-visible");
$(".filter-birdBeak").toggle();
});
$(".filterButtons input").attr("disabled", false);
});
$("#vToggle").click(function(){
$(".js-vItem").toggle();
$("#vToggle").toggleClass("is-active");
});
$("#cToggle").click(function(){
$(".js-claimItem").toggle();
$("#cToggle").toggleClass("is-active");
});
$("#nToggle").click(function(){
$(".js-nItem").toggle();
$("#nToggle").toggleClass("is-active");
});
$("#sToggle").click(function(){
$(".js-sItem").toggle();
$("#sToggle").toggleClass("is-active");
});
$("#pToggle").click(function(){
$(".js-pItem").toggle();
$("#pToggle").toggleClass("is-active");
});
$("li.filterButton").click(function(){
$(this).parent().siblings(".clearButton").show();
$(".AccountHx-filtersPanel .clearButton--all").css('display', 'inline-block');
});
$(".clearButton").click(function(){
var hiddenOption = $(this).siblings(".filterButtons").children(".hiddenOption");
hiddenOption.siblings('.is-active').removeClass('is-active');
hiddenOption.toggleClass("is-active");
$(this).hide();
});
$(".AccountHx-filtersPanel .clearButton--all").click(function() {
$(".AccountHx-filtersPanel .filterButton").removeClass("is-active");
$(".AccountHx-filtersPanel .hiddenOption").toggleClass("is-active");
$(".AccountHx-filtersPanel .filterCheckbox").attr('checked', false);
$(".AccountHx-filtersPanel .clearButton").hide();
$(this).hide();
})
The answer that I discovered is to move the
$("#visitToggle").click();
$("#paymentToggle").click();
$("#statementToggle").click();
inside the following section
success: function (data) {...}
and change async to true

How to get city from coordinates?

I use google maps api 3 to get city from coordinates.
I read the ReverseGeocoding but I did not understand how to have the correct city value from this type of result:
http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=false
this Funktion returns the Name of a requested City at lat/long. As this Script is from end of 2012. Worked fine for me that time. Returns "unknown" when the API doesn't find any.
function get_api ($lat, $long) {
$get_API = "http://maps.googleapis.com/maps/api/geocode/json?latlng=";
$get_API .= round($lat,2).",";
$get_API .= round($long,2);
$jsonfile = file_get_contents($get_API.'&sensor=false');
$jsonarray = json_decode($jsonfile);
if (isset($jsonarray->results[1]->address_components[1]->long_name)) {
return($jsonarray->results[1]->address_components[1]->long_name);
}
else {
return('Unknown');
}
}
edit: and a jquery.
<p id="city"></p>
<script>
$(document).ready( function () {
// define lat / long
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>
In HTML5 page we can get city name as follows:
<script src="//maps.googleapis.com/maps/api/js?v=3.exp&sensor=true"></script>
<script>
(function() {
if(!!navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var geocoder = new google.maps.Geocoder();
var geolocate = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
console.log(position.coords.latitude + ', ' + position.coords.longitude);
geocoder.geocode({'latLng': geolocate}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var result;
if (results.length > 1) {
result = results[1];
} else {
result = results[0];
}
//console.log(result);
console.log(result.address_components[2].long_name + ', ' + result.address_components[3].long_name);
}
});
});
</script>

Jquery AutoComplete Load Problem

Not Work
Jquery Code:
$('[id$=Name]').autocomplete('CallBack.aspx',{formatItem: function(item){return item.Name;}}).result(function(event, item) {
location.href = item.AGE;
});
Json:
var data = [{NAME:"John",AGE:"57"}];
Work
Jquery Code:
var data = [{NAME:"John",AGE:"57"}];
$('[id$=Name]').autocomplete(data,{formatItem: function(item){return item.Name;}}).result(function(event, item) {
location.href = item.AGE;
});
alt text http://img11.imageshack.us/img11/119/38235621.jpg
Help me pls how its make ? callback.aspx return json not work
Try changing your data to this:
var data = [{id:"John",value:"57"}];
EDIT
Here's a sample of what I think you're trying to do:
var data = [{NAME:"John",AGE:"57"}];
$('[id$=Name]').autocomplete('CallBack.aspx', {
formatItem: function(item) {
return item.NAME;
}}).result(function(event, item) {
location.href = 'somepage.aspx?age=' + item.AGE;
});
Basically you needed to capitalise return item.Name to return item.NAME.
Try This
<script type="text/javascript">
$(document).ready(function () {
$("#TextboxId").autocomplete({
source: function (request, response) {
$.ajax({
url: "URL",
type: "POST",
dataType: "json",
data: { ids: idstopass },
success: function (retrieveddata) {
alert(retrieveddata);
var dData = JSON.parse(retrieveddata);
alert(dData.Name);
},
error: function (request, status, error) {
console.log("Error! " + request.responseText);
}
})
},
});
})
</script>

Resources