Passing multiple array value from datatables - javascript

currently I am using datatables with multiple selection. When I select 3 rows based on picture here (from top to bottom), my console.log returns this value (return result every time row is being selected). The value that I need to post to next page is this, since it's the latest result:
["SN20171110", "SN20171111", "SN20171113"]
and so I did console.log again to check the value in ajax post without getting to next page but the result was random (the order):
https://i.stack.imgur.com/zVkrW.png
https://i.stack.imgur.com/Irf1k.png
https://i.stack.imgur.com/9Nn1n.png
So what I get in the next page was the bottom(latest) result from console.log mentioned above.
Is there any way to pass only the bottom result or javascript variable?
Here is my Datatable selection code:
var newdata = $.map(example.rows('.selected').data(), function (item) {
$(this).toggleClass('selected');
return item[1];
});
var test = newdata;
console.log(test);
$('#nextButton').click(function(e){
$.ajax({
url : 'enrollmentDevice.php',
method : 'POST',
data : { test },
beforeSend: function(){
console.clear();
},
success : function(new2) {
console.log(test);
}
Thanks in advance.

Ok I solved the problem by posting the value to hidden form and POST to next page using
<form action="nextpage.php" method="POST"></form>
instead of using Ajax.
But still not sure what cause the problem. Any input would be appreciate. Thank you.

Related

Execute DataTables ajax.reload() Async before a function

I am trying to source some data from the datatable I am working on. I have an edit button on every row and when is clicked it suppose to bring a form with the data that is already in the table for editing. I need to get real time data when the form is render however ajax.reload() doesn't load the table on time for the form be filled by the correct data and with code below only shows the form for the first employee:
let editEmployeeId;
$(document).ajaxStop(function(){
$('#employeesTable tbody').on('click', '.btn.btn-warning.small-edit-button', function(){
let thisRow = this;
tableEmployees.ajax.reload(function(){
//tableDepartments.draw();
tableDepartments.columns().search("").draw();
//tableEmployees.columns().search("").draw();
getDropdown(1,'#departmentEditDropdown', 'Departments');
var data = tableEmployees.row($(thisRow).parents('tr')).data() || tableEmployees.row($(thisRow).parents('li').attr('data-dt-row')).data();
$('#editFirstName').val(data.firstName);
$('#editLastName').val(data.lastName);
$('#departmentEditDropdown>select').val(data.department);
updateLocation('#locationEditDropdown','#departmentEditDropdown>select');
$('#departmentEditDropdown>select').trigger('change');
$('#locationEditDropdown>select').val(data.locationID);
$('#editJobTitle').val(data.jobTitle);
$('#editEmail').val(data.email);
$('#editEmployeeModal').modal("show");
});
});
I tried:
promise
settimeout
nested functions
async functions
I also try to change ajax call to set async: false and this way it works perfect but I don't think that is a good practice and I have other calls through the document and takes double of time to load the page first time.
I changed the way of calling the button with an extra class for the employees page and used the .click() method instead .on() because for some reason it was going in a loop with the last one. Now works and this is how it looks:
let editEmployeeId;
$(document).ajaxStop(function(){
$('.btn.btn-warning.small-edit-button.employees').click(function(e){
e.preventDefault();
let thisRow = tableEmployees.row($(this).parents('tr'));
let thatRow = tableEmployees.row($(this).parents('li').attr('data-dt-row'));
tableDepartments.columns().search("").draw();
tableEmployees.columns().search("").draw();
getDropdown(1,'#departmentEditDropdown', 'Departments');
tableEmployees.ajax.reload(function(){
var data = thisRow.data() || thatRow.data();
editEmployeeId = data.id;
$('#editFirstName').val(data.firstName);
$('#editLastName').val(data.lastName);
$('#departmentEditDropdown>select').val(data.department);
$('#departmentEditDropdown>select').trigger('change');
$('#editJobTitle').val(data.jobTitle);
$('#editEmail').val(data.email);
$('#editEmployeeModal').modal("show");
})
});

Angularjs xeditable not showing value in input field

I am using Angular-xeditable to update individual values on a view. Additionally, I am retrieving those values from a remote server, here is snippet:
$http.get('api/get-solution').success(function (data) {
$scope.goalSoluton = data['goal_planning_data'];
});
And this is what has been return from the remote server:
{age:"26" retirement:"0"}
In my HTML view I see that the object property value of age (which is 26) is displayed, Here is a snippet:
{{goalSoluton.age}}
But when I had clicked to edit that input field the value of 26 does not show up. Also, when I even entered a value in the input field and pressed the update button, the age property of the object did not update. Here is a snippet of the function:
$scope.update = function () {
console.log($scope.goalSoluton);
};
What am I doing wrong and thanks in advance.
You try to href get empty. . we used that. Maybe.

Trying to use an id from the same page that my .click function was triggered on, in an ajax function

newbie to coldfusion/jquery/programming general here. So the overview of my problem is this: I have a ticket id that corresponds with a specific row in my database. When I click a button, I would like one of the columns in that row to change values to "In Testing". My issue is that I do not know how to pull that ticket id number into my jquery function, or if this is even possible. My code:
<script src="/TicketFaster/js/jquery-1.11.3.js"></script>
<script src="/TicketFaster/js/scripts.js"></script>
<cfset ticketid="#ticketid#">
<button id="in_testing" type="button">In Testing</button>
my js:
$(document).ready(function() {
$("#in_testing").click(function() {
var x = (#ticketid#);
$.ajax({
url: 'ticketcomponent.cfc?method=in_testing',
type: 'POST',
data: {
test: x
}
});
});
});
The big problem is that these pages are being generated dynamically, so each one will have a different ticket id. Therefore, I need to have the ticket id variable be imported rather than just hard coded in to the jquery function. So is this possible? I did not include the query because it works fine when I use it in other places, just getting the data delivered is the tough part. I appreciate any help you can give me :)
Edit: I was requested to post what I'm trying right now.
The original coldfusion is the same so I'm not going to post that again. Here is the js I'm using:
$(document).ready(function() {
$("#in_testing").click(function() {
var x = (<cfoutput>#ticketid#</cfoutput>);
alert(x);
});
});
(I also tried without the cfoutput tags)
As you can see, I'm just trying to do a simple alert to check if my variable has been correctly set. Once I get that to work, then the ajax should follow fairly quickly because I have some experience in that.
What is your specific issue?, can you share a jsfiddle?
for dynamic events replace
$("#in_testing").click(function() {});
for
$(document).on('click','#in_testing', function() {});
This value
var x = (#ticketid#);
in jquery is some like that
var x = $('#ticketid').val(); // for value or $('#ticketid') for object
you just have to take account id created dynamically

Appending new results to an open jQuery autocomplete menu

I have an app in which I have multiple search sources. Previously, the users had to choose in what source to search in before searching. If they did not choose, the app would default to one of the options.
However, now they want to search in all the sources at the same time. This is fine enough, but the problem is that when one of the searches returns, it overwrites the previous search result. Pretty much expected behavior. What I basically want is to append the new results to the already open autocomplete menu, instead of overwriting the old results. Naturally, the autocomplete menu would have to empty when it closes.
I guess that this is possible to do, but what approach is the best? I could just have an array I guess, which I append results to and then overwrite _renderMenu to use this array instead of the items one that is passed to the function. Then empty said array at the close event.
Is this the best way to go though? Or is there a more elegant solution?
Some code:
Ok, so searchAction is called by jquery autocomplete eventually. In collection.search I do the ajax call, here the URL is created based in the this parameter, then respondWhithData is called and maps the search result to a proper format (ie value and label for the autocomplete menu). After reponse is called from respondWithData, jquery automagically renders the resultsmenu. Thus, I probably have to overwrite the reponse event function as well as the _renderMenu and possibly _renderItem, yes?
searchAction: function(searchTerm, collection, response){
var self = this;
$.when(collection.search(searchTerm, this)).then(function(data) {
self.respondWithData(data, response);
});
},
respondWithData : function(data, response) {
if (data.length > 0) {
var responseVal = _.map(data, this.mapData);
this.checkResponseCount(responseVal);
response(responseVal);
}
else {
response(this.emptyResult());
}
},
To be clear, the problem is not the multiple search itself, but rendering the asynchronos results. I want to render the first results that come back, and then appends the rest as soon as they are returned from the server.
Edit 2:
Just tried to edit ui.content in the autocompleteresponse event, but any edit does not take once it renders for some reason...
Edit 3: Ah, ui.content can only be modified directly, not changed. If I push every single change instead of concating two arrays ui.content shows what I want.
It works I guess, but its not perfect.
I can figure how looks your scenario but I'm guessing:
You should have like:
function search1() {
$.ajax({ ...
success: function(data) {
$('#myResultsDiv").html(data)
}
});
}
etc
Instead of overwritting the #myResultsDiv you need to Append the results like:
function search1() {
$.ajax({ ...
success: function(data) {
$('#myResultsDiv").append(data)
}
});
}
Edit: You can also do something like this:
var resultsArray = [];
var searchDone = 0;
var totalSearchs = 5; //assuming 5 searches
function search1() {
function search1() {
$.ajax({ ...
success: function(data) {
//APPEND data to resultsArray
searchDone++;
if(searchDone==totalSearch) //syncronize the 5 searchs before render
renderSearchs(resultsArray);
}
});
}

How to reset pagination in a JQuery datatable

I have a JQuery datatable that loads data via an ajax request. There is a form by the table that lets the user filter the results on the server. When the user changes the filter form, I call fnReloadAjax() with the new filter data, and the table redraws with the new, filtered results.
The problem I have is that the pagination sticks, even if the table no longer has enough items to reach the current page. So if the table originally had 20 items, and the user was on page 2 (10 items per page), and they change the filter so only 5 items are returned, the table displays no items and shows this at the bottom:
Showing 11 to 5 of 5 entries
It's still on page 2 even though there is only enough data for one page.
I have found numerous posts about trying to preserve the current page/row, but none showing a simple way to reset pagination to the first page. What is the simplest way to do this?
Here's a simplified version of my code for clarity:
$("#mytable").dataTable({
bStateSave: false,
fnServerData: function (sSource, aoData, fnCallback) {
return $.ajax({
type: "POST",
url: url,
data: {filter: filterValue}
});
}
});
$("#myForm").submit(function(e) {
table.fnReloadAjax();
return false;
});
You could explicitly jump to the first page after reloading, see http://datatables.net/api#fnPageChange
$("#myForm").submit(function(e) {
table.fnPageChange(0);
table.fnReloadAjax();
return false;
});
Accepting the solution given by #Gigo:
$("#myForm").submit(function(e) {
table.fnPageChange(0);
table.fnReloadAjax();
return false;
});
This have a problem, it sends two request to the server.
i have found that the fnPageChange does it at the first time.
$("#myForm").submit(function(e) {
table.fnPageChange(0);
return false;
});
This can be solved by implementing the functions to save and load the state of the datatable and resetting the start point - example below
"fnStateSave": function (oSettings, oData) {
localStorage.setItem( 'MyDataTable', JSON.stringify(oData) );
},
"fnStateLoad": function (oSettings) {
var settings = JSON.parse( localStorage.getItem('MyDataTable') );
settings.iStart = 0; // resets to first page of results
return settings
},
As fnStateLoad is called when the table is reloaded - e.g. a new filter is applied - the paging is reset to the start.
fnStateSave is called each time you retrieve the next page of results
This approach avoids the overhead of an additional request back to the server

Categories