IE11 ajax call not working - javascript

When I am calling requestwidgets function under document.ready it is successfully getting called and call to handler is made.
But when the same function i am calling from some function it is not getting called
Note: This is only happening in IE11 browser
Below is the code
function CreateNewWidget() {
$elementName = $("#ux_widget_name").val();
$elementType = $("#ux_widget_type_dll").val();
$url = '?request=newelement&elementtype=' + $elementType + '&appguid=' + appguid + '&elementname=' + $elementName;
$.get($url, function (data) {
if (data == "True") {
RequestWidgets();
}
setTimeout("$.fn.slickBox.close()", 3000);
});
}
var elements = Array();
function RequestWidgets() {
$.get('/shared/test2.ashx?request=getelements&appguid=' + appguid, function (data) {
xmlDoc = $.parseXML(data);
elements = Array();
RenderElements(elements);
});
}

Related

How can i use same private variable in 2 functions

So im having 2 functions. Problem is in styep_id variable. I know that i can just declare it in second functions, but then he wont take out data from first function. So the question is how i can use the same variable without lost data on him
P.S It shouldn't be public variable, cos it wont work. It wont hold the data.
function delete_estimate_position_type() {
var estpt_tr_jqobj, estpt_action_links_td_jqobj, styep_id, authenticity_token, request_url, stya_id;
styep_id = $(this).attr("styep_id");
// Ja ir tikko kā pievienots, tad tikai izmetīsim ārā no DOM
if (!styep_id == "") {
estpt_action_links_td_jqobj = $(this).parent();
estpt_tr_jqobj = estpt_action_links_td_jqobj.parent();
stya_id = $("td.service-type-est-position-estimate-position-type-name>input.stya-id-for-styep", estpt_tr_jqobj).val();
estpt_tr_jqobj.remove();
show_stya_delete_link_if_possible(stya_id);
remove_estpgt_if_has_no_estpt($(this).attr("estpgt_id"));
}
}
And
function save_configuration(){
var estpt_for_estpgt = "";
// Pārbaudam vai visām tāmes pozīciju grupām ir norādītas tāmes pozīcijas
$('.estpt-for-estpgt').each(function(){
if ($(this).find('tr.action_record_tr').size() == 0){
estpt_for_estpgt = this;
return false;
}
})
if (estpt_for_estpgt == "") {
var form = $(this).closest('form');
form.submit();
// Dzēsīsim ārā no datu bāzes
authenticity_token = $("#authenticity_token").val();
request_url = "/service_type_est_positions/" + styep_id + "/destroy_from_service_type_config";
$.post(request_url, { authenticity_token: authenticity_token}, process_service_type_est_position_delete, "json");
} else {
$.alerts.okButton = 'Labi';
jError("Vismaz vienai Tāmes pozīciju grupai nav norādīta neviena Tāmes pozīcija!", "Kļūda");
}
return false;
}
function remove_estpgt_if_has_no_estpt(estpgt_id) {
// Paskatīsimies vai eksistē kāda tāmes pozīcija
if ($("#estpt_for_" + estpgt_id + ">tr:first").size() == 0) {
$("#estpgt_" + estpgt_id).remove();
$("#estpt_tr_for_" + estpgt_id).remove();
}
}
call your second function within the first and pass the variable as an argument:
function delete_estimate_position_type() {
save_configuration(styep_id)
}
function save_configuration(id){
request_url = "/service_type_est_positions/" + id + "/destroy_from_service_type_config";
}
You can use like this
function delete_estimate_position_type() {
var estpt_tr_jqobj, estpt_action_links_td_jqobj, styep_id, authenticity_token, request_url, stya_id;
styep_id = $(this).attr("styep_id");
// your other code goes here.....
// Your variable pass as argument
remove_estpgt_if_has_no_estpt($(this).attr("estpgt_id"),styep_id.val() );
}
}
// Get it from argument.
function remove_estpgt_if_has_no_estpt(estpgt_id,styep_id ) {
// Paskatīsimies vai eksistē kāda tāmes pozīcija
if ($("#estpt_for_" + estpgt_id + ">tr:first").size() == 0) {
$("#estpgt_" + estpgt_id).remove();
$("#estpt_tr_for_" + estpgt_id).remove();
}
}
Another option is set it in hidden field.
// html
<input type = "hidden" id="styep_id_newval" value="">
// End of html
function delete_estimate_position_type() {
var estpt_tr_jqobj, estpt_action_links_td_jqobj, styep_id, authenticity_token, request_url, stya_id;
styep_id = $(this).attr("styep_id");
// your other code goes here.....
$("#styep_id_newval").(styep_id.val());
// Your variable pass as argument
remove_estpgt_if_has_no_estpt($(this).attr("estpgt_id"),styep_id.val() );
}
}
Now you can easily access code using anywhere.
$("styep_id_newval").val();

Stop form from redirecting?

This question has been asked and answered quite a few different times. I've searched around SO and couldn't find a solution that worked. I tried e.preventdefault() and return false. Neither worked. Then I saw that I need to go back to AJAX and can't use a promise and I refuse to do so and I refuse to think that there isn't a way to do it with promises.
Anyway,
Code:
var submitDataForm = function () {
console.log("button called");
var email = document.getElementById('email');
var first = document.getElementById('first-name');
var last = document.getElementById('last-name');
var web = document.getElementById('domain');
var city = document.getElementById('city');
var obj = document.getElementById('obj');
var describe = document.getElementById('describe');
var brandpower = document.getElementById('brandpower');
if (email.checkValidity() && first.checkValidity() && web.checkValidity() && city.checkValidity() && obj.checkValidity()) {
var emailV = email.value;
var firstV = first.value;
var webV = (web.value == undefined) ? 'null' : web.value;
var cityV = city.value;
var objV = obj.options[obj.selectedIndex].value;
var describeV = (describe && describe.options && describe.selectedIndex) ? describe.options[describe.selectedIndex].value : describe.value;
var brandpowerV = (brandpower && brandpower.options && brandpower.selectedIndex) ? brandpower.options[brandpower.selectedIndex].value : brandpower.value;
var radio = jQuery('input[name="dealer"]:checked').val();
jQuery.post("/form-one/?" + "email=" + emailV + "&first=" + firstV +
cityV + "&domain=" + webV + "&obj=" + objV + "&describe=" + describeV + "&brandpower=" + brandpowerV +
"&radio=" + radio, function () {
console.log("data sent");
})
.done(function () {
console.log("data success");
})
.fail(function () {
console.log("data failed");
})
.always(function () {
console.log("data finished");
email.value, first.value, web.value, city.value, obj.value, describe.value, brandpower.value = "";
//window.location.href = "/";
});
} else {
$('#error').css('display', 'block').delay(5000).queue(function (next) {
jQuery('#error').fadeOut('slow').css('display', 'none');
});
}
}
<button id="next" class="green-button" onClick="submitDataForm()">Next</button>
Again, I'm trying to have the form do nothing but submit data (will add custom events later) without refresh or reload.
Thank you!
event.preventDefault does indeed work. As nnnnnn pointed out, you dont show where you tried it but I suspect that you were not using it correctly, more than likely, you were not passing the event into the handler and e or event (whatever you named it) was actually undefined. Here is an example of one way to use it properly:
$('.ajax-submit').click(function(event) {
event.preventDefault();
console.log("button called");
//... all your other code here
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="">
<button id="next" class="green-button ajax-submit" > Next</button>
</form>

Javascript 'onbeforeunload()' not working with a function call

I have this script below which is used in a survey. The problem I have is, onbeforeunload() works when I don't call a function inside it. If I make any function call(save_survey() or fetch_demographics()) inside it, the browser or the tab closes without any prompt.
<script type="text/javascript">
$(document).ready(function() {
$('#select_message').hide();
startTime = new Date().getTime();
});
loc = 0;
block_size = {{ block_size }};
sid = {{ sid }};
survey = {{ survey|tojson }};
survey_choices = '';
startTime = 0;
demographics_content = {};
function save_survey(sf)
{
var timeSpentMilliseconds = new Date().getTime() - startTime;
var t = timeSpentMilliseconds / 1000 / 60;
var surveydat = '';
if(sf==1)
{ //Success
surveydat = 'sid='+sid+'&dem='+JSON.stringify(demographics_content)+'&loc='+loc+'&t='+t+'&survey_choice='+JSON.stringify(survey_choices);
}
if(sf==0)
{ //Fail
surveydat = 'sid='+sid+'&dem='+json_encode(demographics_content)+'&loc='+loc+'&t='+t+'&survey_choice='+json_encode(survey_choices);
}
//Survey Save Call
$.ajax({
type: 'POST',
url: '/save_surveyresponse/'+sf,
data: surveydat,
beforeSend:function(){
// this is where we append a loading image
$('#survey_holder').html('<div class="loading"><img src="/static/img/loading.gif" alt="Loading..." /></div>');
},
success:function(data){
// successful request; do something with the data
$('#ajax-panel').empty();
$('#survey_holder').html('Success');
alert("Dev Alert: All surveys are over! Saving data now...");
window.location.replace('http://localhost:5000/surveys/thankyou');
},
error:function(){
// failed request; give feedback to user
$('#survey_holder').html('<p class="error"><strong>Oops!</strong> Try that again in a few moments.</p>');
}
});
}
function verify_captcha()
{
// alert($('#g-recaptcha-response').html());
}
function block_by_block()
{
var div_content ='<table border="0" cellspacing="10" class="table-condensed"><tr>';
var ii=0;
var block = survey[loc];
var temp_array = block.split("::");
if(loc>=1)
{
var radio_val = $('input[name=block_child'+(loc-1)+']:checked', '#listform').val();
//console.log(radio_val);
if(radio_val!=undefined)
survey_choices += radio_val +'\t';
else
{
alert("Please select one of the choices");
loc--;
return false;
}
}
for(ii=0;ii<block_size;ii++)
{
//Chop the strings and change the div content
div_content+="<td>" + temp_array[ii]+"</td>";
div_content+="<td>" + ' <label class="btn btn-default"><input type="radio" id = "block_child'+loc+'" name="block_child'+loc+'" value="'+temp_array[ii]+'"></label></td>';
div_content+="</tr><tr>";
}
div_content+='<tr><td><input type="button" class="btn" value="Next" onClick="survey_handle()"></td><td>';
div_content+='<input type="button" class="btn" value="Quit" onClick="quit_survey()"></td></tr>';
div_content+="</table></br>";
$("#survey_holder").html(div_content);
//return Success;
}
function updateProgress()
{
var progress = (loc/survey.length)*100;
$('.progress-bar').css('width', progress+'%').attr('aria-valuenow', progress);
$("#active-bar").html(Math.ceil(progress));
}
function survey_handle()
{
if(loc==0)
{
verify_captcha();
$("#message").hide();
//Save the participant data and start showing survey
fetch_demographics();
block_by_block();
updateProgress();
$('#select_message').show();
}
else if(loc<survey.length)
{
block_by_block();
updateProgress();
}
else if(loc == survey.length)
{
//Save your data and show final page
$('#select_message').hide();
survey_choices += $('input[name=block_child'+(loc-1)+']:checked', '#listform').val()+'\t';
//alert(survey_choices);
//Great way to call AJAX
save_survey(1);
}
loc++;
return false;
}
</script>
<script type="text/javascript">
window.onbeforeunload = function() {
var timeSpentMilliseconds = new Date().getTime() - startTime;
var t = timeSpentMilliseconds / 1000 / 60;
//fetch_demographics();
save_survey(0);
return "You have spent "+Math.ceil(t)+ " minute/s on the survey!";
//!!delete last inserted element if not quit
}
</script>
I have checked whether those functions have any problem but they work fine when I call them from different part of the code. Later, I thought it might be because of unreachable function scope but its not the case. I have tried moving the onbeforeunload() at the end of script and the problem still persists. Wondering why this is happening, can anyone enlighten me?
I identified where the problem was. I am using json_encode instead of JSON.stringify and hence it is crashing(which I found and changed already in sf=1 case). That tip with debugger is invaluable. Also, its working fine even without async: false.
Thank you again #AdrianoRepetti!

Multiple Parameter passing in setTimeOut function throws Uncaught ReferenceError: method is not defined (anonymous function)?

I have a function A() which calls function B(x, y); which again calls C(p,q);
A() --> B(x,y) -->C (p,q)
function A() {
B(x,y)
}
B() Processes JSONStore to extract data relevant for function C, Before JSONStore data extraction ends script makes a call for func C(p,q) so to avoid it I used setTimeOut with a 1 second delay.
function B(x,y) {
if(p===undefined || q===undefined) {
setTimeout(function() {
C(p,q);
}, 1000);
}
}
But I am getting error as Uncaught ReferenceError: method is not defined M979:192 C VM979:192 (anonymous function)
function C(p,q) {
.........
}
I have read many blogs related to setTimeOut and discovered this way to do it.
My code:
function Submit_Data() {
var ChatWindow_Height = 650;
var ChatWindow_Width = 570;
window.open("Live Chat", "chat", "height=" + ChatWindow_Height + ", width = " + ChatWindow_Width);
post("https://xyz/abc/StartChat.aspx", "post");
}
var regUserName,regUserMobile;
function post(path, method) {
method = method || "post"; // Set method to post by default if not specified.
var collectionName = 'Registration';
var JSONStoreCollections = {};
JSONStoreCollections[collectionName] = {};
JSONStoreCollections[collectionName].searchFields = {uName: 'string'};
WL.JSONStore.init(JSONStoreCollections)
.then(function () {
WL.JSONStore.get(collectionName).findAll().then(function (res) {
WL.Logger.info('Registration retrived is :', res);
console.log(JSON.stringify(res));
console.log(res[0].json.userName+" "+res[0].json.userMobile+" "+res[0].json.userPass+" "+res[0].json.userRePass);
regUserName=res[0].json.userName;
regUserMobile=res[0].json.userPass;
console.log("For Chat Data 1 is "+regUserName+" "+regUserMobile);
})
.fail(function (err) {
WL.Logger.error("Failed authentication "+err);
});
})
.fail(function (err) {
alert("Error is "+err);
});
if(regUserName===undefined || regUserMobile===undefined) {
setTimeout(function() {
openChat(regUserName,regUserName); // Error Here
}, 1000);
}
}
function openChat(regUserName,regUserName) {
// The rest of this code assumes you are not using a library.
// It can be made less wordy if you use one.
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
form.setAttribute("target", "chat");
var hiddenField1 = document.createElement("input");
var hiddenField2 = document.createElement("input");
var hiddenField3 = document.createElement("input");
console.log("For Chat Data 3 is "+regUserName+" "+regUserMobile);
hiddenField1.setAttribute("type", "hidden");
hiddenField1.setAttribute("id", "vName");
hiddenField1.setAttribute("name", "vName");
hiddenField1.setAttribute("value", regUserName);
hiddenField2.setAttribute("type", "hidden");
hiddenField2.setAttribute("id", "mobile");
hiddenField2.setAttribute("name", "21512");
hiddenField2.setAttribute("value", regUserMobile);
hiddenField3.setAttribute("type", "hidden");
hiddenField3.setAttribute("id", "state");
hiddenField3.setAttribute("name", "21524");
hiddenField3.setAttribute("value", "25");
document.body.appendChild(form);
form.submit();
}
These lines are illogically placed:
if(regUserName===undefined || regUserMobile===undefined) {
setTimeout(function() {
openChat(regUserName,regUserName); // Error Here
}, 1000);
}
Just call openChat in the JSONStore.get() callback:
regUserMobile=res[0].json.userPass;
console.log("For Chat Data 1 is "+regUserName+" "+regUserMobile);
if(regUserName===undefined || regUserMobile===undefined) {
openChat(regUserName,regUserName);
}
})
You also might want to replace === with !===, there. I would imagine that was intended to be a check to see if the parameters are filled.
I tried your code and i got the same error as you has mentioned, i have tweeked the code and now its working with this code just modify the URL link as per what you want.
function Submit_Data()
{
var ChatWindow_Height = 650;
var ChatWindow_Width = 570;
window.open("VodaFone Live Chat", "chat", "height=" + ChatWindow_Height + ", width = " + ChatWindow_Width);
post("https://xyz/abc/StartChat.aspx", "post");
}
var regUserName,regUserMobile;
function post(path, method) {
method = method || "post"; // Set method to post by default if not specified.
// The rest of this code assumes you are not using a library.
// It can be made less wordy if you use one.
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
form.setAttribute("target", "chat");
var hiddenField1 = document.createElement("input");
var hiddenField2 = document.createElement("input");
var hiddenField3 = document.createElement("input");
var collectionName = 'Registration';
var JSONStoreCollections = {};
JSONStoreCollections[collectionName] = {};
JSONStoreCollections[collectionName].searchFields = {uName: 'string'};
WL.JSONStore.init(JSONStoreCollections)
.then(function ()
{
WL.JSONStore.get(collectionName).findAll().then(function (res)
{
WL.Logger.info('Registration retrived is :', res);
console.log(JSON.stringify(res));
console.log(res[0].json.userName+" "+res[0].json.userMobile+" "+res[0].json.userPass+" "+res[0].json.userRePass);
regUserName=res[0].json.userName;
regUserMobile=res[0].json.userMobile;
hiddenField1.setAttribute("type", "hidden");
hiddenField1.setAttribute("id", "vName");
hiddenField1.setAttribute("name", "vName");
hiddenField1.setAttribute("value", regUserName);
hiddenField2.setAttribute("type", "hidden");
hiddenField2.setAttribute("id", "mobile");
hiddenField2.setAttribute("name", "21512");
hiddenField2.setAttribute("value", regUserMobile);
hiddenField3.setAttribute("type", "hidden");
hiddenField3.setAttribute("id", "state");
hiddenField3.setAttribute("name", "21524");
hiddenField3.setAttribute("value", "25");
console.log("For Chat Data 1 is "+regUserName+" "+regUserMobile);
})
.fail(function (err)
{
WL.Logger.error("Failed authentication "+err);
});
})
.fail(function (err)
{
alert("Error is "+err);
});
if(regUserName===undefined || regUserMobile===undefined)
{
setTimeout(function() {
form.appendChild(hiddenField1);
form.appendChild(hiddenField2);
form.appendChild(hiddenField3);
document.body.appendChild(form);
form.submit();
}, 1000);
}
}
I know this is different way and probably not advicable but that is how i fixed it.
I tired this piece and its working correctly:
function A() {
B(1, 2)
}
function B(x,y) {
if(true) {
setTimeout(function() {
C(3,4);
}, 1000);
}
}
function C(p,q) {
alert('in c')
}
A()

"Object Expected" error while capturing the page load event

The following code inside the tags gives error: "Object Expected".
<!-- JQuery/AJAX-->
<script type="text/javascript">
try {
$(document).ready(function(){
$("p").load(function(){
MakeRequest('divElectionCategory','ulElectionCategory','SELECT * FROM electioncategorymaster', 'UnOrderedList');
});
});
}
catch(e)
{
alert(e.message);
}
</script>
The MakeRequest function resides in a separate .js file and I have included that file before the above given code.
Which object it is referring to?
Edited:
The MakeRequest function
function MakeRequest(DivName, ControlName, SqlQuery, ControlType)
{
var xmlHttp = getXMLHttp();
var strUrl = "";
if (ControlType = 'DropDown')
strUrl = "../phplibraries/filldropdown.php?DivName=" + DivName + "&DropDownControlName=" + ControlName + "&SqlQuery=" + SqlQuery;
else
strUrl = "../phplibraries/createelectioncategorymenu.php?DivName=" + DivName + "&ulName=" + ControlName + "&SqlQuery=" + SqlQuery;
alert(strUrl);
try
{
xmlHttp.onreadystatechange = function()
{
if (xmlHttp.readyState == 4)
{
HandleResponse(xmlHttp.responseText, DivName);
}
}
xmlHttp.open("GET", strUrl, true);
xmlHttp.send(null);
}
catch(err)
{
alert(err);
}
}
I know there is a big security issue above but please ignore it at this point of time.
You cannot call load() that way.
The first parameter of load takes a URL not a function. Perhaps you meant this:
$("p").load( MakeRequest('divElectionCategory','ulElectionCategory','SELECT * FROM electioncategorymaster', 'UnOrderedList') );
That assumes that MakeRequest returns a formatted URL.
EDIT
.load() when used against a DOM element and the first parameter is a function, jQuery assumes you are attaching an event handler. However, p does not have a load event. If you want to wait for everything to load, try this (It doesn't have to be in DOM ready):
$(window).load( function(){
MakeRequest('divElectionCategory','ulElectionCategory','SELECT * FROM electioncategorymaster', 'UnOrderedList')
});
MakeRequest rewrite
function MakeRequest(DivName, ControlName, SqlQuery, ControlType)
{
var strUrl = "", params = {};
if (ControlType = 'DropDown'){
strUrl = "../phplibraries/filldropdown.php";
params = {
DivName: DivName,
DropDownControlName: ControlName,
SqlQuery: SqlQuery
}
} else {
strUrl = "../phplibraries/createelectioncategorymenu.php";
params = {
DivName: DivName,
ulName: ControlName,
SqlQuery: SqlQuery
}
}
alert(strUrl);
$.get(strUrl, params, function(data){
HandleResponse(data, DivName);
});
}

Categories

Resources