How to call JavaScript function during Pageload? - javascript

I have a Html page contains several pages whose data-role = page as page1,page2 etc.
I am trying to call a JS method during pageload of page1 using the following code
$("#page1").on("load",function () {
alert("hi")
$.ajax({
type: "GET",
url: "",
data: "{}",
contentType: "application/json",
dataType:"json",
success: function (msg) {
var BPRList = '';
$.each(msg, function(i,v){
BPRList += '<li onClick="GetBprDetails('+ v.BPRNo +')"><p class="title">' + v.BPRNo + '</p><p class="bodyEle">' + v.BPR_Product +'</p><p class="bodyEle">' + v.BPR_Details+ '</p><br/><p class="bodyEle">' + v.BPR_Status + ':</p></li>'
})
$("#BPRListTable").html(BPRList)
$('[data-role=listview]').listview('refresh');
},
error: function () {
alert("BPR List Error");
}
}); });
During the execution of above function I am unable to get the output during the formload
where as if I call the above method as button click event am able to get the output.
What might be the mistake made in above code..
I am more worried in following code.
$("#page1").on("load",function () {
--statements
})

$(window).load(function () {
alert("hi")
});
If you want the results on page load,then try this instead.Write this code outside $(document).ready(function(){});

Try to put 'page:load' instead of 'load' it might work better :
$("#page1").on("page:load",function () {
- - - -
- - - -
- - - -
});

Found solution Myself
$(document).ready(function(){
$(document).on('pagebeforeshow','#page1',function () {
--statements
}); });

i think using pageinit would be ok
$(document).on('pageinit', '#page1', function() {...})
In this manner, you avoid using document.ready, which is also not recommended by jquery mobile.

Related

jQuery Load And Ajax Forms Not Working Together

I've created a news system, where i should be able to edit articles dynamically without redirect, from a modal. Also, i should be able to delete and create articles.
When something is changed, jQuery Load is called, but the problem is when i have to edit the loaded content.
$("#toolbox-items").load('inc-toolbox');
The above code loads the articles (the file is called inc-toolbox on purpose and works fine).
$(function () {
$('form').on('submit', function(e) {
e.preventDefault();
var clicked = document.activeElement.getAttribute('name');
$.ajax({
type: 'post',
url: 'process-toolbox',
data: $(this).serialize() + "&" + clicked + "=success",
success: function (response) {
$("#toolbox-items").load('inc-toolbox');
$('.modal-backdrop').remove();
}
});
});
});
But, when ever something has to be edited or deleted, the whole page reloads and nothing changes, although i'm still able to add things.
The add-button is not loaded dynamically from the script, but is in there from the start.
What in the world might the problem be?
Try code like this
$(function () {
$(document).on('submit','form', function(e) {
e.preventDefault();
var clicked = document.activeElement.getAttribute('name');
$.ajax({
type: 'post',
url: 'process-toolbox',
data: $(this).serialize() + "&" + clicked + "=success",
success: function (response) {
$("#toolbox-items").load('inc-toolbox');
$('.modal-backdrop').remove();
}
});
});
});

Javascript works locally but not on the server

I've got a problem with some JavaScript code. It works fine when I test the website locally but doesn't work on the server unless I reload the page. The code is below. Please let me know if you need more details.
$(document).ready(function(){
$( "#header_inbox_bar" ).click(function() {
const inboxtopcount = $('#inboxtopcount')
const badgedanger = inboxtopcount.parent('.badge-danger')
$.ajax({
type: 'POST',
url: 'controllers/ctrl_client_update_inbox_notifications.php',
success (res) {
if (res) {
badgedanger.hide()
inboxtopcount.hide()
}
},
});
});
});
my guess is your DOM elements are not binding to the jQuery in time. Also, try inspecting your jQuery for syntax errors or any missing syntax.
To address any binding issues on load, try using the jQuery 'on' method so you can then pass it your #header_inbox_bar element and have it bind at a later time. like this:
$(document).ready(function() {
$('body').on('click', '#header_inbox_bar', function() {
const inboxtopcount = $('#inboxtopcount');
const badgedanger = inboxtopcount.parent();
$.ajax({
type: 'POST',
url: 'controllers/ctrl_client_update_inbox_notifications.php',
success(res) {
badgedanger.hide();
},
});
});
});

e.preventDefault does still loads anchor link in a new tab in browser

I have basically a ajax call that invokes a REST API that gives me list of all names and I have another REST API that matches that. For example,
/list gives me: list1,list2,list3
and
/api/list1.json gives me: json of list1..
But I have my code where I loop through all the lists and invoke /api/list1.json
I want that JSON to be displayed in a div when a onclick event occurs by grabbing the href accordingly without page reload. But right now, since that is also a valid link browser just takes me there.
Here is my code:
$(function() {
$.ajax({
dataType: 'json'
url: '/lists',
success: function (data) {
if (data != null) {
var html = '<ul>';
$.each(data.apis, function (i, item) {
//click event
$('a').click(function(e) {
e.preventDefault();
});
html += '<li class="res">';
html += '<div class="hed"><h2>' + item + '</h2></div>';
html += '</li>';
});
html += '</ul>';
$('#exDiv').empty();
$('#exDiv').append(html);
}
},
error: function () {
alert('Error');
},
contentType: 'application/json'
});
$('a').click(function(e) {
e.preventDefault();
});
});
Apparently I also added e.preventDefault() but it still triggers the link to a new tab.
Link to e.preventDefault()
These are dynamically added anchor tags. They don't exist when you add the click event handler to the anchor tags. So when you click these anchors they are going to bypass your jquery event handlers and do what they normally do by default.(further explanation) You have the same code again inside the $.each function which might have worked if you had called it after your $('#exDiv').append(html); line. But again they still don't exist when you call it.
Depending on the version of jQuery you're using you should use either "on" or "live". If you are using a version 1.7 or higher use 'on'.
Try this:
$(function() {
$.ajax({
dataType: 'json'
url: '/lists',
success: function (data) {
if (data != null) {
var html = '<ul>';
$.each(data.apis, function (i, item) {
html += '<li class="res">';
html += '<div class="hed"><h2>' + item + '</h2></div>';
html += '</li>';
});
html += '</ul>';
$('#exDiv').empty();
$('#exDiv').append(html);
}
},
error: function () {
alert('Error');
},
contentType: 'application/json'
});
$(document).on('click', 'a', function(e) {
e.preventDefault();
});
});
If you're using 1.6 or ealier your click event handler should look like this:
$('a').live('click', function(e) {
e.preventDefault();
});

How can I prevent a click event from firing when I call "<element>.click()"? Or what's a better way to solve this issue?

$(function() {
$(".universeLink").click(function (e) {
e.preventDefault();
var link = this;
alert(link.id);
$.ajax({
type: 'GET',
url: "#Url.Action("IsUniverseCached", "Universes")" + "?universeId=" + (link.id),
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (returnedData) {
if (returnedData === false) {
alert(returnedData);
$("#" + link.id).empty();
$("#" + link.id).html("<div class=\"alert alert-warning\"><strong>Not cached</strong> — this data will take a while to arrive!</div>");
}
$("#" + link.id).click();
},
error: function () {
alert("Error");
}
});
});
});
I am building some JQuery to make a request before the original request is followed.
At the end of the success block, $("#" + link.id).click(); is called and the event is fired again. I tried something similar with (element).submit() on a form, and the .submit() event did not fire again, so I assumed I could do the same trick with .click().
Here's the HTML elements.
<a id="10" href="/Universes/ViewUniverse?universeId=10&regionId=8" class="universeLink">1</a>
(the ID is dynamically assigned)
Just redirect the browser to the new location. I.e. instead of using .click, assign to window.location.href:
window.location.href = link.href;

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