So I've been stuck at this problem for quite a long time. Basically I have a button (#action) located in index.html. I have a second page : number.html. I'm trying to get in the .receiver span from index.html either .success content or .failure content from number.html, depending if #action was clicked in less than 2 seconds.
Here is the code :
$(function() {
var ajaxRetrieve = function(callback) {
$.ajax({
url: 'number.html',
method: 'POST',
success: function(responseData) {
callback(responseData);
},
error: function(responseData) {
alert('Check yourself');
}
});
}
var flag = 0;
$('#action').on('click', function() {
flag = 1;
});
if (flag == 1) {
ajaxRetrieve(function(data) {
$('.receiver').html($(data).find('.success'));
});
} else {
setTimeout(function() {
ajaxRetrieve(function(data) {
$('.receiver').html($(data).find('.failure'));
});
}, 3000);
};
});
Problem : on click, I never get the .success content, and I have no error message. But after 2 seconds, the .failure actually shows up. I tried several ways to make it work but it doesnt. I also checked if the flag value was changed on click with an alert box, and it was
You need to include the ajax calls within the on click function, otherwise the if logic will only be called when the page is loaded and never again.
$(function() {
var ajaxRetrieve = function(callback) {
$.ajax({
url: 'number.html',
method: 'POST',
success: function(responseData) {
callback(responseData);
},
error: function(responseData) {
alert('Check yourself');
}
});
}
var flag = 0;
$('#action').on('click', function() {
flag = 1;
flagCheck();
});
var flagCheck = function() {
if (flag == 1) {
ajaxRetrieve(function(data) {
$('.receiver').html($(data).find('.success'));
});
} else {
setTimeout(function() {
ajaxRetrieve(function(data) {
$('.receiver').html($(data).find('.failure'));
});
}, 3000);
};
}
});
Related
I need help with an advanced search I implemented into a new existing page system.
It seems there is a problem with the existing jquery ui on the page:
<script src="js/jquery-ui-1.10.4.custom.js"></script>
<script type="text/javascript" src="js/jquery.lazy.min.js"></script>
When I enter my code the page isn't working properly anymore.
My code:
$(document).ready(function() {
// Icon Click Focus
$('div.icon').click(function(){
$('input#warenkorb_suche_feld').focus();
});
// Live Search
// On Search Submit and Get Results
function search() {
var query_value = $('input#warenkorb_suche_feld').val();
$('b#search-string').text(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "search.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}return false;
}
$("input#warenkorb_suche_feld").live("keyup", function(e) {
// Set Timeout
clearTimeout($.data(this, 'timer'));
// Set Search String
var search_string = $(this).val();
// Do Search
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}else{
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
});
The search script works fine but I need to add
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
And after this page stops working. What can I do to get this stuff working?
Consider the following. I was not able to test it.
$(function() {
function search(term, callback) {
$('b#search-string').text(term);
$.ajax({
type: "POST",
url: "search.php",
data: {
query: term
},
cache: false,
success: function(html) {
$("ul#results").html(html);
if(callback && (typeof callback == "function")){
callback();
}
}
});
return false;
}
$('div.icon').click(function() {
$('input#warenkorb_suche_feld').focus();
});
$("input#warenkorb_suche_feld").on("keyup", function(e) {
// Set Search String
var search_string = $(this).val();
// Do Search
if (search_string.length > 0) {
$("ul#results, h4#results-text").fadeOut(400, function() {
search(search_string, function() {
$("ul#results, h4#results-text").fadeIn();
});
});
}
});
});
This makes use of the complete callback for .fadeOut(). So once it has faded, it will then run the search. I added a Callback in the search so that once the AJAX has completed, it will reveal the results with .fadeIn().
You may want to consider adjusting the length condition. This ensures
I have an ajax function which loads the next page or results in without refreshing. This works fine, but what I'm aiming to do is run this in a loop until a certain element is loaded in through the ajax call.
jQuery
var ajaxPageNumber = 2;
function infiniteResults() {
$.ajax({
type: 'GET',
url: '/?page=' + ajaxPageNumber,
success: function(data) {
ajaxPageNumber +=1;
if (data.length) {
$('.table tbody').append(data);
} else {
$('<div class="text-center"><strong>No more results remaining.</strong></div>').insertAfter('.table');
}
}
});
}
$(document).ready(function() {
var i = 0;
while (($('.desired-element').length < 1) && (i < 50)) {
infiniteResults();
i++
console.log("More results loaded");
}
} else {
console.log("Max tries reached, fail);
}
});
The problem I'm running into is that it fires all 50 of my loops ajax calls at once, so it appends page 2 of the data 50 times. This happens even though in my test, the desired element is on page 4.
Is something like this feasibly possible in jQuery/javascript?
All the calls happen in sequence very rapidly. Without knowing your full intent I would have it so the infiniteResults is only called again after it has completed, so these happen sequentially and not together.
I haven't tested this but this is what I am thinking...
var ajaxPageNumber = 2;
function infiniteResults() {
$.ajax({
type: 'GET',
url: '/?page=' + ajaxPageNumber,
success: function(data) {
ajaxPageNumber += 1;
if (data.length) {
$('.table tbody').append(data);
if (ajaxPageNumber < 50) {
infiniteResults(); // NEW
}
} else {
$('<div class="text-center"><strong>No more results remaining.</strong></div>').insertAfter('.table');
}
}
});
}
$(document).ready(function() {
infiniteResults();
});
You could return the promise that $.ajax returns, and use that in a kind of loop, by calling a function recursively (although the stack will not grow, due to the asynchronous nature):
var ajaxPageNumber = 2;
function infiniteResults() {
// return the jQuery promise
return $.ajax({
type: 'GET',
url: '/?page=' + ajaxPageNumber,
success: function(data) {
ajaxPageNumber +=1;
if (data.length) {
$('.table tbody').append(data);
} else {
$('<div class="text-center"><strong>No more results remaining.</strong></div>').insertAfter('.table');
}
}
});
}
$(document).ready(function() {
(function repeat(i) {
infiniteResults().done(function () {
if ($('.desired-element').length == 0 && i < 50) {
console.log("More results loaded");
repeat(i+1);
} else {
console.log("Max tries reached, fail");
}
});
})(0);
});
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
setInterval(makeAjaxCall(),5000);
function makeAjaxCall() {
var url = '/Lines/dbcheck/?LineID=#ViewBag.LineID&ProductID=#ViewBag.ProductID&LastID=#LastID';
var data = {};
$.get(url, data, function(response_text){
if (response_text == 1)
{
document.location.reload();
}
else
{
setInterval(makeAjaxCall(),5000);
}
}, "text");
}
I already can call function from controller but only 1 time. I would like to create function to check the data from database and return 1 or 0. If it is 0 i would like to make a delay for 5 sec and then recall function again.
the problem is the parameter response_text is not updated because I can call the function from controller only first time
setInterval(makeAjaxCall(),5000);
function makeAjaxCall() {
$.ajax({
cache : false,
dataType: "json",
type: "GET",
async:false,
url: url ,
success: function (fdata) {
if (fdata == 1)
{
document.location.reload();
}
else
{
setInterval(makeAjaxCall(),5000);
}
},
error: function (reponse) {
}
});
}
Your code executed immediately because of you passing () it is not wait for the time delay.
setInterval(makeAjaxCall(), 5000);
change to
setInterval(makeAjaxCall, 5000);
or alternate way
setInterval(function() {
makeAjaxCall();
}, 5000);
I want to create a "add" button in my jQuery calculator. When I click "add" button, it display "+" in the display and the number that I have entered will be stored. After that I can input another number to finish the equation. I can stuck in the part of the add button not sure how to do it. Do I need to use load()?
Try this out. Made a solution with limited inputs you have given
http://jsfiddle.net/sabkaraja/utc7f2ex/
You can decide what you want to do with the added value in #add.click(....) event. I have used a simple eval to get the result in.
$(function () {
var $display = $('#display');
$display.val(0);
$(document).on('click', 'button.number', function () {
if ($display.val().length >= 8) {
$display.val("Error");
} else if ($display.val() == "Error") {
$display.val("0");
} else {
$display.val( $display.val() + '+' + $(this).val());
}
});
$("#clear").click(function () {
$display.val("0");
});
$("#ce").click(function () {
if ($display.val().length >= 2) {
$display.val($display.val().substring(0, $display.val().length - 1));
} else {
$("#ce").trigger("click");
}
});
$("#add").click(function () {
if ($display.val().length !== 0) {
v = eval($display.val()); //<----- here is where I add the numbers
$display.val( v); //------------> do whatever you like to do after this
$.ajax({
url: 'submit.php',
type: 'POST',
dataType :'html',
data: {sum: v},
success: function(data) {
alert(data);
}
});
}
});
});