On my PHP page I use AJAX to fetch items for an auction, everything is working properly when something is chosen from the dropdown lists (as can be seen from picture 1 ). My problem is that when the page loads for the first time (see second picture ) than nothing happens while I just want the default values of the dropdown list to be loaded in Ajax just like the rest, how do I go around this issue? Note that in the first picture I first selected something else and then selected the default values again, the 2nd picture is the page when i open up my browser and do nothing else.
my code:
$(function() {
$("#filtercatselect").on("change", function() {
var categoryid = document.getElementById("filtercatselect").value;
var orderbyname = document.getElementById("filterorderbyselect").value;
if(categoryid == "")
{
categoryid = 0;
}
$.post('homefiltering.php', { catid: categoryid, sortname: orderbyname }, function(result) {
$('#item-container').html(result);
}
);
});
$("#filterorderbyselect").on("change", function() {
var categoryid = document.getElementById("filtercatselect").value;
var orderbyname = document.getElementById("filterorderbyselect").value;
if(categoryid == "")
{
categoryid = 0;
}
$.post('homefiltering.php', { catid: categoryid, sortname: orderbyname }, function(result) {
$('#item-container').html(result);
}
);
});
});
just place under your code this, to trigger the change event on first script execution
[--- your code above ---]
$("#filterorderbyselect").trigger('change');
// OR - based on what code you prefer to execute on first page execution
// place both you make two equal ajax calls- thanks to Don't Panic
$("#filtercatselect").trigger('change');
How about this? On load you call the functions that I have given names and then assign them for change-event to the dropdowns.
$(document).ready(function(){
// call these methods on load
filtercatselectChangeHandler();
filterorderbyselectChangeHandler();
// set on-change handlers
$("#filtercatselect").change(filtercatselectChangeHandler);
$("#filterorderbyselect").change(filterorderbyselectChangeHandler);
});
function filtercatselectChangeHandler(){
var categoryid = document.getElementById("filtercatselect").value;
var orderbyname = document.getElementById("filterorderbyselect").value;
if(categoryid == "")
{
categoryid = 0;
}
$.post('homefiltering.php', { catid: categoryid, sortname: orderbyname }, function(result) {
$('#item-container').html(result);
}
);
}
function filterorderbyselectChangeHandler(){
var categoryid = document.getElementById("filtercatselect").value;
var orderbyname = document.getElementById("filterorderbyselect").value;
if(categoryid == "")
{
categoryid = 0;
}
$.post('homefiltering.php', { catid: categoryid, sortname: orderbyname }, function(result) {
$('#item-container').html(result);
}
);
}
Related
Im trying to update my grid without the need for refreshing! Right now, it updates only the grid, but dont know why, it changes the id to the last one inserted and dont "clean up" the empty row! When I try to insert data, it clears it .
Im kinda new with ajax and slickgrid! I've tried to see the ajax example from slickgrid, but I got some errors!
Do I need to re-upload the onCellChange and so on ? I just wanted to update th grid with the new data.
Any help?
Thanks in advance
So, I've tried re-draw the table re-using my actual drawning code, but im failling to re-draw with correct data.
Function to re-draw grid
function desenhaGrid() {
$("#myGrid").ready(function () {
$(function () {
$.ajax({
type: "GET",
url: '/SlickGrid/GetData',
dataType: 'json',
success: function (jsonResult) {
for (var key in jsonResult) {
if (jsonResult.hasOwnProperty(key)) {
//print table
var d = (data[key] = {});
for (var i = 0; i < data.length; i++) {
d["#"] = i + 1;
}
d["id"] = jsonResult[key].id;
d["t_nome"] = jsonResult[key].t_nome;
d["t_prof"] = jsonResult[key].t_prof;
d["t_data"] = jsonResult[key].t_data;
d["t_morada"] = jsonResult[key].t_morada;
d["t_percCompleto"] = jsonResult[key].t_percCompleto;
}
}
grid = new Slick.Grid("#myGrid", dataView, columns, options);
dataView.beginUpdate();
grid.invalidateAllRows();
dataView.setItems(data);
grid.render();
dataView.endUpdate();
}
});
});
});
}
and this is my onAddNewRow
grid.onAddNewRow.subscribe(function (e, args) {
var idData = jsonResult[key].id + 1;
var item = { "id": idData, "t_nome": '', "t_prof": '', "t_data": '', "t_morada": '', "t_percCompleto": '' };
$.extend(item, args.item);
dataView.addItem(item);
//if user press enter
grid.onKeyDown.subscribe(function (e) {
var keyPressed = event.keyCode || event.which;
if (keyPressed == 13) {
alert("add");
var myJSON = JSON.stringify(item);
$.post("/SlickGrid/addGridEnter", $("input[name=mydata]").val(myJSON));
console.log(myJSON);
desenhaGrid();
}
});
});
I expected it to re-draw my grid with all the data. Instead, its changing all the id's to the last one inserted and when I try to insert data in the last row, wont let me (it clears it after I leave the cell).
UPDATE:
I've udpate the function to draw the grid
function desenhaGrid() {
$("#myGrid").load(function () {
$(function () {
$.ajax({
type: "GET",
url: '/SlickGrid/GetData',
dataType: 'json',
success: function (jsonResult) {
dataView.beginUpdate();
grid.invalidateAllRows();
dataView.setItems(jsonResult);
dataView.endUpdate();
grid.render();
}
});
});
});
}
I don't think this is a SlickGrid issue. There are all kind of problems with the javascript. For example:
why are you using $("#myGrid").ready( ? the ready event only fires when the DOM has finished loading
the entire copy operation from jsonResult to data just ends up with the same data. why not use jsonResult directly?
the section for (var i = 0; i < data.length; i++) { d["#"] = i + 1; }
runs once for each row added to data, it should just run once at the end, outside of the loop
you are subscribing to the keydown event once for each row added to the grid. you should just subscribe once. listening for an Enter key is also a very poor method of determining if a row has been entered. what if someone clicks on another row before pressing Enter?
Slickgrid is a client-side grid. This means data does not need to be persisted after every change. It's a common approach to use a 'save' button, or detect if the active row has changed.
First, I'm sorry I don't know how to title the question better.
I'm making a Google Chrome extension whose purpose is to read table columns from a table on a page A. This happens in my inject.js:
var $tableRows = $("table tbody tr");
var offers = [];
var links = [];
$tableRows.each(function (index) {
offers.push({
code: $.trim($(this).find('td:nth-child(2)').text()),
city: $.trim($(this).find('td:nth-child(6)').text()),
state: $.trim($(this).find('td:nth-child(7)').text())
});
links.push($(this).find('td:first').find('a').attr('href'));
if (index == $campaignTableRows.length - 1) {
downloadPdfForOffers(offers, links);
}
});
The code above creates an array that holds information that's in the table for those offers and saves the links for every offer profile.
Then the function downloadPdfForOffers does the following:
var downloadPdfForOffers = function (offers, links) {
chrome.storage.local.set({"offers": offers}, function () {
chrome.runtime.sendMessage({
downloadUrlsReady: true,
data: {links: links}
});
});
};
It sets in the local storage the current information I have for those offers and send the links to background.js.
Then from background.js, I open those links in new tabs.
if (request.downloadUrlsReady) {
for (var i = 0; i < request.data.links.length; i++) {
chrome.tabs.create({url: request.data.links[i], active: true});
}
}
In my inject.js I'm waiting for the page to load the offer profile and with jQuery get the additional information I need and I send it to background.js again:
chrome.storage.local.get(["job_offers"], function (items) {
if (items.job_offers && items.job_offers.length > 0) {
var requirements = $("#j_id0\\:SiteTemplate\\:j_id747\\:j_id748").find('.margin-b3:first div.tcell:nth-child(2) div');
var data = {
file: {
link: $('.btn.btn-link.btn-lg.vs2.margin-r2').attr('href'),
name: $.trim($('#j_id0\\:SiteTemplate\\:j_id747\\:j_id767').text())
},
job_offer: {
position: requirements.text()
}
};
chrome.runtime.sendMessage({
pdfUrlReady: true,
data: data
});
}
});
Then in my background.js I update the already set offers and download the pdf:
if (request.pdfUrlReady) {
console.log(request.data);
chrome.storage.local.get(["job_offers"], function (items) {
items.job_offers.forEach(function (job_offer, index) {
if (job_offer.code == request.data.file.name) {
items.job_offers[index] = $.extend(job_offer, request.data.job_offer);
chrome.storage.local.set(items, function () {
chrome.downloads.download({
url: request.data.file.link,
saveAs: false,
filename: request.data.file.name + '.pdf'
}, function () {
chrome.tabs.remove(sender.tab.id);
});
});
}
});
});
}
The console.log there always has the full information I passed from the single page, however when I'm updating chrome.storage.local sometimes I get not complete information about the offer, probably because it's asynchronous.
How can I handle such situation?
what i have: page title is updating dynamically when new data is retrieving from ajax call; if tab with this page is visited - title is set to default value; if i open the second tab with this page, title of this tab is set to default (i must fix this)
what i need: page title must be the same for all tabs with this page. i mean, page title must be updated synchronously for all tabs.
My current implementation:
var prevData;
var newRequestsCounter = 0
var getRequests = function(){
$.ajax({
async: true,
type: "GET",
url: "/get_requests/",
success: function(data){
// retrieve and parse data. i skip this part
// newRequestsCounter is updating here
var visible = vis();
if (visible){
newRequestsCounter = 0
document.title = 'Default title'
} else {
if (newRequestsCounter == 0) {
document.title = 'Default title'
} else {
document.title = 'Dynamic title'
}
}
setTimeout(getRequests, 2000)
}
});
};
I tried with intercom.js, but it doesn't work properly. For some reason intercom.on gets different data each time. For example: first call - default title, second call - dynamic title. I checked with debug, wrong data comes after executing this line setTimeout(getRequests, 2000).
var intercom = Intercom.getInstance();
intercom.on('notice', function(data) {
document.title = data.title;
});
var prevData;
var newRequestsCounter = 0
var getRequests = function(){
$.ajax({
async: true,
type: "GET",
url: "/get_requests/",
success: function(data){
// retrieve and parse data. i skip this part
// newRequestsCounter is updating here
var visible = vis();
if (visible){
newRequestsCounter = 0
intercom.emit('notice', {title: 'Default title'});
} else {
if (newRequestsCounter == 0) {
intercom.emit('notice', {title: 'Default title'});
} else {
intercom.emit('notice', {title: 'Dynamic title'});
}
}
setTimeout(getRequests, 2000)
}
});
};
In general, i don't quite understand if it possible to achieve required functionality in scope of single ajax callback. I tried the next code. In this case variable "counter" from localStorage is incremented every time i open new tab. It means if i expect "3" in title for two tabs, i get "6" with two tabs instead.
var intercom = Intercom.getInstance();
intercom.on('notice', function(data) {
document.title = data.title;
});
if (localStorage.getItem("counter") === null){
localStorage.setItem("counter", 0);
}
var getRequests = function(){
$.ajax({
async: true,
type: "GET",
url: "/get_requests/",
success: function(data){
// skip part with retrieving and parsing data
var counter = localStorage.getItem("counter")
localStorage.setItem("counter", ++counter);
var visible = vis();
if (visible){
localStorage.setItem("counter", 0);
intercom.emit('notice', {title: 'Default'});
} else {
if (localStorage.getItem("counter") == 0 || localStorage.getItem("counter") === null) {
intercom.emit('notice', {title: 'Default'});
} else {
intercom.emit('notice', {title: '(' + localStorage.getItem("counter") + ') requests'});
}
}
setTimeout(getRequests, 2000)
}
});
};
getRequests();
The part I am not understanding in your code is where you are opening a new browser tab. But, if that happening somewhere and you want to set the title of that new tab as its opening you can do this:
var newTab = window.open('/page')
newTab.title = 'New Title';
are you using some kind of long polling?
Maybe you can synchronise those polling calls with the browser's time.
e.g. poll everytime the browser's time's seconds are even numbers. then each tab should send its request at the same time and get (almost) at the same time an answer to update there title
With alot of help from #kalley we have found out that If I comment the following two lines out the LAG is gone!
var $tableContents = $table.find('tbody')
var $html = $('<tbody/>').html(data);
But how do I keep the above but cancel out the LAG ?
MORE INFO:
The code below works but the problem is that the $.GET is causing the browser to hang until the ajax request completes. I need (flow control?) or something that will solve this problem without locking/hanging up the browser until ajax completes the GET request.
The biggest LAG/Lockup/Hang is at $.get("updatetable.php", since the others only return 7 or less (number) values and this one ('updatetable.php') returns alot more (200-300kb). I would like to implement some sort of flow control here or make the script wait like 5 secs before firing the update command for tablesort and before showing the toast message so that ajax has time to GET the $.get("updatetable.php"data I just don't understand why does it lockup the browser as it is getting the data? is it trying to fire the other commands and that's whats causing the LAG?
Here are the STEPS
1.
$.get("getlastupdate.php" Will fire every 10 secs or so to check if the date and time are the same the return data looks like this: 20130812092636 the format is: YYYmmddHHmmss.
2.
if the date and time are not the same as the last GET then $.get("getlastupdate2.php" will trigger and this data will be send back and placed into a toast message and dispalyed to the user $().toastmessage('showNoticeToast', Vinfoo);
3.
before or after the above ($.get("getlastupdate2.php") another GET will fire: $.get('updatetable.php' this will GET the updated table info. and replace the old one with the new info. and then update/resort the table
4.
at the end of it all I want to $.get("ajaxcontrol.php" and this will return a 1 or 2 if the user is logged in then it will be a 2 else it's a 1 and it will destroy the session and log the user out.
<script type="text/javascript" src="tablesorter/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="tablesorter/final/jquery.tablesorter.js"></script>
<script type="text/javascript" src="tablesorter/final/jquery.tablesorter.widgets.js"></script>
<script type="text/javascript" src="tablesorter/final/toastmessage/jquery.toastmessage-min.js"></script>
<script type="text/javascript" src="tablesorter/qtip/jquery.qtip.min.js"></script>
<script type="text/javascript">
var comper;
function checkSession() {
return $.get("ajaxcontrol.php", function (DblIn) {
console.log('checking for session');
if (DblIn == 1) {
window.location = 'loggedout.php';
}
}).then(updateTable);
}
function checkComper() {
var SvInfo;
var onResponse = function (comperNow) {
if (comper === undefined) {
comper = comperNow;
} else if (comper !== comperNow) {
var Vinfoo;
comper = comperNow;
// returning this $.get will make delay done until this is done.
return $.get("getlastupdate2.php", function (primaryAddType) {
Vinfoo = primaryAddType;
$().toastmessage('showNoticeToast', Vinfoo);
}).then(checkSession);
}
};
$.get('getlastupdate.php').then(onResponse).done(function () {
tid = setTimeout(checkComper, 2000);
});
}
function updateTable() {
return $.get('updatetable.php', function (data) {
console.log('update table');
var $table = $("table.tablesorter");
var $tableContents = $table.find('tbody')
var $html = $('<tbody/>').html(data);
$tableContents.replaceWith('<tbody>' + data + '</tbody>')
//$tableContents.replaceWith($html)
$table.trigger("update", [true]);
var currentUrl = document.getElementById("frmcontent").contentWindow.location.href;
var urls = ['indexTOM.php', 'index1.php'],
frame = document.getElementById('frmcontent').contentDocument;
for (var i = 0; i < urls.length; i++) {
var url = urls[i];
if (frame.location.href.indexOf(url) !== -1) {
frame.location.reload()
}
}
$('[title!=""]').qtip({});
});
};
$(function () {
var tid = setTimeout(checkComper, 2000);
$("#append").click(function (e) {
// We will assume this is a user action
e.preventDefault();
updateTable();
});
// call the tablesorter plugin
$("table.tablesorter").tablesorter({
theme: 'blue',
// hidden filter input/selects will resize the columns, so try to minimize the change
widthFixed: true,
// initialize zebra striping and filter widgets
widgets: ["saveSort", "zebra", "filter"],
headers: {
8: {
sorter: false,
filter: false
}
},
widgetOptions: {
filter_childRows: false,
filter_columnFilters: true,
filter_cssFilter: 'tablesorter-filter',
filter_filteredRow: 'filtered',
filter_formatter: null,
filter_functions: null,
filter_hideFilters: false, // true, (see note in the options section above)
filter_ignoreCase: true,
filter_liveSearch: true,
filter_reset: 'button.reset',
filter_searchDelay: 300,
filter_serversideFiltering: false,
filter_startsWith: false,
filter_useParsedData: false
}
});
// External search
$('button.search').click(function () {
var filters = [],
col = $(this).data('filter-column'), // zero-based index
txt = $(this).data('filter-text'); // text to add to filter
filters[col] = txt;
$.tablesorter.setFilters($('table.hasFilters'), filters, true); // new v2.9
return false;
});
});
</script>
Maybe instead of using setInterval, you should consider switching to setTimeout. It will give you more control over when the time repeats:
function checkComper() {
var SvInfo;
var onResponse = function (comperNow) {
if (comper === undefined) {
comper = comperNow;
} else if (comper !== comperNow) {
var Vinfoo;
comper = comperNow;
// returning this $.get will make delay done until this is done.
return $.get("getlastupdate2.php", function (primaryAddType) {
Vinfoo = primaryAddType;
$().toastmessage('showNoticeToast', Vinfoo);
}).then(checkSession);
}
};
$.get('getlastupdate.php').then(onResponse).done(function () {
tid = setTimeout(checkComper, 10000);
});
}
var tid = setTimeout(checkComper, 10000);
Then you can keep it async: true
Here's a fiddle showing it working using echo.jsontest.com and some fudging numbers.
Since the click event callback seems to be where the issue is, try doing this and see if it removes the lag (I removed other comments to make it more brief):
function checkSession() {
return $.get("ajaxcontrol.php", function (DblIn) {
console.log('checking for session');
if (DblIn == 1) {
window.location = 'loggedout.php';
}
}).then(updateTable);
}
function updateTable() {
return $.get('updatetable.php', function (data) {
console.log('update table');
var $tableContents = $table.find('tbody')
//var $html = $('<tbody/>').html(data);
//$tableContents.replaceWith($html);
// replaceWith text seems to be much faster:
// http://jsperf.com/jquery-html-vs-replacewith/4
$tableContents.replaceWith('<tbody'> + data + '</tbody>');
//$table.trigger("update", [true]);
var currentUrl = document.getElementById("frmcontent").contentWindow.location.href;
var urls = ['indexTOM.php', 'index1.php'],
frame = document.getElementById('frmcontent').contentDocument;
for (var i = 0; i < urls.length; i++) {
var url = urls[i];
if (frame.location.href.indexOf(url) !== -1) {
frame.location.reload()
}
}
$('[title!=""]').qtip({});
});
};
$("#append").click(function (e) {
// We will assume this is a user action
e.preventDefault();
updateTable();
});
I commented out $table.trigger("update", [true]) since if you sort the table on the server before you return it, you shouldn't need to run that, which I'm almost certain is where the bottleneck is.
It is really hard untangle the mess you have but if what you want is ajax requests every 10 seconds it make sense to separate this logic from business logic over data from server.
Your code would also really benefit from using promises. Consider this example
$(document).ready(function() {
var myData = { }
, ajaxPromise = null
setInterval(callServer, 1000)
function callServer() {
ajaxPromise = updateCall()
.then(controlCall)
.done(handler)
.error(errorHandler)
}
function updateCall() {
return $.get('updateTable.php', function(data) {
myData.update = data
})
}
function controlCall( ) {
return $.get('ajaxControl.php', function(data) {
myData.control = data
})
}
function handler() {
console.dir(myData)
}
function errorHandler(err) {
console.log(err)
console.dir(myData)
}
})
I have three URLs that return different JSON responses (say user mobiles, addresses and emails) being populated from different beans.
url='/mobile.do?username=x&password=y'
url='/email.do?username=x&password=y'
url='/address.do?username=x&password=y'
For the following autocomplete plugin (fcbkcomplete):
<script type="text/javascript">
$(document).ready(function(){
$("#mySelect").fcbkcomplete({
json_url: "?!!",
});
});
</script>
Now I want to use these URLs to populate and add data to a single field rather than three different fields. Hence, somehow I need to mix these URL or something like this.
I was wondering what is the best way for this? Can we set more than one URLs or something?
You could modify the plugin, by changing the function load_feed. This isn't tested, so might need some tweeking.
function load_feed(etext) {
counter = 0;
if (options.json_url_list && maxItems()) {
if (options.cache && json_cache_object.get(etext)) {
addMembers(etext);
bindEvents();
} else {
getBoxTimeout++;
var getBoxTimeoutValue = getBoxTimeout;
setTimeout(function () {
if (getBoxTimeoutValue != getBoxTimeout) return;
var count = 0;
var all_data = [];
var finished = function () {
if (!isactive) return; // prevents opening the selection again after the focus is already off
json_cache_object.set(etext, 1);
bindEvents();
};
for (var i = 0; i < options.json_url_list.length; i++) {
$.getJSON(options.json_url_list[i], {
"tag": xssDisplay(etext)
}, function (data) {
addMembers(etext, data);
count += 1;
if (count === options.json_url_list.length) finished();
});
}
}, options.delay);
}
} else {
addMembers(etext);
bindEvents();
}
}