Not able to set javascript variable back to null after defining it - javascript

I want to set the variable selectedColumnIndex back to null after using it each time.
I need to be able to check that a new selectedColumnIndex value has been set after each use. It could be used once or dozens of times in a row (it's for "cut and insert" functionality in a table-style UI component).
If I put a browser breakpoint at the variable var check, selectedColumnIndex will show as null. But then if $(document).on('click', '.columnUpdatesInsert', function () { } runs again without $(document).on('click', '.columnUpdates', function () { } ever running, selectedColumnIndex will be back to the previous value.
var selectedColumnIndex = null;
$(document).on('click', '.columnUpdates', function () {
selectedColumnIndex = $(this).attr("data-columnindex");
});
$(document).on('click', '.columnUpdatesInsert', function () {
if (selectedColumnIndex != null) {
// get variables from click element etc.
$(updateColumnPosition(tableId, selectedColumnIndex, newColumnIndex));
}
else {
alert("No column was selected to move.");
}
});
function updateColumnPosition(tableId, selectedColumnIndex, newColumnIndex) {
$.ajax({
type: "POST",
url: "/Task/UpdateColumnIndex",
data: { projectId: _projectId, tableId: tableId, selectedColumnIndex: selectedColumnIndex, newColumnIndex: newColumnIndex },
dataType: 'json',
success: function (data) {
if (data.success) {
// do other unrelated work
selectedColumnIndex = null; // this successfully sets it to null, but it is getting set back to the previous value before this code is explicitly setting it again.
var check = 0;
}
else {
// handle error
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status + " " + thrownError);
},
});
}

Probably because you are passing selectedColumnIndex as an arg to the function it becomes a local to that function.
Try not passing the value selectedColumnIndex as arg and use it as global all the time.
var selectedColumnIndex = null;
$(document).on('click', '.columnUpdates', function () {
selectedColumnIndex = $(this).attr("data-columnindex");
});
$(document).on('click', '.columnUpdatesInsert', function () {
if (selectedColumnIndex != null) {
// get variables from click element etc.
$(updateColumnPosition(tableId, newColumnIndex));
}
else {
alert("No column was selected to move.");
}
});
function updateColumnPosition(tableId, newColumnIndex) {
$.ajax({
type: "POST",
url: "/Task/UpdateColumnIndex",
data: { projectId: _projectId, tableId: tableId, selectedColumnIndex: selectedColumnIndex, newColumnIndex: newColumnIndex },
dataType: 'json',
success: function (data) {
if (data.success) {
// do other unrelated work
selectedColumnIndex = null; // this successfully sets it to null, but it is getting set back to the previous value before this code is explicitly setting it again.
var check = 0;
}
else {
// handle error
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status + " " + thrownError);
},
});
}

Related

chrome.storage.local.get not working

Here i'm using to store the multiple value[below is the code]
Here DocName is the Name of the PDF and Base64File is the base64 string of the pdf
var obj = { DocName: res.Value.DocumentName, Base64File: res.Value.Base64File };
chrome.storage.local.set({ 'MyFile': obj });
In next page i'm retriving like this
$(document).on('click', '.sendToPdf', function(){
chrome.storage.local.get('MyFile', function (result) {
var PdfBase64 = result.MyFile.Base64File;
var DocumentName = result.MyFile.DocName;
var arr=new Array();
var item={"CategoryID": 11,"DocumentNumber": "22022018053567","Base64FileData": PdfBase64,"DocumentName": DocumentName,
"OptionalParam1": "sample string 5"};
arr.push(item);
$.ajax({
type: "POST",
url: Documentupload,
headers: {
'Authorization': headerdata,
'Content-Type':'application/json'
},
data:JSON.stringify(arr),
dataType: 'json',
success: function (res) {
if (res.IsSuccess) {
setTimeout(function () {
$("#divLoading").hide();
}, 2000);
//$("#divLoading").hide();
$(".modal-iframe1").attr("src", window.emSigner.OnlineSignUrl + res.Response[0].DocumentID + "&AuthToken=" + AuthToken);
//window.location.reload();
}else{
alert(res.Messages);
window.location.href='/PdfLogin.html';
}
},
error: function (error) {
//alert("Error while communicating to the server");
alert(error.responseText);
window.location.href='/PdfLogin.html';
}
});
});
});
[check this image .sendToPdf(button)]
Question is, if i click the button first time on any icon, the values are retriving correctly, but in second time if i click other than 1st icon i'm getting the values as the before one? it is accepting the previous values only?
How to resolve this,
Help me to come out of this problem.

How to override the jQuery.ajax success function after it has been initialized?

A button click triggers an ajax request. When the user clicks the button a second time while the first request is still loading, i want to override the first request's success function with another one.
Basically I want to do this:
var ajaxRequest = null;
jQuery('#mybutton').click(function () {
if (ajaxRequest) {
ajaxRequest.success = function () {
};
}
ajaxRequest = jQuery.ajax({
url: '...',
success: function () {
console.debug('do something');
}
});
});
But the initial success handler is been called.
How to achieve an override?
You can try the following hack, I have tested it with asynch setTimeout (instead of asynch jQuery.ajax) and it works -
var mySuccessHander = function() {
console.debug('Initial function');
}
var test = jQuery.ajax({
url: '...',
success: function() {
mySuccessHander();
}
});
And when the button is clicked for the second time, execute following -
mySuccessHander = function() {
console.debug('Overridden function');
}
Nice question , this will work..
var isRequestDone = true;
jQuery('#mybutton').click(function () {
var requestParams = {
url: '....',
beforeSend: function () {
isRequestDone = false;
},
success: function () {
isRequestDone = true;
console.debug('do something');
},
error: function () {
isRequestDone = true;
}
}
if (!isRequestDone) {
requestParams.success = function () {
console.log('please wait for a while!');
};
}
jQuery.ajax(requestParams);
});
beforeSend will fire just before the request will go to server , so when request in on the server isRequestDone will be false and hence will change success handler . on success callback from the first request it will again back to original.
You can set the ajax arguments to a variable first so you can modify it later on.
var clicks = 0,
ajaxArgs = {
url: '...',
success: function () {
console.debug('do something');
}
};
$('#myButton').click(function() {
++clicks;
if (clicks > 1) {
// set the success function if clicked more than once
ajaxArgs.success = function () {
console.debug('Success function ' + clicks);
}
}
$.ajax(ajaxArgs);
});
If you want to modify the success function only when ajax is still loading you can do this:
var loading = false,
ajaxArgs = {
url: '...',
success: function () {
console.debug('do something');
}, complete: function () {
loading = false;
}
};
$('#myButton').click(function() {
if (loading) {
// set the success function if ajax is still loading
ajaxArgs.success = function () {
console.debug('Another Success function ');
}
} else {
loading = true;
$.ajax(ajaxArgs);
}
});

query clearInterval when variable is "x"

I have made a function that is controlling a row in a my database for a certain number with AJAX.
Im calling the function with a click function and putting the function in a setInterval function to make the check 10 times a second.
In the beginning it will return 0, but at some point (usually within 5 seconds) it will return something els than 0, when it does i want to clearInterval.
But im not sure how to this?
This is my function:
function get_buzzer() {
$.ajax({
url: 'ajax_buzzer.php',
dataType: 'json',
async: false,
type: 'post',
data: {
job: 'get'
},
success:function(s) {
if(s['number'] == 0) {
var player = false;
} else {
var player = true;
}
}, error:function(e) {
}
});
}
$(document).ready(function() {
$('#test').click(function() {
var buzzer = setInterval("get_buzzer()",100);
});
});
You can do something like
$(document).ready(function () {
//make buzzer a share variable
var buzzer;
$('#test').click(function () {
buzzer = setInterval(get_buzzer, 100);
});
function get_buzzer() {
$.ajax({
url: 'ajax_buzzer.php',
dataType: 'json',
async: false,
type: 'post',
data: {
job: 'get'
},
success: function (s) {
if (s['number'] != 0) {
//if number is not 0 then clear the interval
clearInterval(buzzer)
}
},
error: function (e) {}
});
}
});
Try this : declare global variable to store interval and call window.clearInterval in success call of ajax
var buzzer;
function get_buzzer() {
$.ajax({
url: 'ajax_buzzer.php',
dataType: 'json',
async: false,
type: 'post',
data: {
job: 'get'
},
success:function(s) {
if(s['number'] == 0) {
var player = false;
} else {
var player = true;
//clear interval
window.clearInterval(buzzer);
}
}, error:function(e) {
}
});
}
$(document).ready(function() {
$('#test').click(function() {
buzzer = setInterval("get_buzzer()",100);
});
});
Use:
inside success use: And make var buzzer Gloval var.
clearInterval(buzzer);
Refence
You just need to clear the interval in the success handler of ajax call over a condition.
success: function (s) {
if (s['number'] != 0) {
//if number is not 0 then clear the interval
clearInterval(buzzer)
}
},
error: function (e) {}

How I can get value from jsonp response and set that value too other variable in other function?

How I can get variable value from jsonp response and use it in other script function?
In first function I have one value that I am getting from jsonp response. I am assigning this value to variable ( var userId ) in first function.
How I can get userId value and use it in second script function???
<script>
$(document).on('pageinit', '#login', function () {
$(document).on('click', '#submit', function () {
if ($('#username').val().length > 0 && $('#password').val().length > 0) {
console.log($('#check-user').serialize());
$.ajax({
url: 'http://localhost/check.php',
data: $('#check-user').serialize(),
type: 'POST',
beforeSend: function () {
$.mobile.showPageLoadingMsg(true);
},
complete: function () {
$.mobile.hidePageLoadingMsg();
},
success: function (result, status, err) {
if(result.login){
$.mobile.changePage( "#output", { transition: "slideup", changeHash: false });
var userID = //// HERE I NEED TO GET USER ID FROM jsonp response!!!!
});
}
else{
alert("An error occurred: " + status + "nError: " + err.status);
}
},
error: function (request, error) {
}
});
} else {
alert('Please fill all necessary fields');
}
event.preventDefault();
});
var output = $('#output');
var userid = ////HERE I NEED TO SET USER ID!!!!!!!!!!!!
$.ajax({
url: 'http://localhost/data.php?user='+userid,
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
var landmark = '<h1>'+item.name+'</h1>'
+ '<p>'+item.lat+'<br>'
+ item.long+'</p>';
output.append(landmark);
});
},
error: function(){
output.text('There was an error loading the data.');
}
});
});
</script>
you can use the global variable assignment feature of js
Declare your variable outside of any function.
<script>
var userId;
function foo(){
//..
}
</script>
OR Use the window object to assign the global variable from inside a function
<script>
function foo() {
window.userID = ...;
}
</script>
more info available here

Javascript OOP inheritance not working

So I am writing something using augment for inheritance and for some reason I can run this.setButtons(type) and console.log(this.buttons) in that method, but when I run my this.getButtons() it comes back as undefined, even though getButtons just returns this.buttons. Any help would be greately appreciated. I will post up all the code I have so far, because maybe I'm not inheriting properly. Thank you in advance.
var ContextMixin = function () {};
ContextMixin.prototype = {
createElements: function (el, mode, type) {
var m;
if (mode == 'exact') {
$("#" + el).append("<ul id='contextmenu'>");
} else {
$(el).each(function () {
m = $(this).append("<ul id='contextmenu'>");
});
$('body').append(m);
}
$("#contextmenu").css({
'position': 'absolute',
top: 13,
left: 13
});
var new_buttons = this.getButtons();
$.each(this.buttons['buttons'], function () {
m.append("<li id='" + this + "'>" + this + "</li>");
});
},
attachEvents: function () {
functions = this.getFunctions(type);
buttons = this.getButtons();
for (index in buttons['buttons']) {
addEvent(buttons['buttons'][index], this.functions[index][0], this.functions[index][1]);
};
},
setFunctions: function (type) {
var callback = {
success: function (msg) {
this.functions = msg;
},
failure: function () {
alert('Error getting functions')
}
};
$.ajax({
type: 'GET',
url: 'function_list.php?type=' + type,
success: function (msg) {
this.functions = msg;
}
});
},
getFunctions: function () {
return this.functions;
},
setType: function (value) {
this.type = value;
},
getType: function () {
return this.type;
},
setButtons: function (type) {
$.ajax({
type: 'GET',
url: 'button_list.php?type=' + type,
success: function (reply) {
this.buttons = reply;
}
});
},
getButtons: function () {
return this.buttons;
}
}
function createMenu(el, type, mode) {
this.setButtons(type);
this.setFunctions(type);
this.createElements(el, mode, type);
}
augment(createMenu, ContextMixin);
function augment(receivingClass, givingClass) {
if (arguments[2]) { //Only give certain methods.
for (var i = 2, len = arguments.length; i < len; i++) {
receivingClass.prototype[arguments[i]] = givingClass.prototype[arguments[i]];
}
} else { //Give all methods
for (methodName in givingClass.prototype) {
if (!receivingClass.prototype[methodName]) {
receivingClass.prototype[methodName] = givingClass.prototype[methodName];
}
}
}
}
Because this in the callback to the AJAX request is not your object.
Here's a common fix...
setButtons: function(type) {
var self = this; // keep a reference to this
$.ajax({
type: 'GET',
url: 'button_list.php?type=' + type,
success: function(reply) {
self.buttons = reply; // use the reference here
}
});
},
...but a better fix is to use the context: property of the $.ajax request...
setButtons: function(type) {
$.ajax({
type: 'GET',
context: this, // set the context of the callback functions
url: 'button_list.php?type=' + type,
success: function(reply) {
this.buttons = reply;
}
});
},
If you change
ContextMixin.prototype = {
createElements
to
ContextMixin.prototype.createElements
it should work.
this is not what you think it is in your ajax callback—instead of being your current object, it's actually the global object the XHR object. All your callback is doing is putting a buttons property onto the xhr object.
You need to save this before your function runs:
setButtons: function(type) {
var self = this;
$.ajax({
type: 'GET',
url: 'button_list.php?type=' + type,
success: function(reply) {
alert(reply);
self.buttons = reply;
}
});
},

Categories