I want to load a JS function only when my php code call this function, but not when you visit the page for the first time. My code looks like this:
<?php
function runMyFunction() {
echo '<script type="text/javascript"> JSfunction(); </script>';
}
?>
<script>
JSfunction();
function JSfunction(){
// Code in my function
}
</script>
The problem is that the function JSfunction() is called as soon as the page (index.html) is loaded. But I only want to execute the function with my PHP code, which is called after clicking a button. I would be glad about an answer.
bind the click event on the button to an ajax call, which calls your php code and returns JSON saying whether to go ahead or not.
The other method for this is to have this type of php code:
<?php
if(isset($_GET['myvar'])){
?>
<script type="text/javascript">
//call your javascript here
</script
<?php
}
?>
With that in place have clicking the button reload the page with the GET variable myvar appended to the url.
Example: https://example.com?myvar=1
Related
I'm trying to attach a PHP script to a button so when someone clicks on it, I'm sent what page they're on. I have the PHP script written and I'm trying to attach it to a JavaScript onclick call. Here's what I have so far:
<button id="location">Click to reveal the page you're on</button>
<script>
function send_sms() {
var result = '<?php locate_me(); ?>';
console.log('send_sms');
}
document.getElementById('location').addEventListener('click', send_sms, false);
</script>
However, the JavaScript gets called when the page loads - not when the button is clicked - or maybe it's just the PHP that gets run. The console.log command does not get written on page load, but the PHP script is run. Very strange - at least to me.
I'm not proficient with JavaScript, but I thought the addEventListener() would prevent that from happening. What am I doing wrong?
Thanks,
Frank
I'm not sure about what you mean by "revealing what page the user is on", but I'm thinking that's not relevant to the question, you're asking. I'm not too kean on running php scripts on the same file, I'm running my js on. As nice_dev suggested, I would make an ajax call to a seperate php file, in order to get live updates and not having your php variables pre-loaded.
So I would write my code like this:
Your main file:
<?php // Result from your second php file ?>
<script>
// Ajax call
$(document).ready(function(){
$("#location").click(function(){
var result = '<?php echo $variable; ?>';
$.ajax({
url: "somepage.php",
type: "POST",
data: {result:result},
success: function(result){alert(result }});
});
});
</script>
<html>
<body>
<button id="location">Click to reveal the page you're on</button>
</body>
</html>
Your second file, which will handle your ajax request:
<?php
$yourvariable = $POST['result'];
if isset($yourvariable){
// The php code you want to execute
}
?>
I hope this makes sense. Otherwise, I would be happy to elaborate.
In summary, I would try to run your code on 2 files in a circular process.
I have a hyperlink and clicking on that link will run a JavaScript function. I also have a PHP variable $counter. Inside the JavaScript function, the value of $counter is increased by 1 i.e., $counter++. It works fine. But the same function also runs whenever the page is refreshed. So the value of the $counter is increased by 1 whenever the page is refreshed. I tried all the solutions available on the net like preventDefault(), clickevent handler etc., But nothing works. Please help to fix this. In the below code, I have set $counter as 0. But it loads with 1 as output. I want it to count only when the hyperlink is clicked. Here is my sample code.
<?php
session_start();
require("dbconfig.php");
$counter=0;
?>
<html>
<head>
<script>
function onclick() {
<?php
$counter++;
?>
}
</script>
</head>
<body>
link text
</body>
<?php
//tracing counter value
echo $counter;
?>
</html>
TL;DR:
You can't mix PHP and JS code expecting that JS function will execute PHP code.
First PHP prepares output to browser, then Browser parses your JS and HTML. JS never knows about PHP code.
Click CTRL+U to view source as browser sees it - there is no PHP code.
JS function is not run on page refresh. PHP code is run on page refresh.
First goes PHP parser:
session_start();
require("dbconfig.php");
$counter=0;
$counter++;
echo $counter;
Then goes JS/Html parser.
At this point your JS code looks like this:
function onclick() {
}
Content of function is empty because you output nothing from PHP side.
To fix it move PHP var to JS var:
<?php
session_start();
require("dbconfig.php");
$counter=0;
?>
<html>
<head>
<script>
var jsCounter = <?= $counter; ?>
function onclick() {
jsCounter++;
console.log(jsCounter);
}
</script>
</head>
<body>
link text
</body>
</html>
Note never output after closing body tag.
Is there a PHP require_once or include_once for <script>? I know <script> is pure HTML, but does PHP or HTML have such a thing?
I would like to prevent javascript from loading twice in the same page.
Example:
<script type="text/javascript" src="js/jquery-0.4.ajaxify.min.js"></script>
Seems like you are looking for this:
http://wonko.com/post/painless_javascript_lazy_loading_with_lazyload
One of the way you can run script tags in php would be
<?php
....Here is php code
?>
... add the script here(<script>....</script>
<?php
?>
Another probable way is :
Using php inside the script tags for example:
<script type="text/javascript">
var alertMsg = '<?php echo $custom_message; ?>';
alert(alertMsg);
</script>
If you are using buttons
echo('<button type="button" onclick="customfunction();">My Button</button>');
<script>
//call your customfunction here
</script>
AN UPDATE TO SOLVE LOADING SCRIPT CONTENTS TWICE
I would suggest use of javascript function which are called to the specific page as they are needed an example would be
Create a file with a .js eg
example.js
here declare your functions you would put in the script tags of a html page
In the page you want to use the <script>
Include the example.js file and you can call the custom functions from there use the obect orientend approach
Check This resource for more info about obect orientend javascrip
I want to have some text shown by the label in HTML. This label must get its text from a Javascript function when the page is loaded or reloaded. How can I achieve this? The text will be dynamic.
<label id="MyLabel"></label>
<script type="text/javascript">
labelFunc(){
document.getElementById("MyLabel").innerHTML='<?php echo $_SESSION["SomeSession"];?>';
}
</script>
The Label 'MyLabel' should get its text from the 'labelFunc()' javascript function.
You've created the labelFunc function, but never called it, so it never gets executed. Also, your function declaration syntax is incorrect - you need to put function before you write your function.
To update your existing code:
<script type="text/javascript">
function labelFunc(){
document.getElementById("MyLabel").innerHTML='<?php echo $_SESSION["SomeSession"];?>';
}
labelFunc();
</script>
If you never need to call that function again, then using a function would be unnecessary - you could simply just put it the code you need to run on its own inside the script tag:
<script>
document.getElementById("MyLabel").innerHTML='<?php echo $_SESSION["SomeSession"];?>';
</script>
your code is just fine as it is, you just need to make sure the page is loaded before the JS is executed. do that by either putting your JS at the bottom, or calling it when the page is loaded.
<body onload="labelFunc();">
also, you need the word "function"
<script type="text/javascript">
function labelFunc(){
document.getElementById("MyLabel").innerHTML='<?php echo $_SESSION["SomeSession"];?>';
}
</script>
So i have a contact page that runs some php and in that php if the email sends through correctly it runs a javascript command. I have two javascript commands one to change page and one to alert the person sending the email. Here is the code:
if ($mail_status) { ?>
<script language="javascript" type="text/javascript">
window.location.assign("http://dtc.bz/twitch/index.html");
$('.alertfeed').show();
</script>
<?php
}else { ?>
<script language="javascript" type="text/javascript">
</script>
<?php
}
?>
When I run it. It redirects me to the correct page but the second command within the php page. So how do I get the second line of the javascript run on the page I want it to redirect to?
After the page redirection no code will be executed, that's the reason "$('.alertfeed').show();" is not getting triggered. To do this you have to redirect the page first and on the page you have redirected then execute the next command.
Something like
window.location.assign("http://dtc.bz/twitch/index.html?redirected=yes");
now on the index.html check if redirected param and execute this command in php
<?php if($_GET['redirected']=='yes')
{
echo "<script>$('.alertfeed').show();</script>";
}?>
Update: Using Jquery
$(document).ready(function(){
var url = window.location.pathname;
var pieces = url.split("?");
if(pieces[1]=='redirected=yes'){
$('.alertfeed').show();
}
});
Working Demo:
http://jsfiddle.net/sLEgJ/4/
Your are getting redirected because there is no condition given for redirecting.
Thats why its redirecting you every time you run it.