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();
})
Related
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.
I'm no javascript expert and I'm trying to find out how I can ensure my functions are available for all my pages.
My setup:
index.php > my main page where I load my javascript functions
sl.php > a back end script sending html back
$(document).ready(
function ButtonManager()
{
$( "button" ).click(function()
{
$.ajax
({
type: 'POST',
url: 'php/sl.php',
data: 'test=1',
cache: false,
async: false,
dataType: 'html',
success: function(result)
{ $('#mydiv').html(result);
}
});
}
});
</pre>
In my index.php, I have a button that triggers this function and it works fine. Basically it retrieves some html containing other buttons using the same function as the one described above. The problem is that the function declared in index.php does not seem to be known by the html I get back from sl.php
Is there a way to make my ButtonManager function available for the html code that comes back from the server ? The html I get back from the server is inserted in the page where the function is declared.
UPDATE 29/07 :
Here is an example of the buttons I use
TEST
I have such a button in index.php and when I click on it, it posts test=1 to sl.php
In return I get some content that I insert into #mydiv. The process works fine except that buttons included in the sl.php output do not react at all when I click on them.
TJ Crowder:
I have tried your solution (the one without the ready tag) but now even the buttons in index.php don't react any more.
Here is a simplified version to clear any interferences with something else.
var MyApp;
MyApp = MyApp || {};
(function() {
MyApp.ButtonManager = ButtonManager;
function ButtonManager() {
$("button").click(function() {
alert ('oo');
});
}
})();
In the end, the only thing I would like to do is have one location to manage all buttons with sometimes buttons being used in index.php sometimes elsewhere.
Thanks!
Laurent
The code in the question has syntax errors. I'm going to guess your code actually looks like this:
$(document).ready(function() {
function ButtonManager() {
$("button").click(function() {
$.ajax({
type: 'POST',
url: 'php/sl.php',
data: 'test=1',
cache: false,
async: false,
dataType: 'html',
success: function(result) {
$('#mydiv').html(result);
}
});
});
}
});
If so, your ButtonManager function is only accessible within the anonymous function you've passed to ready; it's not accessible outside it.
You can make it a global, but the global namespace is already really crowded, so I'd only create one more global, MyApp or something, and make your functions properties on that object:
// Declare it -- this is a no-op if it's already been declared by another script
var MyApp;
// Use it if it's already initialized by another script, or initialize it if not
MyApp = MyApp || {};
// Your original code
$(document).ready(function() {
// Make ButtonManager a property of MyApp
MyApp.ButtonManager = ButtonManager;
function ButtonManager() {
$("button").click(function() {
$.ajax({
type: 'POST',
url: 'php/sl.php',
data: 'test=1',
cache: false,
async: false,
dataType: 'html',
success: function(result) {
$('#mydiv').html(result);
}
});
});
}
});
Using it:
var mgr = MyApp.ButtonManager();
There, I've left your ButtonManager inside the ready callback on the theory that you have other code in that callback that needs to wait for ready, but just creating the ButtonManager function doesn't need to wait for ready. If you don't have code that needs to wait for ready, you can do this:
// Declare it -- this is a no-op if it's already been declared by another script
var MyApp;
// Use it if it's already initialized by another script, or initialize it if not
MyApp = MyApp || {};
// Use a scoping function to avoid creating more globals
(function() {
// Make ButtonManager a property of MyApp
MyApp.ButtonManager = ButtonManager;
function ButtonManager() {
$("button").click(function() {
$.ajax({
type: 'POST',
url: 'php/sl.php',
data: 'test=1',
cache: false,
async: false,
dataType: 'html',
success: function(result) {
$('#mydiv').html(result);
}
});
});
}
})();
Side note: The overwhelming convention in JavaScript is that function names start with a lowercase letter unless the function is meant to be called via the new operator. So in this case, buttonManager rather than ButtonManager.
I think I have found the solution, TJ Crowder put me on the right track.
In my main page, I have isolated my function to make it global:
<pre>
function ButtonManager()
{ same ajax call }
in my server side output I have added:
<script>
var mgr = ButtonManager();
</script>
</pre>
When I now click on one of the button coming from the server, the function is correctly executed!
Thanks!
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/
I have this ajax request:
$.ajax({
type: "POST",
dataType: "json",
data: dataString,
url: "app/changeQuantity",
success: function(data) {
$('#table').append('<tr><td><a id="uid">click</a></td></tr>');
});
as you can see it makes new row in #table. But this new objects made by ajax are not accessible from next functions. Result from ajax is not a regullar part of DOM, or what is the reason for this strange behavior?
$('#uid').on('click', function () {
alert('ok');
});
Use event delegation:
$(document).on('click','#uid', function () {
alert('ok');
});
Note that ajax calls are asynchronous. So whatever you do with the data you need to do it in a callback within the success function (that is the callback which is called when the ajax call returns successfully).
Jquery on doesn't work like that. Use have to give a parent which not loaded by ajax, and the specify ajax load element like this
$('#table').on('click','#uid' ,function () {
// what ever code you like
});
Is simple and complex at the same time. Simple to solve but complex if you are getting started with javascript...
Your event handler - onclick is being fired and bound to an object that doesnt yet exist.
So when you append the object to the #table, you need to set up your click handler as the object now exists.
So in your success part of the ajax return add the click handler event there.
success: function(data) {
$('#table').append('<tr><td><a id="uid">click</a></td></tr>');
$('#uid').on('click', function () {
alert('ok');
});
});
Or how about you make it dynamic and create a function to do it for you.
function bindClick(id) {
$('#' + id).click(function() {
//Do stuff here
console.log('I made it here' + id);
});
}
Then:
success: function(data) {
$('#table').append('<tr><td><a id="uid">click</a></td></tr>');
bindClick(uid);
});
}
This is a super contrived example but you get the idea you just need to make the rest of it dynamic as well. for example some name and counter generated id number: id1, id2, id3...
Try it like this, add this $('#uid').on('click', function () { into the success
$.ajax({
type: "POST",
dataType: "json",
data: dataString,
url: "app/changeQuantity",
success: function(data) {
$('#table').append('<tr><td><a id="uid">click</a></td></tr>');
$('#uid').on('click', function () {
alert('ok');
});
});
});
I have a nifty little piece of Ajax code that loads in PHP.
http://www.moneyworrier.com/client-stories/
What happens is that when you click on a menu item on the left-hand navigation, it reloads a Div with content appropriate.
What it does however is loop through previous requests, which is bothersome (Click on any left hand item 3x and you will see what I mean). I think I need to find a function that does the equivalent of exit; and clears any post data.
My call in code is:
Video
And my JS looks like:
$(document).ready(function () {
$('a.media').click(function () {
var usr = $(this).attr('rel');
$("#displaystories").html('Retrieving..');
$.ajax({
type: "POST",
url: "/client-stories/media.php",
data: "showcode=" + usr,
success: function (msg) {
$("#displaystories").ajaxComplete(function (event, request, settings) {
$(this).html(msg);
});
}
});
});
});
You're binding a new listener to ajaxComplete on every click. Your success callback should just be:
success: function(msg) {
$("#displaystories").html(msg);
}