$function(){ and $window.onload() - I'm not sure how to handle this? On the $('#ashift').on('click',function(){ I need the ajax call to fire again? should I wrap it in a function and call the function on page load and then again in the click event, or is there a better way - I need the clicked_shift variable to update in the ajax call.
<script id="source" language="javascript" type="text/javascript">
var clicked_shift = "C";
$('#ashift').on('click', function(){
clicked_shift = "A";
});
$(function () {
$.ajax({
url: 'county.php',
data: {action:"tt"},
dataType: 'json',
success: function(data){
alert(clicked_shift);
$.each(data, function(key, val) {
if (val.completed == 1) {
color = "green";
} else {
color = "red";
}
if (val.Shift == clicked_shift){
$('#station'+val.Station+' .snum').append("<span style='color:"+color+"'>" + val.LastName + "</span><br/>");
}
});
}
}); // end ajax
}); // end of function()
</script>
var clicked_shift = "C";
function ajaxCall(){ // function declaration
console.log("clicked_shift",clicked_shift);
}
$(function () {
ajaxCall(); // call function ondomready
$('#ashift').live('click',function(){
clicked_shift = "A"; // change variable value
ajaxCall(); // re-invoke the function
});
}); // end of function()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div id="ashift">click</div>
$(function(){}); is like $(document).ready(function(){}); a self invoked anonymous function which will be triggered when dom is fully loaded. To re-invoke a function later, you need to declare it or to assign it to a variable.`
Related
I have main.js and load.js, in load.js there are 2 crucial functions, getData which is an AJAX post call and constHTML which appends data based on the JSON array returned from the AJAX call. This data is appended to a div that will become a carousel slider when I call carousel() on main.js, therefore, It's important to append the data before the carousel() function else the slider renders for 0 items.
load.js
var getData = function (item, id) {
$.ajax({
//ajax options,
success: function (data) {
constHTML(item, data);
}
});
}
var constHTML = function (item, data) {
if (condition) {
for (var i in data.results) {
//Do something
}
}
else if (condition) {
//Do something
}
}
var getID = function () {
//Code...
};
main.js
//Execute getData scripts
if (condition) {
getData('single', getID());
} else if (condition){
getData('list', getID());
}
var carousel() = function(){
//do stuff
}
//call carousel() MUST execute after constHTML in load.js is done
carousel();
HTML
<script src="js/jquery.min.js" defer></script>
<script src="js/load.js" defer></script>
<script src="js/owl.carousel.min.js" defer></script>
<script src="js/main.js" defer></script>
So the result of the above code is load.js loads then main.js loads, getData() is called, ajax call started THEN carousel() executed, constHTML and so on.
What I'm trying to do is wait until constHTML() is finished THEN continue to carousel();. I cant figure out how to implement deferred objects and promise for cross-file functions.
Your getData must return the ajax call in order to use .then( doneCallbacks, failCallbacks ):
var getData = function (item, id) {
return $.ajax({
//ajax options,
success: function (data) {
constHTML(item, data);
}
});
}
getData(....).then(
function() {
alert( "succeeded" );
}, function() {
alert( "failed!" );
}
);
Here is my javascript code, the event is onkeyup for many row of table !
function product(id)
{
$('#customers2').find('tr').click( function(){
var clicked = this;
});
var row = $(clicked).find('#tempnow').val();
if (row == "noncheck"){
$(clicked).find('#ett').val("");
$(clicked).find('#ett').prop("disabled", true);
}
else{
$(clicked).find('#ett').prop("disabled", false);
$.ajax({
url:baseurl+"/getinform/",
type: "POST",
dataType: "json",
data: {masp : id},
success:function(data) {
var thue = data['pcs_cl_pd_thue'];
$(clicked).find('#tyu').css("color", "red");
$(clicked).find('#tyu').val(thue);
}
});
}
}
When i use firebug, variable clicked is not defined ?
var clicked; // Define it outside
$('#customers2').find('tr').click( function(){
clicked = this; // Give it a value on click, from inside a function
next() // Now it has a value, call another function that'll do something with it
});
function next(){
$(clicked).find('#ett') // It works!
}
I have a simple ajax function:
<script type="text/javascript"
src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
function crunchifyAjax() {
$.ajax({
url: '/user/show-user-task-messages?code=<c:out value="${liveCode}"/>',
success: function (data) {
$('#result').html(data);
}
});
}
</script>
<script type="text/javascript">
var intervalId = 0;
intervalId = setInterval(crunchifyAjax, 100);
</script>
The function check every 100ms my url and return some text like this:
10
9
8
7
6
5
4
3
2
1
stop
I want to break this timer after data contains stop. How can I do this?
Any help in this regard is much appreciated.
Try this:
<script type="text/javascript"
src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
function crunchifyAjax() {
$.ajax({
url: '/user/show-user-task-messages?code=<c:out value="${liveCode}"/>',
success: function (data) {
$('#result').html(data);
if((""+data).indexOf("stop") > -1)
clearInterval(intervalId); //clearing the interval started by setInterval
}
});
}
</script>
<script type="text/javascript">
var intervalId = 0;
intervalId = setInterval(crunchifyAjax, 100);
</script>
Just to give you an example, check for data's content - and if it matches your condition (in your case holding "stop") -> clearInterval().
Dummy code:
var intervalId = null;
var x = 0;
intervalId = setInterval(crunchifyAjax, 100);
function crunchifyAjax() {
if (x < 10) {
x++;
console.log(x);
return true;
}
clearInterval(intervalId, crunchifyAjax);
}
Assuming your server returns an array of items like
["1","2","4","stop","6"]
You can check the array coming back and see whether it has an item "stop" and if yes call clearInterval method.
success: function (data) {
$('#result').html(data);
var subset = data.filter(function (a) {
return a === "stop";
});
if (subset.length > 0) {
window.clearInterval(intervalId);
}
}
If your server is returning a string like "1,3,5,stop,6", you can do indexOf method to check the existence of the specific string
success: function(data) {
$('#result').html(data);
if (data.indexOf("stop") > -1) {
window.clearInterval(intervalId);
}
If you are returning a collection of items, I strongly suggest you to return an array instead of a concatenated string.
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 want after click on link show alert box with tow option ok and cancel, if user click on button ok return it function is true and if click on button cancel return it function is false, problem is here that after click on link always return is true. How can fix it?
Example: http://jsfiddle.net/MaGyp/
function myalert() {
var result = true;
var $alertDiv = $('<div class="alert">Do you want to delete this item?<button class="ok">ok</button><button class="cancel">cancel</button></div>');
$('body').append($alertDiv);
$('.ok').click(function () {
$('.alert').fadeOut(100);
$('#appriseOverlay').css('display', 'none');
result = true;
});
$('.cancel').click(function () {
$('.alert').fadeOut(100);
$('#appriseOverlay').css('display', 'none');
result = false;
});
$alertDiv.fadeIn(100);
$('#appriseOverlay').css('display', 'block');
return result;
};
$('.iu').click(function () {
alert(myalert());
if (myalert() == true) {
alert('ok')
} else {
alert('no')
}
});
Update:
...
$('.iu').click(myalert)
function callback(result) {
//
if(result){
alert(result);
$('.image_upbg').each(function(){$(this).removeClass().addClass(unique())});
var get_class = '.'+$(this).closest('div').attr('class');
var get_val = $(this).closest('a').find('input').attr('value');
//alert(get_val);
var val = 'val_upimg1=' + get_val;
$(get_class).fadeOut('slow');
$.ajax({
type: "POST",
dataType: 'json',
url: 'delete_upimg',
data: val,
cache: false,
success: function (data) {
$(get_class).fadeOut('slow');
},
"error": function (x, y, z) {
// callback to run if an error occurs
alert("An error has occured:\n" + x + "\n" + y + "\n" + z);
}
});
}else{
alert('no')
}
}
If you want to keep it structured like this, you could use a callback after the user responds.
http://jsfiddle.net/MaGyp/2/
function myalert() {
...do stuff here
$('.ok').click(function () {
callback(true); // callback when user clicks ok
});
$('.cancel').click(function () {
callback(false); // callback when user clicks cancel
});
}
$('.iu').click(myalert);
function callback(result) {
alert(result);
}
As suggested by Ben you could improve this by making the callback function a parameter to the first function to remove the tight coupling.
myalert() returns before result is set to true or false. To fix it I suggest having myalert() take a callback function as a parameter, and calling it inside the click() handlers within myalert(). The .iu event handler will then need to be split into two functions, one of which is the callback passed into myalert().
you are not waiting for the ok and cancel clicks so would always return true.
Modified the fiddle - http://jsfiddle.net/MaGyp/3/
function myalert() {
var result = true;
//var hide = $('.alert').fadeOut(100);
//var css = $('#appriseOverlay').css('display','none');
var $alertDiv = $('<div class="alert">Do you want to delete this item?<button class="ok">ok</button><button class="cancel">cancel</button></div>');
$('body').append($alertDiv);
$alertDiv.fadeIn(100);
$('#appriseOverlay').css('display','block');
return result;
};
$(document).ready(function(){
$('.ok').live('click',function () {
$('.alert').fadeOut(100);
$('#appriseOverlay').css('display','none');
alert('ok');
});
$('.cancel').live('click',function () {
$('.alert').fadeOut(100);
$('#appriseOverlay').css('display','none');
alert('cancel');
});
$('.iu').click(function() {
myalert();
});
})