Locally defined JavaScript Functions works in All Page - javascript

I am using PHPAjax Version of SmartAdmin Template,
in which i am writing some script for specific page,
$(document).on('change', '#vehicle_id', function(){
var vehicle_id = $('#vehicle_id').val();
var url = '<?php echo site_url('processor/#../tyres/check_current_km/'); ?>'+vehicle_id;
window.location.href = url;
});
but it works on every page, suppose i have defined this function on a.php, it also works on b.php

Your listener is implemented on the document, so most likely both the pages are included/ rendered in the same document and hence the script is applied to the complete document.
If you would like to constraint your script to one page then create page specific unique id and apply listener on that. e.g.('#pageA-vehicle_id').

Related

Use javascript (and jQuery and other libs) from parent document on iframe with several sources

good day all.
I'm working on a project in which there is an application that has one of its view implemented with an iframe, the iframe src is changed when the user clicks on some of the "parent" document. So basically there is always the same container, but the contents of the iframe will change according to the user choices.
let's say that there will be:
parent.html (which will have all the js logic)
child1.html
child2.html
...
each "child" page will be an html page with no (or very little) javascript. What I want to obtain is that when the user arrive on the child1.html, only the code that is global to every child is execute and of course also the code related to that page.
Let's say that on the child1.html there must be executed a couple of ajax calls, then some js to handle tables, and things like that. while on the child2.html there will be some forms whith their own validations, and another ajax call to send the forms (displayed on the child1.html).
There will be a big js library on parent.html that will contain the js code of every child page, so what I'd like to have is a way to "know" in which page I am and execute only the portion of code that is related to that page.
the structure should be something like:
var myGlobalObject = {username:undefined,foo:1}
if(childpage1.html){
if (myGlobalObject.username == undefined){
$.ajax(retrieve username);
$("#someTableIniFrame",iframeContext).doSomething();
}
}
if(childpage2.html){
$("body",iframeContext2).on("submit","#someFormOnChild2", function(){
//do something
});
}
and/or something on childpages that could execute only its code... like:
document.addEventListener("DOMContentLoaded", function(event) {
//execute only my part of the global js!
});
I hope to have been clear on what I'd like to obtain:
a parent page, with all the js used in childs, executed on demand OR with the capability to understand in which page we are.
several child page without or with a very little js.
Just for information, the iframe src will be changed by js on the parent page, by destroying the previous one and adding a new iframe with the new source.
If you want to keep all the Javascript in the parent page then you just really need a way to map the child pages to any code you wish to execute. This is a long way around doing something, but without further context it's difficult to suggest a more appropriate solution.
With that in mind, here's how I'd approach your problem.
First of all, I'd create an array of objects that defines what script to run for each child page...
var childScripts = [{
"src": "childpage1.html",
"init": function() {
// what to do when childpage1 is loaded
}
},
{
"src": "childpage2.html",
"init": function() {
// what to do when childpage2 is loaded
}
}];
Don't destroy and recreate the iFrame every time you want to load a new page, or (if you really have to), assign an event handler to the load event every time. You only have to do this once if you never destroy the iFrame...
$("#iframeId").on("load", function() {
var scriptInfo = childScripts.filter(function(childInfo) {
return window.location.href.slice(-childInfo.src.length) === childInfo.src;
});
for (var i in scriptInfo) {
scriptInfo[i].init();
}
});
Obviously replace the selector #iframeId with something that will find your iframe.
In short, you create an array that holds each child page filename (prefix with / so you don't run scripts on pages that end with the same thing, but aren't the same page), and a function that you want to execute when that page loads. You then parse that array each time the iframe is loaded and execute all associated functions. Realistically you'll only have 1 init function per child page, but that code will handle multiple instances.

Using $.getScript (jquery): code is not executed

I am working on updating my website, which now uses an AJAX engine. My engine works well, up-to-hand for some reason some pages do not execute javascript, let me explain: when the anchor change I use $.get for data recovery. The pages have this structure:
title
h1
script1.js,script2.js,etc.js
style1.css,style2.css,etc.css
<!--there's the page's content-->
It appears reload the page solves the problem, but i don't understand what is different. In the previous code, the engine runs successfully, reloaded or not:
$.getScript("script1.js");
$.getScript("script2.js");
$.getScript("etc.js");
In addition, a php generated script contains user's current state under an Object form:
$(function(){
user = new Object();
user.id = user.logged = <?php echo $user->getId();?>;
user.nick = "<?php echo $user->getNick();?>";
user.mail = "<?php echo $user->getMail();?>";
user.logout = function(){
};
});
The $.getScript request is successful, but the user object is not changed. The script, however, has yet been modified. And it don't works from console too.
The update is currently online at v2.wawolf.com, you'll find everything you need.
Hotlink: Engine's code
I just solved my problem: when all document is loaded, $(function(){}) will not work again, so calling a script which uses $(function(){}) will no get run. I removed it from all my secondary-called scripts and now all works perfectly!
it might just be a loading order issue.
try encapsulating the JS loading in an onload function
$(window).load(function(){
//get script loads here
}
or
$(document).ready(function() {
//get script loads here
}
Sometimes I use one inside the other for dynamic JS script that needs to be loaded last.

How can I load javascript when needed into a single page ASP.NET MVC4 web site?

I have the following code that loads a login page into my
single page web site when a user clicks on the login button. The href in this case calls a MVC4 controller and this returns a partial view with the HTML.
$('#loginLink')
.click(function () {
var $link = $(this);
var href = $link.attr('data-href');
$('#article').load(href);
}
return false;
});
But I also need to have some additional Javascript loaded
from the server. Can someone tell me how I can do this as the page is loaded. Rather than at the start when all my javascript is loaded into the browser.
Here's my MVC4 code for the login page:
#model WebUx.Models.LoginModel
<section id="content" class="grid_9">
........
</section>
#Scripts.Render("~/bundles/jqueryval")
Here's the C# code for the javascript bundle:
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*"));
Even if the scripts render then it seems they are not added to the web page when I check with the chrome developer tools. Ideally I don't want them to be inline. I would like them loaded as normal js that the browser can check against its js cache.
The scripts are actually added. In your particular case you are adding the jquery unobtrusive validation scripts and I guess that they do not work for you because you haven't called the $.validator.unobtrusive.parse method once you injected the new contents into the DOM:
So make sure that you have registered all newly added elements to the DOM with the unobtrusive validation framework:
$('#loginLink').click(function () {
var $link = $(this);
var href = $link.attr('data-href');
$('#article').load(href, function() {
$('form').removeData('validator');
$('form').removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse('form');
});
return false;
});
To execute code you load with ajax, you can create a new tag with the code, and add it to the page. For instance :
$("#article").append("<script type='text/javascript' src='script.js'></script>");
should execute the content of "script.js" (provided there is an element with the id "#article" in the page).
In IE the tag has to be added to the page at the moment you want the script to be run (you can't just use .load on a script tag).

jquery fail on DOM modify made with html()

In my website, I build the page navigation based on hashchange:
var hashHome;
$(window).bind( 'hashchange', function(e) {
var homeClass = "home";
var url = $.param.fragment();
if($('#page-content').hasClass(homeClass)){
hashHome = $('#page-content').html();
}
if(url ==''){
//homepage with nothing(no hash)
if(!$('#page-content').hasClass(homeClass)){
//alert("load frim cache ->#"+url);
$('#page-content').addClass(homeClass);
$('#page-content').html(hashHome);
}
}else{
//go to some page
if($('#page-content').hasClass(homeClass))
$('#page-content').removeClass(homeClass);
initAction(url);
}
})
$(window).trigger( 'hashchange' );
When the site loads its homepage, the homepage gets stored in hashHome. If user navigates away, the initAction(id) replaces the entire $('#page-content')'s content with other pages' content. When the uses navigates back to home, it restores the stored home back to the $('#page-content').
My problem is that all of the jQuery stopped working on the homepage.
I've read about live() already but it seems that it needs a event like click() for it to work. How do I fix this?
I figured out that i need to store my entire page before i change the content of the div that is surrounding it
var content$('#page-content').html();
then do the content change
that way, when i reinitialize all my jQuery plugins, they will loose all of their old reference and use the new content variable, instead of a double initialization
and finally, i've the original question's code also won't work since the script tag look like this: <script type="text/javascript">...</script>, IE for some reasons won't recognize this, so I have to change it to <script></script> in order to make it cross browser compatible

jQuery code repeating problem

I have a piece of code in jQuery that I use to get the contents of an iFrame after you click a link and once the content is completed loading. It works, but I have a problem with it repeating - at least I think that is what it is doing, but I can't figure out why or how.
jQuery JS:
$(".pageSaveButton").bind("click",function(){
var theID = $(this).attr("rel");
$("#fileuploadframe").load(function(){
var response = $("#fileuploadframe").contents().find("html").html();
$.post("siteCreator.script.php",
{action:"savePage",html:response, id: theID},
function(data){
alert(data);
});
});
});
HTML Links ( one of many ):
<a href="templates/1000/files/index.php?pg=0&preview=false"
target="fileuploadframe" class="pageSaveButton" rel="0">Home</a>
So when you click the link, the page that is linked to is opened into the iframe, then the JS fires and waits for the content to finish loading and then grabs the iframe's content and sends it to a PHP script to save to a file. I have a problem where when you click multiple links in a row to save multiple files, the content of all the previous files are overwritten with the current file you have clicked on. I have checked my PHP and am pretty positive the fault is with the JS.
I have noticed that - since I have the PHP's return value alerted - that I get multiple alert boxes. If it is the first link you have clicked on since the main page loaded - then it is fine, but when you click on a second link you get the alert for each of the previous pages you clicked on in addition to the expected alert for the current page.
I hope I have explained well, please let me know if I need to explain better - I really need help resolving this. :) (and if you think the php script is relevant, I can post it - but it only prints out the $_POST variables to let me know what page info is being sent for debugging purposes.)
Thanks ahead of time,
Key
From jQuery .load() documentation I think you need to change your script to:
$(".pageSaveButton").bind("click",function(){
var theID = $(this).attr("rel");
var lnk = $(this).attr("href");//LINK TO LOAD
$("#fileuploadframe").load(lnk,
function(){
//EXECUTE AFTER LOAD IS COMPLETE
var response = $("#fileuploadframe").contents().find("html").html();
$.post("siteCreator.script.php",
{
action:"savePage",
html:response,
id: theID
},
function(data){alert(data);}
);
});
});
As for the multiple responses, you can use something like blockui to disable any further clicks till the .post call returns.
This is because the line
$("#fileuploadframe").load(function(){
Gets executed every time you press a link. Only add the loadhandler to the iframe on document.ready.
If a user has the ability via your UI to click multiple links that trigger this function, then you are going to run into this problem no matter what since you use the single iframe. I would suggest creating an iframe per save process, that why the rendering of one will not affect the other.

Categories

Resources