Run JS function on .load() content - javascript

I have a function called timepicker which is usually called by using
$(document).ready(function() {
$('#timepicker').timepicker();
});
But I have been unable to make it work on content that is displayed using jQuery .load().
I have tried several methods including using the below but nothing happens?
$(document).ready(function() {
var $parent = $('#small_container');
var time = $parent.find('#timepicker');
time.timepicker();
});
The #small_container is the ID of the DIV that the content is loaded into and the #timepicker is the id of the input that should call the function when it is clicked on.
Have I added it to the correct place in the callback?
$('.edit_job').on("click", function(){
var week_start = $('input[name=week_start]').val();
var job_id_del= $('input[name=job_id]').val();
var user_id = $('input[name=user_id]').val();
$('#small_container').load('ajax/edit_weekly_job_load.php?job_id='+job_id_del+'&week_start='+week_start+"&user="+user_id);
$('#timepicker').timepicker();
$('#small_container').on("click", '#edit_job_submit', function(){
jQuery.ajax({
type: "POST",
url: "ajax/edit_weekly_job_ajax.php",
dataType: "json",
data: $('#edit_job_form').serialize(),
success: function(response){
if(response.success === 'success'){
window.opener.$("#diary").load("ajax/diary_weekly_load.php?week_start="+week_start+"&user="+user_id);
window.close();
}
},
});//end ajax
});//save_job_edit_submit
});//end edit job

The content is loaded asynchronously to the element #small_container. The timepicker function is gets called before the content is actually loaded. Try to call the function in the callback of load() method:
$('#small_container').load('ajax/edit_weekly_job_load.php?job_id='+job_id_del+'&week_start='+week_start+"&user="+user_id ,function(){
$('#timepicker').timepicker();
} );
Also validate that element #timepicker is actually appended to the element #small_container.

Related

when scroll down, data is loaded by ajax but click trigger is not working jquery

i face a problem of jquery click function when i scroll down in list.
in list, data is loaded by ajax request and when i scroll down then click function (trigger) is not working.
when i not scroll down, ajax data is not loaded then click function is working.
i'm confuse why this happened. i used following triggers below but not success.
on()
click()
bind()
load()
delegate()
i'm sending you code. this is code below. Please help me to sort out.
$(window).ready(function(){
$(".like").on("click", function(){
var id = $(this).attr('data');
// alert(id);
$.ajax({
url: "/stores/addLike",
type: 'GET',
data: {
id: id
},
error: function (data) {
console.log(data);
},
success: function (data) {
console.log(data);
if(data == "liked"){
alert('Sorry, you have already liked this beat.');
}else if(data == "notlogin"){
alert('Please login first to like a beat.');
window.location = "https://demo.amplifihub.com/login";
}else{
$(".likes"+id).text(data);
}
}
});
});
});
instead of $(".like").on("click", function(){ }); use $(document).on("click", ".like", function(){}); or use any static parent dom element to preserve the DOM event. I believe you are generating .like class element on scroll ajax call.

Loading screen while javascript function executes

I have following javascript code which loads information from multiple json files and appends them in HTML table if "info" parameter in URL is true.
$(document).ready(function(){
var appList=["app1","app2","app3"];
//function to get url parameters
var parameters = new URL(window.location).searchParams;
var info=parameters.get('info');
if (info=="true"){
for (var i=0;i<appList.length;i++){
setInfoAndDateUtil(app)
}
}
function setInfoAndDateUtil(app){
$.ajax({
url:'server_name/'+ app + '/info.json';
method: 'GET',
dataType: 'json',
contentType:'application/json',
success: function(jsonData){
var info=jsonData.info;
td=$("#" + app);
td.text(info).css("text-align", "center");
}
})
}
The ajax requests are taking some time since they are loading about 16 json files. So I want to add loading screen while this function executes.
I have tried few methods like this but none of them are working.
$(document).ajaxStart(function(){
$("#wait").css("display", "block");
});
$(document).ajaxComplete(function(){
$("#wait").css("display", "none");
});
Can anyone tell me how to do it exactly?
Use this approach using JQuery:
// Add Loader on ajax calls
$("body").prepend("<div id='spinner'><img src='/images/spinner.gif'></div>");
$(document).ajaxSend(function(){
$('#spinner').show();
});
$(document).ajaxComplete(function(){
$('#spinner').hide();
});

jQuery: Updating global var and re-running function

I have a function that has another function nested that binds a click event to re-run that function with a different ajax URL:
function getInternal() {
var callUrl = 'https://url.com'; // URL ON LOAD
$.ajax({
dataType: "json",
url: callUrl,
success: function(data) {
var obj = data;
$( document ).ready(function(callUrl) {
$( "a.dept" ).click(function() {
var filterDept = $(this).attr('id');
callUrl = 'https://url.com/' + filterDept; // URL TO UPDATE
getInternal(callUrl); // RUN THIS FUNCTION AGAIN
});
});
Unfortunately the click event continues to return the same data. It doesn't look like callUrl is updating.
How do I update a global variable from within a function to re-run itself?
The first line of your function sets your variable to a specific value: var callUrl = 'https://url.com'; Thus, every single time you run this function, the variable will be set to 'https://url.com'.
By moving your variable outside of the function it will become a global variable, and the portion of your code that updates callUrl will persist.
That being said, your code is all sorts of mixed up. You have $( document ).ready() within an AJAX callback, a click event that gets redefined within that with each call, nothing seems to be closed, and you've supplied a parameter for getInternal(); despite the fact that it takes none.
Is something like this what you're after?
$(document).ready(function() {
//On click of link, run AJAX call to changing URL (based on clicked link's ID)
$( "a.dept" ).click(function() {
var filterDept = $(this).attr('id');
var callUrl = 'https://url.com/' + filterDept;
getInternal(callUrl);
});
});
function getInternal(callUrl) {
$.ajax({
dataType: "json",
url: callUrl,
success: function(data) {
alert("Call made to " + callUrl);
}
});
}

JQuery fadeOut not working for ajax post request

I have this JQuery code:
$(function(){
$('input#SearchGo').on('click', function(){
var searchid = $('input#search').val();
var dataString = 'search='+ searchid;
$.ajax({
type: "POST",
url: "tickets.php",
data: dataString,
cache: false,
success: function(html) {
$("#result").html(html).show();
}
});
return false;
});
});
that does a live search and posts data to a PHP page.
On every page i have a div with an id of overlay with a loading image while the page loads, then this code:
$(window).load(function(){
// PAGE IS FULLY LOADED
// FADE OUT YOUR OVERLAYING DIV
$('#overlay').fadeOut();
});
removes the overlay div once the page has loaded.
when i run the search query, the overlay div doesnt fadeOut at all, i tried adding $('#overlay').fadeOut(); within the success part of my function but it doesnt fadeOut the div.
UPDATE:
here is the HTML for the loading / overlay div
<div id="overlay" class="overlay">
<img src="images/integra_loading.gif" alt="Loading" width="12%" style="margin-top:15%;" />
<br /><br />
<h1>Loading...</h1>
</div>
$(function(){//this says the dom is ready
$('#overlay').fadeOut();
});
alternatively
$(document).on("ajaxComplete", function(){
$('#overlay').fadeOut();
});
Don't hide your ajaxloader with a function that is called from the html script wich is loaded through the ajax request. just show the loader before the request and hide it before replacing the html content with your response.
function loader(){
this.id = '#overlay'
};
loader.prototype.show = function(){
$(this.id).fadeIn();
};
loader.prototype.hide = function(){
$(this.id).fadeOut();
};
loaderObj = new loader();
$('.list').live('click', function() {
loaderObj.show();
$.ajax({
type: "GET",
url: "http://echo.jsontest.com/uid/12345/value/nuno_bettencourt",
cache: false,
dataType: "json",
success: function(json) {
// setTimeout only to delay the response and let the loader do his thing ;)
setTimeout(function(){
loaderObj.hide();
$('#ajaxResult').html("UID=" + json.uid + "\nName=" + json.value);
}, 2000);
}
});
i made you a small fiddle example http://jsfiddle.net/358Fz/1/
after doing your $.ajax, add a done. in that done, do the fadeout!
$.ajax({
...
}).done(function(){
$('#overlay').fadeOut();
});
you can add a .fail for when it fails, etc. see: http://api.jquery.com/jquery.ajax/
Just define the loader variable outside of your click event and then use it where needed. There will be less overhead if you only have to traverse the DOM once to locate the loader element. You can also change the on event to just a click event to save a few key strokes unless you need to delegate the event to another element. Also, you don't need to look up $(input#search) since ID's are unique. Removing the variable selector and just looking up the ID will be more efficient.
$(function() {
var $loader = $('#overlay');
$('.list').click(function(){
$loader.fadeIn();
$.ajax({
type: "GET",
url: "http://time.jsontest.com/",
dataType: 'json',
cache: false,
success: function(json) {
$loader.fadeOut();
$("#axajResponse").html('<b>Current Time:</b> ' + json.time).show();
}
});
return false;
});
});
In the above example I'm getting back the current time so that you can see the response change on each click event.
Here is an example: http://jsfiddle.net/bradlilley/jLG4g/

execute a function on page load in jquery mobile

I am building a mobile app with Jquery mobile. What you need to know is that I am also working with a content renderer. So I only have one with data-role page. This is what I do in the content renderer. with <%= incBody %> I get the content of my pages.
<body <%=incBodyAttr%>>
<div data-role="page" class="type-index" data-theme="g">
<%=incBody%>
</div>
</body>
I think that was somewhat that you needed to know. Now the real problem.
At the moment I have a function load() You can see it over here.
function load(){
var userId = $("#userId").val();
$.ajax({
url: "~SYSTEM.URL~~CAMPAIGN.URL~/SelligentMobile/Webservice/WebService.asmx/getNieuwtjes",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{'userId':'" + userId + "'}",
success: function (response) {
var nieuwtjes = response.d;
if (nieuwtjes.length > 0) {
$.each(nieuwtjes, function (i, entity) {
$('#nieuwtjesList').append(
$("<li/>").append($("<a/>")
.attr("href",'~PROBE(239)~&NEWSID=' + entity.nieuwtjeId)
.text(entity.nieuwtjeOnderwerp)
)
);
$('#nieuwtjesList').trigger("create");
$('#nieuwtjesList').listview('refresh');
});
}
}
});
}
Now this load is triggered by a button at the moment. But what I want to do is that each time the page loads, its executing this function.
Can anybody help ?
kind regards
Call it from a document ready handler:
$(document).ready(function() {
load();
});
Or, given that you're not passing parameters to load():
$(document).ready(load);
The first way allows you to do other stuff before or after calling load(), should you need to: just add more code into the anonymous function.
See the .ready() doco.
You should use jQuery DOM ready:
$(function() {
// call load() after DOM ready
load();
});
You can also use as
$(document).ready(function() {
load();
})

Categories