How to get previous defined variables with .load() - javascript

index.php
<script>
var example = 1;
$("#example-div").load("external.php");
</script>
<div id="example-div"></div>
external.php
<script>$("example-div").innerHTML("BlaBla " + example);</script>
Hi,
I am currently loading content from another file into my index.php with the load() function of JQuery to load images only then when I want it for example.
Now I am using a database connection which i define in my index.php. When I load the external content now, the code I load doesn't now all the variables I defined previously in the index.php, although it's part of index.php after loading them.
Is there a way to let the loaded content now all the previous stuff?
Thanks y'all!

You want to use session cookie to save data in php and for javascript you want to use cookie then use cookie and session any page
for php
https://www.w3schools.com/php/php_sessions.asp
https://www.w3schools.com/php/php_cookies.asp
for javascript
https://www.w3schools.com/js/js_cookies.asp

Jquery have some callback function executed when the load is finish, you can execute the script in external.php in this callback function, because at the moment your function will be execute, the content is in the DOM and it should work.
var example = 1;
$("#example-div").load("external.php", function() {
$("#example-div").innerHTML("BlaBla " + example);
});
It's a bit strange for me to use a script from the page you loaded to perform some task in the current document.

I don't know what you are trying to do. But your code is working, just small mistakes. Do it as follows -
index.php
<div id="example-div"></div>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script>
var example = 1;
$("#example-div").load("external.php");
</script>
external.php
<script>$("#example-div").html("BlaBla " + example);</script>
This gives the output
BlaBla 1

Related

Is it possible to include a javascript function call into php?

I am stuck with this issue. I have a js function into a scripts.js file:
var userLoggedIn;
function openPage(url) {
if(url.indexOf("?") == -1) {
url = url + "?";
}
var encodedUrl = encodeURI(url + "&userLoggedIn=" + userLoggedIn);
$('#mainContent').load(encodedUrl);
}
I call the javascript function from a php file like this:
<?php
//This file should check if the requested url is sended by AJAX or it's manaually typed by the user into the browser
if(isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
include 'includes/config.php';
include 'classes/Artist.php';
include 'classes/Album.php';
include 'classes/Song.php';
} else {
include 'includes/header.php';
include 'includes/footer.php';
$url = $_SERVER['REQUEST_URI'];
echo "<script>openPage('$url')</script>";
exit();
}
?>
It works fine when it's called from an onclick event into the HTML document, but it doesn't works when I enter manually the url. It prints a string into the screen. However this code is taken from some sample coding pages and it seems to work this way. What am I missing here?
Thanks in advance for the help and be patient... i'm a beginner on this!!
First of all you need to have the mentioned above js code loaded somewhere. Do you have it loaded in header or footer? (Directly or by loading your scripts.js?)
Be sure to have:
<script type="text/javascript" src="scripts.js">
Somewhere printed in your code. Do you have it in your footer or header?
Assuming that you have your js code in scripts.js now you can execute after page loads, but be sure print the <script> part WITHIN your <html>...</html>. So if you print out </html> in your footer.php then be sure to print:
echo "<script type="text/javascript">openPage('$url')</script>";
BEFORE loading of footer (but after loading of scripts.js);
While you learn a bit more you will get to know that actually it is a bad thing to execute code parts like that: you should separate your markup from code which executes things directly from it.
Modern frameworks will assist you with that, there is also defer attribute of the script element (https://www.w3schools.com/tags/att_script_defer.asp) which helps to execute the code after the page actually loads.
So, after reviewing all the code i found the problem. There was a missing ">" in the html closing tab. Now it works!! Thank you for your help!

Accessing external JS variable from inline html page?

How do you access the variable from an external JavaScript within a HTML page?
In my external JavaScript file(init.js), I created a variable call:
var myMessage="Hello World";
And in my HTML page which has init.js included but when I try alerting it:
alert(myMessage);
It gives me an error.
Sample code here
your codepen sample does not include the code as an external file but internally so that is an issue, but generally you need to wait for the page and all elements to finish loading.
The example bellow will wait 1000ms or 1sec and then you'll see that the alert will show the variable.
<div>
Body content
</div>
<script>
setTimeout(function() {
alert(myMessage);
},1000);
</script>
The better way is of course to use jQuery's
$('document').ready(function(){ });
instead of a timer as you can't be sure 1 second is enough. the connection might be poor and it could take more for all the pages to load.
If you dont want to use jQuery there are vanilla JS ways to do it as well.
pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it
You can call external js variable through making
var init={
myMessage="Hello World";
}
call your html code
alert(init.myMessage);

Calling JS function from PHP not working

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.

Initialize more than one html element using jQuery and Javascript

I have tried to lead my html element to fire my customized JS file's method.
Third textarea appears nicely.
First and second textareas does not effect any of the settings i am trying to change in myJSFile.js file.
Here's my problem : js file loads the last textarea nicely, but cannot initialize previous ones properly using my js methods.
I'm doing something wrong with my JS file, and i'd appreciate if you help me.
P.S. : Initalizing some plugin and working on CKEditor.
Here's my HTML file :
<textarea id="myTextAreaID" name="myTextArea"></textarea>
<script type="text/javascript" src="../public/js/myJSFile.js"onload="setTextAreaValues('myTextAreaID')"></script>
<textarea id="myTextAreaID2" name="myTextArea2"></textarea>
<script type="text/javascript" src="../public/js/myJSFile.js"onload="setTextAreaValues('myTextAreaID2')"></script>
<textarea id="myTextAreaID3" name="myTextArea3"></textarea>
<script type="text/javascript" src="../public/js/myJSFile.js"onload="setTextAreaValues('myTextAreaID3')"></script>
Here's myJSFile.js file
var textAreaID;
$(function(){
var myTextArea = $('#'+textAreaID);
//something is being loaded here, and it is loaded fine.
});
function setTextAreaParameters(param){
textAreaID = param;
}
Thanks in advance.
This is not very good idea to do it like this, however it's interesting to understand why it happens. In your code below you are defining global variable textAreaID:
var textAreaID;
$(function() {
var myTextArea = $('#' + textAreaID);
//something is being loaded here, and it is loaded fine.
});
function setTextAreaParameters(param) {
textAreaID = param;
}
This script is injected three times into document. After the last script tag the value of textAreaID variable will be myTextAreaID3, because it's global and the last setTextAreaParameters invocation will override previous. Remember that scripts are loaded synchronously in your case (no async or deferred attribute), it means that onload callbacks don't wait and immediately set textAreaID to new values.
However DOMContentLoaded event has not yet fired. This is the event you are subscribing with this code:
$(function() {
// DOMContentLoaded
});
When it eventually does - only the third textarea will be processed - the one with id myTextAreaID3.
Better approach would be to have only one script tag and set textareas the same className attribute:
<textarea id="myTextAreaID2" name="myTextArea2" class="editor"></textarea>
Then in the script probably have some sort of map with configuration parameters for each individual textarea.
You are including the same script three times, but the browser is probably smart enough to only load it once (no reason to load the same script on the same page more than once).
What you need to do is to include the script only once, say before the end of the body tag
...
<script type="text/javascript" src="../public/js/myJSFile.js"></script>
</body>
and then in the JS file, wait for the document to load, and handle all text areas accordingly:
$(function() {
$('textarea').each(function(i, j) {
console.log('do something for the ' + i + 'th text area');
});
})

how to load external javascript inside partial view dynamically?

I'm using jquery's .html() function to inject a html file into a partial div of the main page of my application. In the injected partial html page, there is a javascript reference such as script(src='../../javascripts/partialFunctions.js').
The jquery function and the main page are like:
$('.partialDiv').html(htmlResult);
<div>main page</div>
<div class='partialDiv'></div>
<input type='button'>button</input>
When the user click a specific button on the main application page, the jquery function will got called and the html file will got injected to the main page.
The problem is every time a new htm file got injected, the browser will load the script file. So there will be many duplicated javascript functions after the user clicked the button several times.
How can I do this dynamically and avoid the duplication of javascript functions?
Thanks in advance!
You can remove the script tags and references from the htmlResult page.
Then use $.getScript('myscript.js') to import the necessary JavaScript files.
More info on getScript() here
So to load in the script and make sure it only loads in once:
var window.foo = false; //Outside the document.ready
$('.partialDiv').html(htmlResult);
if(window.foo == false){
$.getScript("js/myScript.js", function(data, textStatus, jqxhr){
console.log('Script loaded');
window.foo = true;
});
}
I just did a quick test, it looks like script tags are stripped out anyways when you call .html(). So you should be able to simply do:
var html = "<html><script></script></html>",
cleanedHtml = $(html).html();
myEl.html(cleanedHtml);

Categories