In my parent.htm there's a dropdown list, which is filled dynamically from the database using a JQuery function updateMyList() in parent.js.
If the user wants to add another option to the list, the form child.htm is loaded inside <div id="overlay"> of the parent.htm. To insert new data an AJAX request is called from child.js, which is included in child.htm.
If the request was successful, child.htm is unloaded via $("#overlay").html("") from child.js. When this happens, i'd like to call parent.js's updateMyList(), but i can't find a way to trigger it.
Using opener from inside child.js didn't work (TypeError: opener is null) and i can't find a way to tell if $("#overlay").html() has been changed back to "".
Any help would be greatly appreciated!
Sorry if this is a double post, i'm running out of ideas for search terms...
edit: here's a simplified code:
parent.htm:
<head>
<script type="text/javascript" src="js/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="parent.js"></script>
<script>
$(document).ready(function () {
$('#new-option').click(function(){
$("#overlay").load("child.htm");
});
});
</script>
</head>
parent.js:
$(document).ready(function(){
function updateMyList(){
//send AJAX and write options
});
// and do much more...
});
child.htm:
<head>
<script type="text/javascript" src="js/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="js/child.js"></script>
</head>
child.js:
$(document).ready(function(){
// do more stuff
$('#save-option').click(function(){
$.post("./inc/savenewoption.php", {
//save user entries
}, function(data){
alert(data);
})
.done(function() {
updateMyList(); // <- this won't work
$("#overlay").html("");
});
});
});
It doesn't work because updateMyList() is inside a different function (one of your $(document).ready() ones). In my experience the only reason you put code into a $(document).ready() function is because Javascript can fire before the document has completely loaded. Trying to fire Javascript on elements before they are in the document will cause errors.
The updateMyList() function doesn't fire until the ajax request is complete, so it should be safe to have it located outside $(document).ready().
Related
I asked half this question already but as i began debugging and messing around with code i noticed some other issues. On my website, http://www.yokaproject.com/, for arguments sake this is what i want you to do. Click on the art tab first, youll notice two logs to the console one for script length, other is ajax call, 5 and 1 respectively. I dont understand why it logs 5, i have 4 known scripts. Then click the next tab, music, it will log 8 twice for script length, and ajax call twice, why? Further it will keep adding in this pattern. I have this very simple request, please work with me on this. Im not saying write code for me or give me everything, just help direct me so i can actually learn my mistake and how to correct it. In fact i would even chat with someone and work on this issue, i just really want to write better JS. That being said here is my code(ignore my script check function meant to comment that out):
*This is just my ajax function, please check my website to see further details, http://www.yokaproject.com/index.html
function handlersAttached(){
$('.header a').on('click', ajaxLoad);
}
handlersAttached();
function ajaxLoad(e) {
console.log($("script").length);
console.log("ajax called");
e.preventDefault();
var url = $(this).attr("href");
var that = $(this);
that.off('click'); // remove handler
$.ajax({
url: url,
dataType: "html",
type: "GET",
cache: false
}).done(function(data){
$("#container").html(data);
})
};
At the first click $(scripts) returned following tags:
<script async="" src="https://www.google-analytics.com/analytics.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="../assets/instafeed.js-master/instafeed.min.js"></script>
<script type="text/javascript" src="../assets/load_scripts.js"></script>
<script>/*google analytics stuff*/</script>
At the next one the following:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="../assets/instafeed.js-master/instafeed.min.js"></script>
<script src="../assets/load_scripts.js"></script>
<script async="" src="https://www.google-analytics.com/analytics.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="../assets/instafeed.js-master/instafeed.min.js"></script>
<script type="text/javascript" src="../assets/load_scripts.js"></script>
<script>/*google analytics stuff*/</script>
It seems that first three of them are appending to DOM tree every time your ajax call performed. Furthermore, load_scripts.js is among them itself, so next clicks will produce more ajax calls and more triggered handlers with console.log respectively.
Solution: do not include scripts in ajax response or, at least, do not append them to DOM tree. Depends on what you're trying to achieve :)
So, lets say you have a page that wants to load from a javascript file and it includes
temp.html file
<script src="example.js"></script>
<p class="one"></p>
Now in the example.js file you have a function that is
function getInfo() {
var place = "foo"
$(".one").html(place);
}
//Edit currently I call the function inside the JS file
getInfo();
My question is how would you connect the two files so that the external javascript file knows that it is pointed to the paragraph with the class one?
Normally when this is in a single page, you would call the function and the info will be set.
I have seen a getScript method and a load method for Jquery. Would that be applicable here?
Any ideas on how to approach this? If you provide some code that will be super helpful.
Thanks in advance.
Looks like you want to execute getInfo() as soon as it's defined (i.e.: example.js is loaded).
You can try this approach:
<script src="example.js" onload="getInfo();"></script>
In your example.js, change getInfo() to something like this:
function getInfo() {
$(document).ready(function() {
var place = "foo"
$(".one").html(place);
});
}
Your language is confusing, but you could use jQuery's $(document).ready function which would suffice. Generally speaking, an externally loaded file should execute where the tag is in the script.
A hack could be to place a tag before the end of your document body, give it an id, and then use $('#id').ready() there. In general though, you could just try coding the transclusion concept (I'm guessing you're used to this) from scratch using intervals and timeouts.
<div id="rdy">
</div>
</body>
Then in your file:
$('#rdy').ready(getInfo);
Just my added opinion, you should consider that Google is up to some not-so-nice things these days, they are long-gone from the "do no evil" mantra.
If we assume you have a JavaScript file that contains this content:
function getInfo() {
var place = "foo"
$(".one").html(place);
}
then your markup will look something like this:
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="example.js"></script>
<script>
$(function(){
getInfo();
});
</script>
</head>
<body>
<p class="one"></p>
</body>
</html>
$(function(){ ... }); is just the simplified version of $(document).ready(function(){ ... });. They both more or less handle the onload event, which fires when page has finished loading.
I want to execute php file in javascript function. Code is as shown below:
<a id="cancel" href="./?&_action=list" onclick="javascript:clearRecord();return rcm.command('list','',this,event)">Cancel</a>
<script language="javascript" type="text/javascript">
var u1='michael';
function clearRecord() {
$(function() {
location.href = 'clear.php?h='+u1;
});
}
</script>
But when I click to cancel button, clear.php not executed. How I should come out from this?
full & working answer to your question:
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script language="javascript">
function cancelClicked() {
// function below will run clear.php?h=michael
$.ajax({
type: "GET",
url: "clear.php" ,
data: { h: "michael" },
success : function() {
// here is the code that will run on client side after running clear.php on server
// function below reloads current page
location.reload();
}
});
}
</script>
</head>
<body>
<a id="cancel" href="#" onclick="cancelClicked()">Cancel</a>
</body>
</html>
if you want to just execute some php and leave current page to the one generated by this php script. then you got it almost right.
I do not see that you are using jquery - so skip this "$(function(){})" part, and i don't see what u1 is added for but this will work:
function clearRecord() { location.href = 'clear.php'; }
and this will do the same:
Cancel
BUT if you want only to run "clear.php" and then reload current page.
One way of doing it can be putting at the end of your "clear.php" file something like:
header("Location:/");
(it will work only if clear.php does't write anything in response).
But you can do it other ways:
- using AJAX - call clear.php with jQuery.get() and call location.reload() on success;
- using IFRAME - set iframe's location to clear.php and then call window.location.reload();
- using IMG - set img.src to clear.php ...
...and possibly many other ways :)
I am creating an application that may become very large over time. So in order to keep things simple, we have decided to keep Javascript (mostly jQuery code), CSS and html for one particular feature in one file. for example, if upload is a function, then we have all the jQuery validation and css, html for upload in one file (without head and html tags).
We have a home dashboard in which a click handler will load all the links by ajax and append to the designated DIV of class indicated by additional attribute in links called "whereTOadd". so if a link has its "WhereTOadd" attribute set to ".here" and href set to upload.php then the contents of upload.php will be added to a div of class 'here' in the same page. it is done using script given below.
But the problem i am facing is that I need to include jQuery file again in every file to get the codes working, which is a terrible thing. What can be done to avoid this?
This is html of my dashboard:
<html>
<head>
..
<script src="Path-to-jquery-min-file.php" ></script>
<script>
$( document ).ready(function(){
$(document).on("click","a",function(e){
if( $(this).attr('href'))var ajaxurl = $(this).attr('href').valueOf();
if( $(this).attr('whereTOadd'))
var target = $(this).attr('whereToadd').valueOf();
/*for ajax request */
var options= {
type: 'GET',
url: ajaxurl,
dataType: 'html',
success: function (html, textStatus){
$(target).empty().append(html);
},
error: function(xhr, textStatus){
alert('error');
}
}
$.ajax(options);
return false;
});
});
</script>
</head>
<body>
<a href="upload.php" >Upload data</a>
<div class=".here" ></div>
</body>
upload.php contains:
<script type="javascript" >
$('body').append('load successful!');
</script>
This setup will not work until I make change in upload.php as:
<script src="Path-to-jquery-min-file.php" ></script>
<script type="javascript" >
$('body').append('load successful!');
</script>
Please help in solving this because loading jQuery again and again in the same page may cause errors and conflicts. Please suggest me a better approach to what I am doing.
Thanks
I've been sifting around the web trying to find out whats going on here and I have not been able to get a concrete answer.
I have one $(document).ready on my site that seams to run multiple times regardless of the code that is inside it.
I've read up on the bug reports for jQuery about how the .ready event will fire twice if you have an exception that occurs within your statement. However even when I have the following code it still runs twice:
$(document).ready(function() {
try{
console.log('ready');
}
catch(e){
console.log(e);
}
});
In the console all I see is "ready" logged twice. Is it possible that another .ready with an exception in it would cause an issue? My understanding was that all .ready tags were independent of each other, but I cannot seem to find where this is coming into play?
Here is the head block for the site:
<head>
<title>${path.title}</title>
<meta name="Description" content="${path.description}" />
<link href="${cssHost}${path.pathCss}" rel="stylesheet" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript" charset="utf-8"><!----></script>
<script src="media/js/fancybox/jquery.fancybox.pack.js" type="text/javascript" ><!-- --></script>
<script src="/media/es/jobsite/js/landing.js" type="text/javascript" ><!-- --></script>
<script src="/media/es/jobsite/js/functions.js" type="text/javascript"><!-- --> </script>
<script src="/media/es/jobsite/js/jobParsing.js" type="text/javascript" charset="utf-8"><!----></script>
<script src="/media/es/jobsite/js/queryNormilization.js" type="text/javascript" charset="utf-8"><!----></script>
<script src="${jsHost}/js/jquery/jquery.metadata.js" type="text/javascript" charset="utf-8"><!----></script>
<script src="${jsHost}/js/jquery/jquery.form.js" type="text/javascript" charset="utf-8"><!----></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.7/jquery.validate.min.js" type="text/javascript" charset="utf-8"><!----></script>
<script src="${jsHost}/js/jquery.i18n.properties-min.js" type="text/javascript" charset="utf-8"><!----></script>
<script type="text/javascript" charset="utf-8">
function updateBannerLink() {
var s4 = location.hash.substring(1);
$("#banner").attr('href','http://INTELATRACKING.ORG/?a=12240&c=29258&s4='+s4+'&s5=^');
}
</script>
</head>
Pay no attention to the JSP variables, but as you can see i'm only calling the functions.js file once (which is where the .ready function exists)
The ready event cannot fire twice. What is more than likely happening is you have code that is moving or manipulating the element that the code is contained within which causes the browser to re-execute the script block.
This can be avoided by including script tags in the <head> or before the closing </body> tag and not using $('body').wrapInner();. using $('body').html($('body').html().replace(...)); has the same effect.
It happened to me also, but I realized that the script had been included twice because of a bad merge.
This happened to me when using KendoUI... invoking a popup window would cause the document.ready event to fire multiple times. The easy solution is to set a global flag so that it only runs once:
var pageInitialized = false;
$(function()
{
if(pageInitialized) return;
pageInitialized = true;
// Put your init logic here.
});
It's sort of hack-ish, but it works.
Make sure you don't include JS file twice. That was my case
You might consider to use
window.onload
instead of
$(document).ready
try putting this in your functions.js to prevent it from being executed twice :
var checkit = window.check_var;
if(checkit === undefined){ //file never entered. the global var was not set.
window.check_var = 1;
}
else {
//your functions.js content
}
however i suggest that you look more into it to see where are you calling the second time.
I had a similar problem when I was trying to refresh a partial. I called a return ActionResult instead of a return PartialViewResult. The ActionResult caused my ready() to run twice.
There is a possibility to encounter this problem when you add same controller twice in the html.
For an instance:
[js]
app.controller('AppCtrl', function ($scope) {
$(document).ready(function () {
alert("Hello");
//this will call twice
});
});
[html]
//controller mentioned for the first time
<md-content ng-controller="AppCtrl">
//some thing
</md-content>
//same controller mentioned again
<md-content ng-controller="AppCtrl">
//some thing
</md-content>
I had a similar issue today. A <button type="submit"> caused the $(document).ready(...) event to fire again in my case. Changing the code to <button type="button"> solved the issue for me.
See document.ready function called again after submit button? here on stackoverflow for more details.
In my case $(document).ready was firing twice because of bad CSS, check if any part of your CSS has background-image: url('');
If the iframe doesnt show anything and is used for other reasons (like uploading a file without reload) you can do something like this :
<iframe id="upload_target" name="upload_target" style="width:0;height:0;border:0px solid #fff;"></iframe>
Notice that src is not included that prevents the second on ready trigger on the document.
I had this problem with window.load function was executed twice:
The reason was because I had reference to the same javascript-file in the main page as well as a .net usercontrol. When I removed the reference in the main page, the load-function was only executed once.
I had this happen to me this morning... and what I discovered after closely examining some html code in a jquery modal form that I had recently manipulated, that I'd accidentally removed a closing table tag. I haven't taken the time yet to fully understand why that caused the document.ready function to be called twice, but it did. Adding the closing table tag fixed this issue.
jQuery JavaScript Library v1.8.3 (yes, it is a legacy app)
My problem was that I had tags referencing my JS file in both my index.cshtml file AND my _Layout.cshtml. This was causing the document.ready function to fire twice, which was causing DataTables to bomb.