How to insert data in function parameters in javascript? - javascript

I initialize Datatable on the page:
$("#datatable-buttons").DataTable()
The problem is that I need to form a parameters (300 lines of code) for this Datatable, so I make an object:
var myfunctions = {
parametrs: {
ajax: {
type: "POST",
data: data,
.....
},
inittable: function() {
a = $("#datatable-buttons").DataTable(this.parametrs);
}
The problem is that data has to change depending on user input. So I make a function:
var requestdata = function() {
return document.getElementById("daterange").value;
};
I change a data in parameters to this function
ajax: {
type: "POST",
data: requestdata()...
However, when page is first time initialized the function is being called and everything work excellent however when the code calls this function after user's input, it uses the parameters from initial page initialization, not asking it current (changed!!!) value.

It is using initial data because when myfunctions object is created, the parameters object is created with initial data.
var requestdata = function() {
return document.getElementById("daterange").value;
};
var myfunctions = {
parametrs: {
ajax: {
type: "POST",
data: requestdata(), // Pass this data as a function parameter
.....
},
inittable: function() {
a = $("#datatable-buttons").DataTable(this.parametrs);
}
}
Instead of saving the data, pass the data to the function call.

Related

Callback when AJAX calls are done using jQuery when

I am having trouble making the callback work correctly. Here is what I am trying to achieve: I have 2 items that I want to add to cart so I make 2 asynchronous POST requests. Once those two POST requests are complete, then I want to update the partial view of the cart. The issue is that it seems like only 1 item gets added to cart. When I debug it, then 2 of the items gets added. Any suggestion or help would be great. Thanks in advance!
here is my code:
var cart = []
function AddToCart(input) {
return $.ajax({
method: 'POST',
url: '/cart/add.js',
data: input,
dataType: 'json'
})
.done(function(data) {
return data;
});
}
$("#addToCart").click(function() {
$('#capsContainer input:checked').each(function() {
var cartItem = {
id: $(this).val(),
quantity: 1
}
cart.push(cartItem);
});
var test1 = AddToCart(cart[0]);
var test2 = AddToCart(cart[1]);
$.when.apply(test1, test2).done(function() {
$.getJSON('/cart.js', function(data) {
$('.cart-item-count').text(data.item_count);
$('.cart-item-price').html(formatMoney(data.total_price));
ShowCart();
});
})
});
Part of the issue is that your using ajax requests which could occur either before or after the code happens to handle those executions. Since they are async, its possible that they could fire/return before any other code runs on the page depending on how your browser's Javascript parser decides to execute the code. Rather than attempting to use Callbacks on asynchronous ajax requests, you can control the entire interaction by using a small 600 byte library called ajaxq.js
ajaxq.js essentially works just like jQuery's $.post() method, only you can also specify multiple queues by name to execute asyncronously, and attach a callback to them or whatever.
Here's a quick example of how you could setup your Ajax Cart Preview using this library.
/* queue up an AJAX request */
$.postq("set_data", "add_items.php", {"itemID": someItemID, "customerID": customerID },
function(result1) {
/* perform new request at the end of first request */
$.postq("get_data", "get_items.php", { "id": customerID },
function(result2) {
/* add in code to perform at the end of the second ajax POST request */
}); // end of request 2
}); // end of request 1
Here's your example using the ajaxq.js library:
function AddToCart(input) {
$.postq("add_item", "/cart/add/js", input, function(result) {
preview_items();
}, "json");
}
function preview_items() {
$.getJSON('/cart.js', function(data) {
$('.cart-item-count').text(data.item_count);
$('.cart-item-price').html(formatMoney(data.total_price));
ShowCart();
}
$(document).ready(function() {
$("#addToCart").on("click" function() {
$('#capsContainer input:checked').each(function(elem) {
var cartItem = {
id: $(this).val(),
quantity: 1
}
cart.push(cartItem);
});
var test1 = AddToCart(cart[0]);
var test2 = AddToCart(cart[1]);
});
Your AddToCart method already returns a deferred object. You are calling .done method twice.
I guess your code should look like this.
var cart = []
function AddToCart(input) {
return $.ajax({
method: 'POST',
url: '/cart/add.js',
data: input,
dataType: 'json'
});
}
$("#addToCart").click(function() {
$('#capsContainer input:checked').each(function() {
var cartItem = {
id: $(this).val(),
quantity: 1
}
cart.push(cartItem);
});
var test1 = AddToCart(cart[0]);
var test2 = AddToCart(cart[1]);
$.when(test1, test2).done(function() {
$.getJSON('/cart.js', function(data) {
$('.cart-item-count').text(data.item_count);
$('.cart-item-price').html(formatMoney(data.total_price));
ShowCart();
});
})
});

jquery Datatables filter rows

Hi I have a DataTables DataTable object which requests json data via an ajax call. Each object inside the json data has a property called state that can be one of a number of values. Ultimately, I'd like to create several (Data)tables, one for each state without having each table request the same data via ajax again and again. For now, I haven't managed to make a single table filter out the rows with incorrect state yet and I'd like to solve this problem first.
The DataTable object defined as follows:
$(document).ready(function () {
var table = $('#example').DataTable({
data: example,
ajax: {
url: "{{ callback_url }}",
dataType: 'json',
dataSrc: '',
},
createdRow: function (row, data, index) {
},
columns: [{
data: "Type"
}, {
data: "State",
}
}]
});
});
I want to filter the data that comes from the ajax call based on a parameter (e.g. "if (row.State == 'new') {...};"). How can I do that? Does datatables have a function that can be passed to filter each row?
I really need several tables which show data from the same ajax callback but in different states (e.g. a "New" table, an "Old" table etc.). How can I do this without requesting the same json data again and again for each table rendered? Ideally I can store the ajax in a variable but with the async process I'm not sure how this will work out.
You can use one ajax and store the data, and than create each datatable.
Example:
$(document).ready(function () {
var data = null;
$.ajax(URL, {
dataType: 'json',
success: function(ajaxData){
data = ajaxData;
newData = data.filter(function(item){ return item.State == "New"});
oldData = data.filter(function(item){ return item.State == "Old"});
var newTable = $('#newTable').DataTable({
data: newData,
});
var oldTable = $('#oldTable').DataTable({
data: newData,
});
}
});
}

How to reset the data after init , Select2

I use Select2-4.0.0 I have been struggling with this problem for a whole day that to update the data.
I search every posts I can like Update select2 data without rebuilding the control, but none have them work.
What I need is really simple (a setter to data):
I have a diaglog, which had a select. Every time I open the diaglog, I will ajax for an data to keep it in a local array like:
when dialog open :
var select2List=syncToLoadTheData();//data for select2
$('#search-user-select').select2({ //here when secondly executed, the select2's data on UI does not refreshed
data:select2List,
matcher: function(params, data){
var key = params.term;
if ($.trim(key) === '') {
return data;
}
if( (matchKeyAndPinyin(key,data.text))){
return data;
}
return null;
}
}
But the problem is even though the list is changing, the select options does not change at all.Please note in my test case, every time i open the dialog, the data from server is changed:
What I had tried:
1.when init:
data: function() { return {results: select2List}; }// not work to show any data at all
2.when secondly open dialog:
$( "#search-user-select").select2('data',newdata,true);//not work to have the new data
3.when secondly open:
$("#search-user-select").select2("updateResults");//Error, does not have this method
And some other method like directly change the array's data(only one copy of the data), but none of them work.
I had the same problem before, my problem was i need to update the select2 after every ajax request with new data.
and this how i fixed my code.
EventId = $(this).attr('id');
$.ajax({
url: 'AjaxGetAllEventPerons',
type: 'POST',
dataType: 'json',
data: {id: EventId},
})
.done(function(data) {
$("#select2_job").select2({
minimumInputLength: 2,
multiple:true,
initSelection : function (element, callback) {
//var data = data;
callback(data);
},
ajax: {
url: "/AjaxGetAllPersonForEvent",
dataType: 'json',
quietMillis: 100,
data: function (term) {
return {
term: term
};
},
results: function (data) {
var myResults = [];
$.each(data, function (index, item) {
myResults.push({
'id': item.id,
'text': item.fullname
});
});
return {
results: myResults
};
}
}
});
I hope this example will help you to solve your problem

Access class variable in jquery

I have a select in my html and would like to add the options via ajax when the page loads. The options values are in my DB and I get them via a call to ajax. To do so, I'm writing a class in javascript but I just can't get my data when it runs. Please take a look :
--- Main.js ---
function MyLoader() {
this._clients = null;
this._code = null;
}
Loader.prototype = {
var context = this;
loadClients: function() {
$.ajax({
url: "my/php/",
type: "POST",
data: {...},
success: function(response) {
context._clients = response;
}
});
},
getCode: function() {...}
};
Then I have the following :
$(document).ready(function() {
var loader = new Loader();
loader.loadClients();
alert(loader._clients);
//Here I want to add my options to the select
});
My alert always returns null, and I don't understand why. I need to save my data in the class in order to access them anytime I need to.
Can you point me to the right direction to make all my stuff work ? Thank you for your answers.
Loader.prototype = { // v---callback parameter
loadClients: function(callback) {
$.ajax({
url: "my/php/",
context: this, // <---set success context
type: "POST",
data: {...},
success: callback // <---pass callback
});
},
getCode: function() {...}
};
$(document).ready(function() {
var loader = new Loader();
// v---pass callback
loader.loadClients(function(response) {
this._clients = response;
alert(this._clients);
//Here I want to add my options to the select
});
});
I believe that you need to do all of your dynamic loading inside of your 'success' callback, since it is loading asynchronously.
You need to do it inside the success callback since it's async:
Loader.prototype = {
var context = this;
loadClients: function() {
$.ajax({
url: "my/php/",
type: "POST",
data: {...},
success: function(response) {
context._clients = response;
alert(loader._clients);
//Here I want to add my options to the select
}
});
},
getCode: function() {...}
};
$(document).ready(function() {
var loader = new Loader();
loader.loadClients();
});

Json MVC3 Object value in Javascript

I am sending json list from my controller:
public ActionResult LoadTree()
{
List<ListItem> list = new List<ListItem>() {
new ListItem() { Text = "Keyvan Nayyeri" },
new ListItem() { Text = "Simone Chiaretta" },
new ListItem() { Text = "Scott Guthrie" },
new ListItem() { Text = "Scott Hanselman" },
new ListItem() { Text = "Phil Haack" },
new ListItem() { Text = "Rob Conery" }
};
return new JsonResult { Data = list };
}
Trying to get the list in my view using:
var text =
$.ajax({
url: '/CourseCases/LoadTree',
dataType: 'json',
data: { },
cache: false,
type: 'GET',
success: function (data) {
}
});
alert(text);
I just get [object object]. How I can get the actual value of the object? Thanks in advance.
First you have to set the JsonRequestBehavior = JsonRequestBehavior.AllowGet in the JsonResult.
public ActionResult LoadTree()
{
List<ListItem> list = new List<ListItem>() {
new ListItem() { Text = "Keyvan Nayyeri" },
new ListItem() { Text = "Simone Chiaretta" },
new ListItem() { Text = "Scott Guthrie" },
new ListItem() { Text = "Scott Hanselman" },
new ListItem() { Text = "Phil Haack" },
new ListItem() { Text = "Rob Conery" }
};
return new JsonResult { Data = list, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
<script type="text/javascript">
$.ajax({
url: '/Home/LoadTree',
dataType: 'json',
data: {},
cache: false,
type: 'GET',
success: function (data) {
alert(data.length); // 6
// do whatever with the data
}
});
</script>
in success function you have to parse json to get actual data e.g.
var jsObject = JSON.parse(data);
and then access each item like jsObject.List[0].Text etc
Simple problem here. In your controller, you're actually assigning the list to a variable named Data inside the response data collection. Just because your success function takes a data parameter doesn't mean that the Data value you set in your controller automagically will become the data variable.
As your Data list is inside the data object: you need to do:
data.Data
inside your success function. Try this:
success: function(data) {
alert(data.Data.length);
}
function $.ajax() does not return value from server, so var text = $.ajax() will not work. You need to look at success handler instead
success: function (data) {
// data is the result of your ajax request
}
I strongly recommend you to read more at jQuery.Ajax
success(data, textStatus, jqXHR) A function to be
called if the request succeeds. The function gets passed three
arguments: The data returned from the server, formatted according to
the dataType parameter; a string describing the status; and the jqXHR
(in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the
success setting can accept an array of functions. Each function will
be called in turn. This is an Ajax Event.

Categories