I've got a web app using ASP.NET with C# code behind using JQuery 11.1.2. I have a dropdownlist that is populated by an AJAX call to the server when it is clicked. The web method returns a list of options to include in the dropdown based on args. Some of the options return a 'confirm' appended to the end of the option, which my success function splits out of it and I use it on my front end to decide whether or not the option requires confirmation once selected. All good.
My problem occurs when the confirm dialog comes up, it crashes IE 11 no matter the chosen option. It works fine in Chrome and Firefox, but crashes every time in IE. My only thought is that IE doesn't like that this is all done in an AJAX success function? Not sure. Any ideas would be greatly appreciated! Thank you.
$('.lazy-load').click(function (e, k) {
if (e.currentTarget.length < 2) {
var callerId = getTarget(e);
callerId = callerId.id;
// parse out the true encrypted id
var encIdIndex = callerId.indexOf('ddlAction') + 9;
var encId = callerId.substring(encIdIndex);
if (encId == '' || encId == null)
return;
// get the valid workflow options for this clientice
$.ajax({
type: 'POST',
url: 'LandingSummary.aspx/GetWorkflowOptions',
async: false,
data: "{ 'csId': '{0}'}".format(encId),
success: function (data) {
ddlId = 'ddlAction' + encId;
$$(ddlId).get(0).options.length = 0; // clear
$$(ddlId).get(0).options[0] = new Option("Choose...", '');
$.each(data.d, function(index, item) {
if (item.Value.indexOf('CONFIRM') != -1) {
//strip text
var newText = item.Value.slice(0, 0 - 'CONFIRM'.length);
// add confirm attribute
var option = new Option(newText, item.Key);
option.setAttribute('data-confirm', 'confirm');
$$(ddlId).get(0).options[$$(ddlId).get(0).options.length] = option;
}
else {
$$(ddlId).get(0).options[$$(ddlId).get(0).options.length] = new Option(item.Value, item.Key);
}
});
var fullId = $$(ddlId)[0].id;
ExpandSelect(fullId);
// add warning hookup
$$(ddlId).change(function () {
var confirmAttribute = $$(ddlId).find('option:selected').attr('data-confirm');
//debugger;
if (confirmAttribute != undefined) {
var newState = $$(ddlId).find('option:selected').text();
var sure = confirm('Are you sure you want to move this authorization to the {0} state?'.format(newState));
if (!sure) {
$$(ddlId).val('');
return false;
}
}
});
},
error: function (result) {
alert('error retrieving workflow options');
}
});
}
return false;
})
function getTarget(obj) {
var targ;
var e = obj;
if (e.target != undefined) targ = e.target;
else if (e.srcElement != undefined) targ = e.srcElement;
if (targ.nodeType == 3) // defeat Safari bug
targ = targ.parentNode;
return targ;
}
});
Problem signature:
Problem Event Name: APPCRASH
Application Name: IEXPLORE.EXE
Application Version: 11.0.9600.17631
Application Timestamp: 54b31a70
Fault Module Name: MSHTML.dll
Fault Module Version: 11.0.9600.17631
Fault Module Timestamp: 54b33039
Exception Code: c0000005
Exception Offset: 0008d910
OS Version: 6.1.7601.2.1.0.256.48
Locale ID: 1033
Additional Information 1: 0a9e
Additional Information 2: 0a9e372d3b4ad19135b953a78882e789
Additional Information 3: 0a9e
Additional Information 4: 0a9e372d3b4ad19135b953a78882e789
Related
Trying to create a jade version to do autofill city state from
https://www.zipcodeapi.com/Examples
script(type='text/javascript').
//<![CDATA[
$(function() {
// IMPORTANT: Fill in your client key
console.log("thing")
var clientKey = "js-9qZHzu2Flc59Eq5rx10JdKERovBlJp3TQ3ApyC4TOa3tA8U7aVRnFwf41RpLgtE7";
var cache = {};
var container = $("#example1");
var errorDiv = container.find("div.text-error");
/** Handle successful response */
function handleResp(data)
{
// Check for error
if (data.error_msg)
errorDiv.text(data.error_msg);
else if ("city" in data)
{
// Set city and state
container.find("input[name='city']").val(data.city);
console.log(data.city);
container.find("input[name='state']").val(data.state);
}
}
// Set up event handlers
container.find("input[name='zipcode']").on("keyup change", function() {
// Get zip code
var zipcode = $(this).val().substring(0, 5);
if (zipcode.length == 5 && /^[0-9]+$/.test(zipcode))
{
// Clear error
errorDiv.empty();
// Check cache
if (zipcode in cache)
{
handleResp(cache[zipcode]);
}
else
{
//Build url
var url = "https://www.zipcodeapi.com/rest/"+clientKey+"/info.json/" + zipcode + "/radians";
// Make AJAX request
$.ajax({
"url": url,
"dataType": "json"
}).done(function(data) {
handleResp(data);
// Store in cache
cache[zipcode] = data;
}).fail(function(data) {
if (data.responseText && (json = $.parseJSON(data.responseText)))
{
// Store in cache
cache[zipcode] = json;
// Check for error
if (json.error_msg)
errorDiv.text(json.error_msg);
}
else
errorDiv.text('Request failed.');
});
}
}
}).trigger("change");
});
//]]>
div#example1
label Zip:
input(type='text', name='zipcode', value='')
label City:
input(type='text', name='city', value='')
label State:
input(type='text', name='state', value='')
I am getting the following error and not sure why this is erroring out:
$ is not defined
Any ideas? This is a conversion from the original javascript so I am not sure what I am doing wrong in the conversion. Thanks!
Always listen to your error messages; they're usually right. $ isn't defined. Have you included jQuery (just guessing) in a higher-level template, of which this is a subtemplate? If not, $ is undefined is a valid message from the javascript interpreter.
I have this particular problem, where I need to validate the data before it is saved via an ajax call. save_ass_rub function is called when user navigates to a different URL.
In my application, I have a custom Window and user is allowed to input data. I am able to capture all the data in this step: var data = $('form').serialize(true);. But I need to loop through this and check if data for some specific elements is empty or not. I can't do it when the user is in the custom window. The Custom window is optional for the user. All I want is to alert the user in case he has left the elements blank before the data is submitted.
We are using Prototype.js and ajax .
<script>
function save_ass_rub() {
var url = 'xxxx';
var data = $('form').serialize(true);
var result;
new Ajax.Request( url, {
method: 'post',
parameters: data,
asynchronous: false, // suspends JS until request done
onSuccess: function (response) {
var responseText = response.responseText || '';
if (responseText.length > 0) {
result = eval('(' + responseText + ')');
}
}
});
if (result && result.success) {
return;
}
else {
var error = 'Your_changes_could_not_be_saved_period';
if (window.opener) { // ie undocked
//Show alert in the main window
window.opener.alert(error);
return;
}
return error;
}
}
// Set up auto save of rubric when window is closed
Event.observe(window, 'unload', function() {
return save_ass_rub();
});
</script>
Can some thing like this be done?
After Line
var data = $('form').serialize(true);
var split_data = data.split("&");
for (i = 0; i < split_data.length; i++) {
var elem = split_data[i];
var split_elem = elem.split('=');
if( split_elem[0].search(/key/) && split_elem[0] == '' ){
console.log( split_elem );
var error = 'Not all the elements are inputted';
window.opener.alert(error);
return;
}
}
Instead of using the serialized form string, I would use the form itself to do the validation. if $('form') is your form element then create a separate function that checks the form element so its compartmentalized.
function checkform(form)
{
var emptytexts = form.down('input[type="text"]').filter(function(input){
if(input.value.length == 0)
{
return true;
}
});
if(emptytexts.length > 0)
{
return false;
}
return true;
}
and in the save_ass_rub() function
//..snip
if(checkform($('form') == false)
{
var error = 'Not all the elements are inputted';
window.opener.alert(error);
return;
}
var data = $('form').serialize(true);
var result;
I only added text inputs in the checkform() function you can the rest of the input types and any other weird handling you would like to that function. As long as it returns false the error will be displayed and the js will stop otherwise it will continue
I'm running this code:
jQuery.get("http://email.hackmailer.com/checkuser.php?email=".concat(document.getElementById('name').value).concat(document.getElementById('domain').value), function(data) {
if(data == "true") {
document.getElementById('containerThree').style = "background-color:#20bb47;";
}else{
document.getElementById('containerThree').style = "background-color:#b33535;";
}
document.getElementById('avail').style = "color:#272727;";
document.getElementById('emt').style = "color:#272727;";
});
It works fine in FireFox, but in chrome not at all. I've tried using .style.background = "#mycolorcode" but it still doesn't work in chrome(and in that case, firefox too).
Try this:
if (data === 'true') {
document.getElementById('containerThree').style.backgroundColor = '#20bb47';
} else {
document.getElementById('containerThree').style.backgroundColor = '#b33535';
}
http://devdocs.io/html/element/style
http://youmightnotneedjquery.com/
NOTE: 'true' is a string. You would most likely would rather use the Boolean true.
Based on the latest edit to your question, does this cleanup of your surrounding code help?
jQuery.get('http://email.hackmailer.com/checkuser.php?email='
.concat(document.getElementById('name').value)
.concat(document.getElementById('domain').value),
function (data) {
if (data === true) {
document.getElementById('containerThree').style.backgroundColor = '#20bb47';
} else {
document.getElementById('containerThree').style.backgroundColor = '#b33535';
}
document.getElementById('avail').style.color = '#272727';
document.getElementById('emt').style.color = '#272727';
});
You don't need to send a string as 'true' to check a condition. Use it like:
var data = true; //use boolean but not 'true' as string.
Then you can simple use it as follows:
jQuery.get("http://email.hackmailer.com/checkuser.php?email=" + document.getElementById('name').value + document.getElementById('domain').value, function(data) {
var colorValue = "#272727";
document.getElementById('containerThree').style.backgroundColor = data == "true"?"#20bb47":"#b33535";
document.getElementById('avail').style.color = colorValue;
document.getElementById('emt').style.color = colorValue;
});
BTW, I am not sure how .style = "background-color:#20bb47;"; is working for you.
I can't seem to figure out this problem where the below code works when the "for loop" is disabled, and the attributes "locations" and "startAddress" are just simple strings. But if they are not, I am getting a "this is undefined" error when the ajax post request is submitted. Do you have any ideas why would this be? Any leads would be appreciated.
// create an event handler for the save route button
$("#saveRouteButton").click(function(){
var saveRouteName = $("#saveRouteNameField").val();
if (!saveRouteName) {
alert("Please supply a proper name to be submitted to the database");
} else {
var routeLength = directionsDisplay.getDirections().routes[0].legs.length;
var returnRoute = {
alias: null,
locations : [], // make this a string - it works!
startAddresses : [], // make this a string - it works!
};
// disable this loop - it works!
for (var i = 0; i < routeLength; i++){
returnRoute.locations[i] = directionsDisplay.getDirections().routes[0].legs[i].start_location
returnRoute.startAddresses[i] = directionsDisplay.getDirections().routes[0].legs[i].start_address
};
route_info = returnRoute;
route_info.alias = saveRouteName;
//test to see if the variables are set, they are!
alert(route_info.alias);
alert(route_info.locations);
alert($.isPlainObject(route_info))
$.ajax({
url: "save_route/",
type: "POST",
data : route_info,
success: function(data){
if (data != "None") {
$("#savedRoutesList").append('<li class="savedRoutesListItem">'
+ data + '</li>');
}
else {alert("You need to enter a route name");}
}
});
}
return false;
});
the error originates from the : google maps main js - line 13
Thanks!
Just check the route Length value,whether it is giving correct value or not?
I have written a UserScript for Greasemonkey (Firefox) and am testing it for compatibility with Chrome's Tampermonkey, and getting errors in the developer console:
Uncaught TypeError: Cannot read property 'profile_url' of undefined
Uncaught TypeError: Cannot read property 'encoded_name' of undefined
The errors seem to be referencing the onreadystatechanged callback of GM_xmlhttpRequest which is called like this:
var flairs = document.querySelectorAll('span.flair');
var steam_re = /(?:(?:https?:\/\/)?www\.)?(?:steam|pc)(?:community\.com\/?(?:(id|profiles)\/?)?|[\s\-_]*id)?[\/:\s\|]*(.{2,}?)(?:[\/|:\-\[(] ?(?:\/?(?:ghost|enforcer|tech|mm|master))+[\[)]?)?$/i
function get_text(e) { return e.innerText || e.textContent; }
function set_text(e, t) {
if (e.innerText)
e.innerText = t;
else
e.textContent = t;
}
var parser = new DOMParser();
for (var i = 0; i < flairs.length; i++) {
var text = get_text(flairs[i]);
var match = steam_re.exec(text);
if (match == null || match.length < 3)
continue;
var type = match[1] || 'id';
var name = encodeURIComponent(match[2]);
var url = 'http://steamcommunity.com/' + type + '/' + name;
var xml_url = url + '?xml=1';
GM_xmlhttpRequest({
method: 'GET',
url: xml_url, // Link to a steam profile with ?xml=1 added
accept: 'text/xml',
context: {
flair_index: i,
flair_text: text, // textContent of span element
encoded_name: name,
profile_url: url, // Link to steam profile
query_url: xml_url
},
onreadystatechange: function(response) {
if (response.readyState != 4)
return;
// Attempt to fall back to alternate forms of context,
// none of which works. response.context works on Firefox/Greasemonkey.
var context = response.context || this.context || context;
var doc = parser.parseFromString(response.responseText, 'text/xml');
var validProfile = doc.documentElement.nodeName == 'profile';
var a = document.createElement('a');
a.href = validProfile ?
context.profile_url : // TypeError here, context is undefined
('http://steamcommunity.com/actions/SearchFriends?K=' + context.encoded_name);
a.className += (validProfile ? 'steam-profile-link' : 'steam-profile-search-link');
var a_text = document.createTextNode(context.flair_text);
a.appendChild(a_text);
set_text(flairs[context.flair_index], '');
flairs[context.flair_index].appendChild(a);
}
});
}
The function itself is called fine, and the callback is invoked, but once I try to access the context var inside it, it's undefined.
It all works as expected in Firefox. What it does is iterating over span elements that have the "flair" class and checking with a regex if they contain a Steam username, and if so, makes it a link to their SteamCommunity page. (Full source on github). The script runs on /r/PaydayTheHeistOnline.
I have tested using an array defined outside the function to store the data instead of using the context property passed to xmlhttpRequest, but I'm getting the exact same error.
Update:
Tampermonkey now reports that this feature is fixed as of version 3.8.4116 (in beta at the moment). See:
The bug report
The change log
Older/generic workaround:
The context property is a relatively new feature of GM_xmlhttpRequest(), in Firefox. I doubt it's been implemented in Tampermonkey yet; see Tampermonkey's docs for GM_xmlhttpRequest().
Meanwhile, the tried-and-true method for this kind of thing is to use a closure.
Change your GM_xmlhttpRequest() call to something like:
( function (flair_index, flair_text, encoded_name, profile_url, query_url) {
GM_xmlhttpRequest ( {
method: 'GET',
url: xml_url, // Link to a steam profile with ?xml=1 added
accept: 'text/xml',
onreadystatechange: function (response) {
if (response.readyState != 4)
return;
var doc = parser.parseFromString (response.responseText, 'text/xml');
var validProfile = doc.documentElement.nodeName == 'profile';
var a = document.createElement ('a');
a.href = validProfile ?
profile_url :
('http://steamcommunity.com/actions/SearchFriends?K=' + encoded_name);
a.className += (validProfile ? 'steam-profile-link' : 'steam-profile-search-link');
var a_text = document.createTextNode (flair_text);
a.appendChild (a_text);
set_text (flairs[flair_index], '');
flairs[flair_index].appendChild (a);
}
} );
} ) (
i,
text, // textContent of span element
name,
url, // Link to steam profile
xml_url
);