Calling JS function from PHP not working - javascript

Using a method recommended by a user in a previous question I used just one document (index.php) to show different contents instead of creating one file for each one.
This is the code:
HTML
Home
More info
Contact Us
<div id="index">...index content...</div>
<div id="more_info">...more info content...</div>
JS
$(document).ready(function(){
function more_info(){
$('#index').hide();
$('#more_info').show();
}
});
PHP
<?php
if (isset($_GET['id_page'])) {
$id = $_GET['id_page'];
if ($id == 1) {
?>
<script>
more_info();
</script>
<?php
}
}
?>
That's not working. But if I change <script> more_info(); </script> for:
<script>
$(document).ready(function(){
$('#index').hide();
$('#quienes-somos').show();
});
</script>
It works. Why is this?

It looks like the problem you are having is because you are defining your more_info function inside of a function. This takes it out of the global scope which will not make that function accessible anywhere except for inside of your document ready function.
//more_info is now available globally
function more_info(){
$('#index').hide();
$('#more_info').show();
}
$(document).ready(function(){
//document ready code here
});
This should make the more_info execute when you output the JS function from PHP. Also it is good to note that since you are not executing the function on ready you will need to make sure the html is available for the JS to modify it. It is normally best practice to put all your JS just before the closing tag. This will ensure your html loads as quickly as possible and your JS will always have access to the HTML you are attempting to edit. With the JS in the head tag you need to make sure your JS is being called at the correct time using:
$(function() {
});
OR
$(document).ready(function() {
});
OR
$(window).load(function() {
});
All of these methods execute at different times during page initialization. With JS in the head tag your browser will need to download all the JS to the client before it can begin to render the HTML which will also add to time between going to the site and actually seeing the site.

Related

javascript wont find the id/class of html/javascript imported code with XMLHttpRequest

i´m building a search system for this petshop software web base, the thing is that i search for a name, than send the name with XMLHttpRequest to php page that execute the query and return me the results and display them at my search page,until here is ok. the information that php page returns to search page goes like this:
<?php
$query = "selec ...
$queryName = mysqli_query...
while($fetchNames = mysqli_fetch_array...
?>
<a class="profile">
<div id="clientInfo"><?php echo $fetchNames[0]; ?></div>
</a>
<?php }
?>`
i try to acess the html class .profile imported on searchpage.php:
`<script>
document.querySelector('.profile').addEventListener('click',function=(){
alert('js code works!');
});
</script>
</body>`
i tryed to import it with the results of php query page right after the end of while loop, even with the window.onload=func... it won't work!
javascript won't work at the imported document, it can't see the class to display the alert. how can i work around this issue?
thanks in advance!
As you have dynamically-generated elements, you'll need to make use of event delegation and target an element that exists on page load, and work down from there. You haven't mentioned any parent elements in your question, so I'll target <body> in my answer, as this always exists on page load.
As you're shifting the eventListener up the hierarchy, you need to ignore clicks other than the desired element. This can be achieved with event.target and .contains():
if (document.querySelector('.profile').contains(event.target)) { }
So your final code would look like:
const body = document.querySelector('body');
body.addEventListener('click', function() {
if (document.querySelector('.profile').contains(event.target)) {
alert('js code works!');
}
})
The above ensures that when you click on your dynamically-generated elements your alert() will fire, but it won't fire when you click on any other element.
I can suggest two different methods. The first one is that you can write javascript codes after the html code. or wait for the document to be loaded using 'document.addEventListener('DOMContentLoaded', ...)'
document.addEventListener('DOMContentLoaded', function() {
document.querySelector('.profile').addEventListener('click',function=(){
alert('js code works!');
});
})

including a javascript file at the end of the file doesn't work for some functions

In my file, a have many dom elements and an external javascript file that has some functions to manage events. The problem is that when i include the functions.js file at the end of my main file:
<script src="functions.js"></script>
That works for some elements but not for others. So i move that at the top of my file, and now it works for some elements but not the other either.
It doesn't works means that i got such error in the web console:
ReferenceError: oneOfMyFunctions is not defined
What is the best place to put that include? Thanx in advance.
EDIT:
In my html file (the main file), i did this:
<script>
window.onload = function(){
// start calling your function eg. functions.j();
myFunction();
};
</script>
Still get the same issue.
You can put your JavaScript file anywhere in page. But you should use window.onload method to start execution of your code.
<script>
window.onload = function(){
// start calling your function eg. functions.j();
};
</script>
If you invoke the function before its loaded, it doesn't know what to do. There are two solutions to this:
Use the window.onload option (or jquery $(document).ready(function(){ ... });
make the function call after you load the scripts.

How can I fire jQuery outside document.ready block?

The common method of starting jQuery is putting it in
$(document).ready(function() {
// put all jQuery stuff here
});
But what if I have a complicated site which uses basic jQuery in <head> and some custom functions that depend on the page type (e.g. if I have login page, fire some login ajax stuff).
So, how can I attach code to $(document).ready() or fire it later? Which JS syntax should I use?
Thanks for help!
My page structire is similar to this:
Display static header using PHP's include()
Add content inside <body></body>
Display the template footer
<?php
include_once('system/classes/class.display.php');
$d = new IFDisplay();
$d->display_header(array('subtitle' => 'Log In')); <-- Here it displays static
head tags. There is
document.ready in there.
I can't change it.
?>
<script type="text/javascript">
AND WHAT DO I NEED TO PUT HERE
</script>
<div>...</div>
<?php
$d->display_footer();
?>
If you aren't worried about race conditions, you should be able to use this:
$(function(){
//put your code here
});
As many times as you like.
If you have a block of code that you want to be able to run BOTH in a $(document).ready() function and sometime later like when an ajax call completes, then you can just define a function and call it both places like this:
// define this in the global scope or some other publicly available scope (not inside a document.ready() call).
function myOperation() {
// put your code here
}
$(document.ready(function() {
myOperation();
});
And, then sometime later (like in an ajax call in your other code), you can call that same function with this:
myOperation()

AJAX that calls a "parent" function

I've seen a few questions like the one I'll ask but nothing identical. I have two html files, main and today. What I want to do is load today.html via AJAX into a child div in main.html. Sometime after load, I would like to call a function that resides in main.html from today.html
Within Main I have this function:
function drawCircle (size){
alert('DRAWING');
}
This AJAX load:
$("#leftofad").ajax({
url: ":Today.html?r="+genRand(),
type: 'GET',
success: function(data) { },
error: function() { alert('Failed!'); },
});
And this div:
<div id="leftofad"></div>
In Today.html I have
<script type="text/javascript">
$(document).ready(function(){
drawCircle (100);
});
</script>
The load is going well but Today.html doesnt seem to recognize the drawCircle function. I've tried several precursors including this., window., and parent..
I understand that I can use the callback method of the AJAX loader in jQuery but I don't necessarily want to call drawCircle when the load is complete. I may want to wait a bit or do it as a result of an action from the user. Is it possible to reference these functions from an AJAX-loaded div? If not, can I use an alternative method like events and listeners to fire the drawCircle function?
Since you will be loading JS into your page, try calling the function directly?
(The ready function won't run as the main page is already loaded)
Main.html
<script type="text/javascript">
function drawCircle(size) { alert("DRAWING" + size); }
$(function() {
$("#leftofad").load("Today.html?r="+genRand(), function() {
alert('loaded successfully!');
});
});
</script>
<div id="leftofad"></div>
Today.html
<script type="text/javascript">
drawCircle(100);
</script>
If this doesn't work, I strongly suspect that JavaScript returned in an AJAX call is not executed.
In this case, refer to: How to execute javascript inside a script tag returned by an ajax response
$("#leftofad").ajax is not proper.
jQuery's $.ajax function does not use a selector.
What you can use is load:
$("#leftofad").load("Today.html?r="+genRand(), function(){
alert('loaded successfully!');
});
Everyone here has some good answers, but I believe there is a knowledge gap and we are missing some information. If I were you, I would add an alert to the script in the Today.html file right before the drawCirle. Then I would run this page using IE or Chrome dev tools or Firebug in Firefox. When the alert is displayed you can put a breakpoint in the javascript code. Then check your global scope to try and locate drawCirle...
Sorry this is not an exact answer, but with javascript files you need to use debugging tools for this.
while there isn't really a document.ready function for a div, there is a hack that works just as if so:
create your returning data as a full html page:
<html>
<head>
<script type='text/javascript'>
$(document).ready( function () {
do-this;
to-that;
....
});
</script>
</head>
<body>
<%
your possible vbscript
%>
the rest of stuff to be loaded into that div
</body>
</html>
Then, you can have as many cascading div loading from different page loading and .... rinse and repeat ... forever .... EXPERIMENT with different DOCTYPE to see the different results.
EDIT:
Then, of course, you load the original MAIN with
$('#thedivid').load('url-of-the-html-returning-page');
Which, in turn, can have the VERY SAME call in the returning page document.ready as, for example; $('#thedivid-inthereturningdata-html-page').load('url-of-the-html-of-the-child-process-for-whaterver); .... and so on.
Go ahead, PLAY AROUND and make wonderful ajax based applications ....

jQuery not working in external JavaScript

I am new to jQuery and am stuck at some strange issue. I am using jQuery's change and click methods. They are working fine when used in my HTML file in the <script> tag.
Like:
<script>
$("select,input").change(function ()
{
// My code and some alerts
});
</script>
When I copied the same in external JavaScript code without <script> and imported that in my HTML it was not at all working.
Are there any changes which are needed to use jQuery in external JavaScript code?
PS: Some other non-jQuery functions present in same external JavaScript code are successfully called from HTML.
First off, you don't want a <script> tag in an external JavaScript file, if that's how I'm reading your post.
The trick with jQuery is that your code is set to execute immediately.
You want to wrap your script so that it loads when the document is ready, in something like:
$(document).ready(function(){
$("select,input").change(function ()
{
// My code and some alerts
})
});
And you want to make sure that your file is loaded after jQuery (otherwise the $ global will not be set).
Additions:
Here is what your HTML should look like:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript" src="jscript/myExternalJs.js"></script>
Here is what your JavaScript code should look like (note there is no script tag inside the JavaScript file):
$(document).ready(function(){
$("select,input").change(function ()
{
// My code and some alerts
})
// Other event handlers.
});
As far as your other script... it sort of depends on what you're doing. The most important thing is to not try to hook event listeners up to objects that don't yet exist, which is why we use document.ready.
Did you make sure jquery is defined before your own jquery code?
You should also make sure the DOM is ready when dealing with jquery:
$(document).ready(function() {
$("select,input").change(function() {
// my code and some alerts
});
// more code here if needed, etc.
});

Categories