how to access dataTable variable outside ajax - javascript

I have this datatable that is created inside a function call. But if I want to create new rows based on event listeners like this, it gives an error that the table variable is undefined, which is understandable because it is inside a function call and not global. So how do I create a workaround for this and add event listeners under $(document).ready() section?
The structure of my JS file is very shabby, but it's intended to be in that way.
$(document).ready(function()
{
var table=null;
$('#button').click(function()
{
callfunction1();
}
callfunction1()
{
$.ajax({
'success': function(response) //response contains the plain table
{
createDatatable(response)
}
})
}
createDatatable(response)
{
$('#division').html(response); //creating the plain table
table=$('#tableId').Datatable({}); //converting it to datatable
}
//I want to add event listeners here, because if I add
//it anywhere else, it doesn't work, because basically
//it's a function call.
}

You can create a instance of the table var in a wider scope, example:
//the table is now a window object variable window.table
var table = null;
$(document).ready(function()
{
$('#button').click(function()
{
callfunction1();
}
callfunction1()
{
$.ajax({
'success': createDatatable()
})
}
createDatatable()
{
table=$('#tableId').Datatable({})
}
//the table is binded in the window scope so you can use in your event listeners
}

The following should work if you choose one var table declaration and delete the other
var table; //accessible everywhere
$(document).ready(function()
{
var table; //accessible anywhere in this function
$('#button').click(function() {
callfunction1();
}); //); were missing
function callfunction1 ()
{
$.ajax({
'success': createDatatable //no () here, you want to pass a function, not the result of a function call
});
}
function createDatatable()
{
table=$('#tableId').Datatable({});
}
}
This should give no errors, but i'm not sure if this is what you want to do.

So after all your answers(which I am very grateful for) , I have found out a different approach for it. As per documentation here, I added a $.ajax({}_.done() (this is as good as accessing the dataTable variable outside ajax call) function to host my event listener for accessing my dataTable.
Once again, I thank you all for the answers.
Edit: As requested for the correct solution.
$(document).ready(function()
{
var table=null;
$('#button').click(function()
{
callfunction1();
}
callfunction1()
{
$.ajax({
'success': function(response) //response contains the plain table
{
createDatatable(response)
}
}).done(function()
{
//add event listener here,You can access the table variable here. but you can not access the variable outside, instead just pass the variable to another function.
console.log(table);//this will work.
});
}
createDatatable(response)
{
$('#division').html(response); //creating the plain table
table=$('#tableId').Datatable({}); //converting it to datatable
}
}

Related

Accessing a JS variable from a different <script> block

I need to access a js variable declared in one block of a html page into another block of the same html page just so I can stop a ajax call that is being made, but I don't know how can I access a variable that was declared into another block. I can't merge the two blocks, everything else is on the table.
<script>
$(function() {
var term = new Terminal('#input-line .cmdline', '#container output');
term.init();
});
</script>
<script>
term.ajaxHandler.abort();//but how can I access the variable term from the block above,this will be inside a button later
</script>
Thanks in advance
The way your code example is described, it's not possible to reuse that variable. Because it is not bound to the window object, it's bound to the function that is self-executed. It's an example of a "safe" way of libraries not intervening with your own code.
You can however, since I guess by the syntax it's jQuery, hook into the jQuery ajax handling. Based on your requirements, to stop an ajax call, you need to listen to all ajax requests.
You could take a look at the jQuery ajax hooks, https://api.jquery.com/category/ajax/.
You could end up with something like:
$(document).ajaxSend(function(event, xhr, settings){
if (settings.url === "/your/url/to/abort") {
xhr.abort();
}
});
just declare var term above the function declaration
var term
function test1(){
term = 'hello there'
test2()
}
function test2(){
console.log(term)
}
test1()
ok, I managed to solve, basically I created a function only to abort the ajax request like this:
this.abortAjax = () => {
requestHandler.abort();
}
and then accessing it within terminal.js itself using the term object that was instantiated beforehand. After working around the code I was able to keep everything inside the terminal script and not splitted in the two parts, getting something like this:
function ShowLoadingScreen () {
var customElement = $("<div>", {
"class" : "btn btn-danger btn-lg",
"text" : "Abort",
"onclick": "term.abortAjax()"
});
$.LoadingOverlay("show", {
//image : "/static/loading.gif",
background : "rgba(204, 187, 0, 0.8)",
imageAnimation : "rotate_right",
//imageAutoResize : true,
text : "Loading...",
custom : customElement
});
}
function request (command) {
...
requestHandler = $.ajax({
url: _url,
beforeSend: function () { ShowLoadingScreen(); }, // <Show OverLay
type: 'GET',
dataType: 'json',
success: function (response) {
...
},
complete: function () { HideLoadingScreen(); } //<Hide Overlay
}).fail(function (jqXHR, textStatus, error) {
...
});
ShowLoadingScreen();
}
Thanks, everyone.

whacky closures and ajax questions

I'm super confused by my code. Let me show what it looks like:
$(document).ready(function ($) {
var customer_exists = false;
$.get(window.additional_parameters.customer_exists_url, "json")
.done(function () {
customer_exists = true;
})
.always(function () {
// Don't make request to buy clickable until we know if the customer exists
$('#request-to-buy').on('click', function(e) {
request_to_buy(customer_exists);
});
});
function request_to_buy(customer_exists) {
response = can_request_to_buy();
response.done(function (response) {
if (customer_exists) {
// Actually create the request on the server
$.post(window.additional_parameters.request_to_buy_url,
{'ticket_id': window.additional_parameters.ticket_id},
"json")
.done(function (response) {
request_to_buy_success(response);
})
.fail(function () {
var message = handle_ajax_response(response);
show_ajax_message(message);
});
} else {
show_pre_stripe_popup();
}
})
.fail(function (response) {
var error_message = handle_ajax_response(response);
show_ajax_message(error_message, 'danger');
});
}
$(document).ready(), we set a variable called customer_exists. This variable guides the path of the code afterwards and is pretty important. If the $.get AJAX request is successful, it's true, otherwise it remains it default value of false. After the AJAX response, we attach a click event to "#request-to-buy." My goal here is to create a closure and pass in the value of customer_exists that was just set. This doesn't happen.
A good portion of the time ( I had it work correctly once or twice ), when I inspect request_to_buy in the debugger, I can see that customer_exists is a jQuery click event. why ??? Shouldn't it take on the value of the customer_exists from the surrounding scope of where the function was created? Can anyone explain what is going on here?
Thank you
EDIT: Here's a little more information that describes how it works sometimes...
The first time that I click '#request-to-buy', the handler is
function(e) {
request_to_buy(customer_exists);
}
This is what we would expect. e contains the click event, customer_exists retains it's value, and everything works inside request_to_buy.
Every time I click '#request-to-buy' after the first, instead of the above function being called, request_to_buy is called directly, and instead of passing in customer_exists in the first parameter, the click event is passed in instead. I hope this helps someone.
You should be able to do this without the need for the cumbersome outer var customer_exists.
For example :
$(document).ready(function ($) {
$.get(window.additional_parameters.customer_exists_url, "json").then(function () {
// Don't make request to buy clickable until we know if the customer exists
$('#request-to-buy').on('click', request_to_buy);
}, function() {
$('#request-to-buy').on('click', show_pre_stripe_popup);
});
function request_to_buy(e) {
e.preventDefault();
can_request_to_buy().then(function(response) {
// Actually create the request on the server
$.post(window.additional_parameters.request_to_buy_url, {
'ticket_id': window.additional_parameters.ticket_id
}, "json").then(request_to_buy_success, function() {
show_ajax_message(handle_ajax_response(response));
});
}).fail(function(response) {
show_ajax_message(handle_ajax_response(response), 'danger');
});
}
}
show_pre_stripe_popup will also be passed an event and you may need to do e.preventDefault(); there too.
You will need to check that the correct parameters are passed to the various error handlers. I can't verify them.
If it still doesn't work, then you must suspect other code that's not included in the question, for example the function can_request_to_buy().
var customer_exists = false;
Declare this outside of ready block.

Why a JavaScript function with some specific name is not working while others are?

A very interesting problem I am facing these days is regarding one of my JavaScript function. My JavaScript function with some specific name is not working but if I change its name to anything else then it is working. Have a look -
// function to retain the jquery ui css for toolbar
function retain_css() {
alert('hi');
$( "#new_sort_options" ).buttonset();
}
// new sort
$(document).on("click", ".new_sort_button", function() {
var order = $(this).val();
var make_id = $('#new_make_id').val();
$.ajax({
beforeSend : start_loader(),
type : 'POST',
url : '/ajax/new-sort.php',
data : 'order='+order+'&make_id='+make_id,
dataType : 'json',
success : function(data) {
$("#new_results_toolbar").html(data.toolbar);
$("#new_results").html(data.models);
retain_css();
end_loader();
}
});
});
But retain_css() is not working at all. Even alert() is not firing. But if i change its name to anything such as my_fun() then the code works. I don't understand why it is happening so? Any idea? Don't worry about end_loader() function as it has nothing to deal with my problem. I also changed the order of code when retain_css() was being used but didn't work.
Try not to create global functions because it may collide with other frameworks or libraries.
//define private namespace
window.user3779493Functions = {};
//define method
user3779493Functions.retain_css = function() { ... }
//call method
user3779493Functions.retain_css();
Some functions are already programmed like 'alert('hi');', that is a function called alert:
function alert() {
/* do something */
}
That function also doesn't work.

trouble updating multiple anchors aysc with jquery

So i have all these links in html like this
Gen Invoice
Gen Invoice
Gen Invoice
then i wrote some javascript which binds to the click event
and i want it to submit an ajax request, and replace the anchor with the returned text.
but if i have clicked on multiple links so that several are running asychronously, then it doesn't update all the anchors with the returned text, only the last anchor i clicked on.
i am guessing that the anchor variable is being overwritten each time it is run, how would i structure my code so that each time the click event is triggered, it updates the correct anchor on completion?
here is the javascript
<script type="text/javascript">
$(document).ready(function() {
// bind geninvoice function to all invlink's
$('.invlink').bind('click', geninvoice);
});
function geninvoice() {
// stop double clicks
anchor = $(this);
anchor.unbind('click');
competition_id = $(this).attr('competition_id');
$.ajax({
type: "POST",
url: "<?php echo url::site('manage/ajax/geninvoice'); ?>/"+competition_id,
dataType: "json",
beforeSend: function() {
anchor.addClass("loading");
},
success: function(response, textStatus) {
anchor.replaceWith(response.invoice_number);
},
error: function(response) {
alert("Unknown Error Occurred");
anchor.bind('click', geninvoice); // rebind if error occurs
},
complete: function() {
anchor.removeClass("loading");
}
});
}
</script>
Yeah, the problem is that your anchor variable as it is written being 'hoisted' to a global scope. See this jsfiddle for a simplified example.
You can fix this, by putting a var in front of the variable, so its scope will be limited to the function:
function geninvoice() {
// stop double clicks
var anchor = $(this); //<-- put a var here
You can see the fix at this updated version of the above fiddle
Note, this will only help you for scoping within functions. The x variable in the following example will be hoisted to the top of the global scope even though it has been declared with a var:
var a = 1;
var b = 1;
if (a === b){
var x = 0;
}
alert(x); //alerts '0'
the advantages of scoping within functions is on of the reasons we often see the following convention around jQuery plugins:
(function($){
//plugin code
//all variables local to the invoked anonymous function
})(jQuery);
See at this JSFiddle

jQuery: Referencing the calling object(this) when the bind/click event is for a class

Thanks for reading this.
I am dynamically generating some data which includes a select drop-down with a text box next to it. If the user clicks the select, I am dynamically populating it (code below). I have a class on the select and I was hoping the following code would work. I tested it with an ID on the select and putting the ONE on the ID I got it to work. However, in changing the code to reference a class (since there will be multiple data groups that include a select with a text box next to it) and $(this), I could not get it to work. Any ideas would be helpful. Thanks
The relevance of the text box next to the select is the second part of the code...to update the text box when an option is selected in the select
.one is so the select is updated only once, then the .bind allows any options selected to be placed in the adjacent text box.
$('.classSelect').one("click",
function() {
$.ajax({
type: "post",
url: myURL ,
dataType: "text",
data: {
'_service' : myService,
'_program' : myProgram ,
'param' : myParams
},
success:
function(request) {
$(this).html(request); // populate select box
} // End success
}); // End ajax method
$(this).bind("click",
function() {
$(this).next().val($(this).val());
}); // End BIND
}); // End One
<select id="mySelect" class="classSelect"></select>
<input type="text">
$(this) is only relevant within the scope of the function. outside of the function though, it loses that reference:
$('.classSelect').one("click", function() {
$(this); // refers to $('.classSelect')
$.ajax({
// content
$(this); // does not refer to $('.classSelect')
});
});
a better way to handle this may be:
$('.classSelect').one("click", function() {
var e = $(this);
$.ajax({
...
success : function(request) {
e.html(request);
}
}); // end ajax
$(this).bind('click', function() {
// bind stuff
}); // end bind
}); // end one
by the way, are you familiar with the load() method? i find it easier for basic ajax (as it acts on the wrapped set, instead of it being a standalone function like $.ajax(). here's how i would rewrite this using load():
$('.classSelect').one('click', function() {
var options = {
type : 'post',
dataType : 'text',
data : {
'_service' : myService,
'_program' : myProgram ,
'param' : myParams
}
} // end options
// load() will automatically load your .classSelect with the results
$(this).load(myUrl, options);
$(this).click(function() {
// etc...
}); // end click
}); // end one
I believe that this is because the function attached to the success event doesn't know what 'this' is as it is run independently of the object you're calling it within. (I'm not explaining it very well, but I think it's to do with closures.)
I think if you added the following line before the $.ajax call:
var _this = this;
and then in the success function used that variable:
success:
function(request) {
_this.html(request); // populate select box
}
it may well work
That is matching one select. You need to match multiple elements so you want
$("select[class='classSelect']") ...
The success() function does not know about this, as any other event callback (they are run outside the object scope).
You need to close the variable in the scope of the success function, but what you really need is not "this", but $(this)
So:
var that = $(this);
... some code ...
success: function(request) {
that.html(request)
}
Thanks Owen. Although there may be a better to write the code (with chaining)....my problem with this code was $(this) was not available in the .ajax and .bind calls..so storing it in a var and using that var was the solution.
Thanks again.
$('.classSelect').one("click",
function() {
var e = $(this) ;
$.ajax({
type: "post",
url: myURL ,
dataType: "text",
data: {
'_service' : myService,
'_program' : myProgram ,
'param' : myParams
},
success:
function(request) {
$(e).html(request); // populate select box
} // End success
}); // End ajax method
$(e).one("click",
function() {
$(e).next().val($(e).val());
}); // End BIND
}); // End One

Categories