Hey guys I have the following code:
function runATF(){
var urlatf = '/pcg/ATF/updateATF_window.php';
var tagatf = $("#insider_dialog");
var promise1 = showUrlInDialogATF(urlatf);
var promise2 = sendUpdateATFwindow();
$.when(promise1, promise2).done(function(data1, data2) {
tagatf.html(data1[0]).dialog({
width: '100%',
modal: true
}).dialog('open');
//$('.updaterATF_outerbody').text(data2[0].atfName),
//$('.updaterATF_outerbody').text(data2[0].atfAmount)
//console.log(data2[1]);
alert(data2[0].text(atfName));
alert(data2[0].text(atfAmount));
});
}
The part I need you to look at it the alert(data2[0].text(atfName)); and the alert(data2[0].text(atfAmount)); My problem is I can't seem to get the values?
Let me show you the 2 functions that are ran:
First this one just sends a url and returns....
function showUrlInDialogATF(urlatf)
{
return $.ajax({
url: urlatf
});
}
The second one returns the two data values that are created in a document.ready (I have tested them and they do hold values, it's only when I try and get it into the $.when statement).....
function sendUpdateATFwindow()
{
return $.ajax({
data: {
'atfName': atf_name.val(),
'atfAmount': atf_amount.val()
}
});
}
Let me know if you need anything else, thank you
David
Oh here is the first statement that begins everything:
$(document).ready(function () {
$(".atf-submit").click(function () {
atf_name = $(this).parent().parent().find(".user_table");
atf_amount = $(this).parent().parent().find(".user_atf");
runATF();
});
});
Note: I am using the Jquery UI dialog opener, I already have one open so I am making another one open. I don't know if this will effect anything? I would assume not because the functions and values are different names.
UPDATE:
Okay I want to show the first code that opens the first dialog window up:
$(document).ready(function () {
$("#ATF").click(function () {
runATF();
});
});
function runATF(){
var urlATF = '/pcg/ATF/atf_layout.php';
showUrlInDialogATF(urlATF);
}
function showUrlInDialogATF(urlATF)
{
var tag = $("#dialog-container");
$.ajax({
url: urlATF,
success: function(data) {
tag.html(data).dialog
({
width: '100%',
modal: true
}).dialog('open');
}
});
}
Than the other code runs - I will re post here:
$(document).ready(function () {
$(".atf-submit").click(function () {
atf_name = $(this).parent().parent().find(".user_table");
atf_amount = $(this).parent().parent().find(".user_atf");
runATFinsider();
});
});
function runATFinsider(){
var urlatfinsider = '/pcg/ATF/updateATF_window.php';
var tagatfinsider = $("#insider_dialog");
var promise1 = showUrlInDialogATFinsider(urlatfinsider);
var promise2 = sendUpdateATFwindow();
$.when(promise1, promise2).done(function(data1, data2) {
tagatfinsider.html(data1[0]).dialog({
width: '100%',
modal: true
}).dialog('open');
//$('.updaterATF_outerbody').text(data2[0].atfName),
//$('.updaterATF_outerbody').text(data2[0].atfAmount)
console.log(data2[1]);
alert(data2[0].text(atfName));
});
}
function showUrlInDialogATFinsider(urlatfinsider)
{
return $.ajax({
url: urlatfinsider
});
}
function sendUpdateATFwindow()
{
return $.ajax({
data: {
'atfName': atf_name.val(),
'atfAmount': atf_amount.val()
}
});
}
Also I try to do a console.log(data2) and it just gives me, [0] = abunch of html? , [1] = success, [2] = object
UPDATE:
Here is an example of what it I should be getting in the data2[0]...
alert(atf_name.val()); = bob
alert(atf_amount.val()); = 0
Related
I have two very similar jquery AJAX codes. Both work correctly when I use them separately. However, if I load the first code, if I want to load the second it probably works (because I tested different places "console.log(''test'')"), but it doesn't change the DOM. Please help.
I have tried many different solutions and none have provided a solution. I have searched on many forums but have not found an answer.
1st
var basketAddTimeout;
var ajaxSubmitForm;
app_shop.run(function() {
ajaxSubmitForm = function() {
$this = $('#projector_button_basket');
var url = $('#projector_form').attr('action');
var txt = $this.text().trim();
clearTimeout(basketAddTimeout);
$.ajax({
type: 'POST',
url: url,
data: $('#projector_form').serializeArray(),
success: function(data) {
basketAddTimeout = setTimeout(function() {
$('#Basket').load(' #projector-basket-form');
}, 1000)
fetch('/ajax/basket.php').then(res => res.json()).then(({
basket
}) => {
const number = basket.productsNumber;
const number12 = basket.worth_formatted;
$('#kwota-basket').text(number12);
document.getElementById('badgekoszyka').style.display = 'block';
$( "#badgekoszyka" ).fadeOut( "slow");
$( "#badgekoszyka" ).fadeIn( "slow");
$('#menu_basket .badge').text(number);
$('#badgekoszyka').text(number);
})
},
error: function() {
classObj.alert(classObj.txt.dodano_produkt_blad);
$('#projector_button_basket').html(txt);
$('#projector_button_basket').removeClass('loader');
}
});
}
}, 'all');
second
var basketAddTimeout2;
var ajaxSubmitForm2;
app_shop.run(function() {
ajaxSubmitForm2 = function() {
var url = $('#projector-basket-form').attr('action');
$('#loaders').addClass('loader-koszyk');
$('#blok-koszyk').css('filter','blur(3px)');
clearTimeout(basketAddTimeout2);
$.ajax({
type: 'POST',
url: url,
data: $('#projector-basket-form').serializeArray(),
success: function(data) {
basketAddTimeout2 = setTimeout(function() {
}, 1000)
fetch('/ajax/basket.php').then(res => res.json()).then(({
basket
}) => {
const number = basket.productsNumber;
const number12 = basket.worth_formatted;
$('#kwota-basket').text(number12);
$('#menu_basket .badge').text(number);
$('#badgekoszyka').text(number);
$('.topBasket').load('/basketchange.php?type=multiproduct&mode=2 .topBasket>*', function() {});
$('#loaders').removeClass('loader-koszyk');
$('#blok-koszyk').css('filter','blur(0px)');
document.getElementById("Basket").innerHTML = contentt;
})
},
error: function() {
classObj.alert(classObj.txt.dodano_produkt_blad);
}
});
}
}, 'all')
$(document).on('click', '#usuwanie-koszyk, #dodawanie-koszyk, #usuwanie-calkowite ', function(e) {
ajaxSubmitForm2();
e.preventDefault();
});
You Should call e.preventDefault() at the priority to defend the default action on the element in the second request.
$(document).on('click', '#usuwanie-koszyk, #dodawanie-koszyk, #usuwanie-calkowite ', function(e) {
e.preventDefault()
ajaxSubmitForm2()
});
Is it possible to open the window after the execution of the script expandNextLevel()?
I'm asking this because I don't want to let the client see the expand/collapse animation but just the treeview collapsed.
This is my code.
<script type="text/javascript">
$(function () {
$(".k-gantt").click(function () {
expandNextLevel();
var windowWidget = $("#window");
windowWidget.data("kendoWindow").open().center();
$.ajax({
type: 'GET',
url: '/Act/load',
contentType: 'application/json; charset=utf-8',
success: function (result) {
},
error: function (err, result) {
alert("Error" + err.responseText);
}
});
function expandNextLevel()
{
setTimeout(function () {
var treeview = $("#treeview").data("kendoTreeView");
var b = $('.k-item .k-plus').length;
treeview.expand(".k-item");
treeview.trigger('dataBound');
if (b > 0) {
expandNextLevel();
collapseNextLevel();
}
}
, 200);
};
function collapseNextLevel()
{
setTimeout(function () {
var treeview = $("#treeview").data("kendoTreeView");
var b = $('.k-item .k-minus').length;
treeview.collapse(".k-item");
treeview.trigger('dataBound');
if (b > 0) {
collapseNextLevel();
}
}
, 200);
};
</script>
Regards
try this
$.when(expandNextLevel()).done(function(){
/// show window
});
docs https://api.jquery.com/jquery.when/
I think the fastest way to do something like this is put everything in a hidden div, wich you will then show when you're done with the code execution.
You could also put a visible div with a rotating icon while the code is being executed, and hide it when you show the main content to make the users know something is happening.
EDIT:
I made a slight modification to the expand function, that should let me know when it's done executing the recursion, by adding an index I increment everytime. At the end of the function there is a code that will be executed only when the index is equal to one, wich means the first instance of the function is done executing.
<script type="text/javascript">
$(function () {
$(".k-gantt").click(function () {
expandNextLevel(0);
var windowWidget = $("#window");
windowWidget.data("kendoWindow").open().center();
$.ajax({
type: 'GET',
url: '/Act/load',
contentType: 'application/json; charset=utf-8',
success: function (result) {
},
error: function (err, result) {
alert("Error" + err.responseText);
}
});
function expandNextLevel(var i)
{
i++;
setTimeout(function () {
var treeview = $("#treeview").data("kendoTreeView");
var b = $('.k-item .k-plus').length;
treeview.expand(".k-item");
treeview.trigger('dataBound');
if (b > 0) {
expandNextLevel(i);
collapseNextLevel();
}
if (i == 1)
{
$.("#maincontent").show();
}
}
, 200);
};
function collapseNextLevel()
{
setTimeout(function () {
var treeview = $("#treeview").data("kendoTreeView");
var b = $('.k-item .k-minus').length;
treeview.collapse(".k-item");
treeview.trigger('dataBound');
if (b > 0) {
collapseNextLevel();
}
}
, 200);
};
</script>
You should put you content inside a div
<div id="maincontent" style="display:none;">
/*your content*/
</div>
I didn't test it but it should work :)
There is a better way to do this with jQuery.when, jQuery.done and promises, but I'm not confident I can give you a working sample since I never used those methods
I am opening mvc view(s) inside a modal dialog.
I am trying to make a recursive call and the problem I am facing is : after the recursive call the view loads properly but none of the controls on the view work :
In Main.js :
$(function () {
$(document).on('click', '.ddlCart li', Mod.Carts);
}
Carts.js :
var Mod = Mod || {};
Mod.Carts = function (e) {
var ddlselectedVal = $(this).attr('id');
var selectedListinsCount = selected_Listings.length;
var SelectedMlsnums = selected_Listings.join();
var agentId = $("#AgentId").val();
var Action;
var EnvironmentURL = $("#EnvironmentURL").val();
var postData = { AgentId: agentId, Mlsnums: SelectedMlsnums, ActionTypeValue: “PreAddToCart” };
var close = function (event, ui) {
$('#dvModalDialog').dialog("close");
}
var open = function (event, ui) {
var url = EnvironmentURL + "MLSReports/Stats/SearchContacts";
$("#btncart_cancel").on("click", function () {
$('#dvModalDialog').dialog("close");
});
$("#btncart_submit").on("click", function () {
var url = EnvironmentURL + "MLSReports/Stats/Cart";
//Send the data using post and put the results in a div
$.post(url, {
AgentId: agentId, Mlsnums: SelectedMlsnums, ActionTypeValue: "AddToCart"
},
function (data) {
// Replace current data with data from the ajax call to the div.
$("#dvModalDialog").empty().append(data);
});
});
$("#lnkCreateNewcart").on("click", function () {
var url = EnvironmentURL + "MLSReports/Stats/Cart";
//Send the data using post and put the results in a div
$.post(url, {
ActionTypeValue: "preAddorEditContact"
},
function (data) {
//debugger;
// Replace current data with data from the ajax call to the div.
$("#dvModalDialog").empty().append(data);
$("#btnCancelContact").on("click", function () {
////********** replace the view (Contact) with the view (Cart).
// In the cancel event I am loading the previous page.I am having problem here. after a recursive call none of the controls work.**
// rd.open();
this.Mod.Carts();
});
});
});
};
if (ddlselectedVal == "AddtoCart") {
var rd = Mod.ReportsDialog({ title: 'Add To Cart', close: close, open: open });
rd.url = EnvironmentURL + "/MLSReports/Stats/Cart";
rd.targetElement = '#dvModalDialog'// '#dvSendEmail'
rd.formName = '#frmCart'
rd.postData = postData
rd.open();
}
};
The value of this inside of the referenced function is going to be different when this.Mod.Carts(); is used. You should use call in this scenario to bind the value of this to the proper value when calling the Carts function.
$("#btnCancelContact").on("click", function () {
Mod.Carts.call(this);
});
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 an inline script on my page as such:
<script type="text/javascript">
var rootPath = '<%= Url.Content("~/") %>';
$(document).ready(function () {
$('#logonStatus').click(function () { loadLoginForm(); });
alert('Document Ready');
});
function loadLoginForm() {
if(!serenity.tools.isStyleSheetLoaded('redmond.css')) {
$('head').append('<%= Url.StyleTag("Redmond/redmond.css", MediaTypes.Screen) %>');
}
if(!serenity.tools.elementExists($('#logonContainer'))) {
$.ajax({
async: false,
cache: false,
datatype: 'html',
success: function (data) { $('body').append(data); },
type: 'GET',
url: '/Membership/LogOn'
});
}
$('#logonContainer').dialog({
modal: true,
hide: 'slide'
});
}
</script>
I also am loading a custom javascript file and the contents of it are as such:
var serenity = new function () {
$(document).ready(function () {
jQuery.ajaxSetup({
beforeSend: function (xhr) {
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
}
});
});
this.tools = new function () {
this.isStyleSheetLoaded = function (fileName) {
$(document.styleSheets).each(function () {
if (this.href.toLowerCase().indexOf(fileName) != -1) {
this.isStyleSheetLoaded = true;
return;
}
});
this.isStyleSheetLoaded = false;
}
this.elementExists = function (element) {
this.elementExists = element.length != 0;
}
}
}
The file that is being loaded by the ajax call is simply a div with an table containing input elements. The file does not contain any javascript in it whatsoever.
My problem is that the first time I call isStyleSheetLoaded it works just fine but after the file is loaded and the dialog is shown and closed I click on the link that fires the loadLoginForm function but this time it says isStyleSheetLoaded is not a function. This is showing up in all browsers, so I am 99% sure it is my problem, but I have no idea what it is. Could someone please point me in the right direction?
Thanks in advance.
I think your problem is the following:
you define a function "this.isStyleSheetLoaded = function (fileName)" but in his body you overwride this property "this.isStyleSheetLoaded = true;".
So after your first call of isStyleSheetLoaded the function is overwride with a boolen.
the right way could be:
this.isStyleSheetLoaded = function (fileName) {
$(document.styleSheets).each(function () {
if (this.href.toLowerCase().indexOf(fileName) != -1) {
return true;
}
});
return false;
}