Linking to a page to also load javascript - javascript

I want to be able to create a link to a specific page on my site and then also have that link load a specific piece of javascript on that page.
For example:
I link to this page:
http://www.myexample.com/cat/test.html
Then I want the link to also open a topic on arrival by executing a piece of javascript:
javascript:showContentDesc(59, 11, 'left'), scroll(0,120)
I have done some research and I believe I have to do the following:
1- Modify the URL to specify the DIV to open
2- Have an onLoad handler that parses the URL and opens the appropriate DIV.
So I will then have a URL like this:
http://www.myexample.com/cat/test.html#1
The link will take me toe the page where an onLoad Handler will parse the URL and then call the
javascript:showContentDesc(59, 11, 'left'), scroll(0,120) piece of script.
If the URL were
http://www.myexample.com/cat/test.html#2
it would then be parsed by the online handler and run a different piece of javascript
javascript:showContentDesc(60, 11, 'left'), scroll(0,120)
So my question is, based on this being correct:
1 - What do I need to do to create the onLoad Handler?
2 - How do I make the script that parses the url and then runs the the appropriate piece of javascript?
I hope this is understandable.
Thanks for the help as always!
OK so this is what I have figured out thus far...
In my joomla module (The one I want to be able to load a spesific topic of has this piece of code on the bottom.
<script type="text/javascript">
showContentDesc("<?php echo $module->id; ?>",0,"<?php echo $menuPositions; ?>");
</script>
This tells the browser to load topic 0 - this can be changed to 2 or what ever I want.
So I believe all I have to do now is add a handler that parses the URL somewhere and then have the 0 in the code be the value of the part the handler parses ??
Any help???

This made it work!
<script type="text/javascript">
showContentDesc("<?php echo $module->id; ?>"<?php $page=$_GET['page'];
if(isset($_GET['page']))
echo "$page";
else
echo "0";
?>"<?php echo $menuPositions; ?>");
</script>

Related

insert php into javascript

I write some html, javascript and php code that normally have to execute php code when a html button is pressed if you click on "ok" on the "confirm box", so there is my html code :
<input onclick="logout()" name="logout" type="submit" value="Logout me" />
Javascript and php code :
function logout() {
if (confirm("Are you sure you want to logout ?") == true) {
<?php echo "Hello world !"; ?>
} else {
<?php echo "Goodbye world !"; ?>
}
}
I think that the javascript code work because when i click on the html button the confirm box appear like it has to appear, but the php code is not executed.
Please if someone would help me it will be greatfull.
You can't use php in javascript because php is a serverside programming lenguage and javascript is a client side programming lenguage, so php is executed (by the server) before javascript (that is executed by the browser of the user).
You have to use Ajax requests for your needs.
Quickstart Ajax guide: https://www.w3schools.com/xml/ajax_intro.asp
Even though it is possible to write JS inside of PHP, I don't think this is the way to solve this problem. You can only (as far as I know) echo PHP values inside JS that is executed inside tags, when you write HTML inside .php files.
PHP is indeed server side and the Javascript is in this situation client side. You're thinking wrong.
First you should extract your logout functionality to a logout.php file for example. Then you could do either one of the two:
When you really want to use the logout function as a direct event listener to the onClick event on your input, your logout callback function should make an AJAX call to logout.php, which logs out your user. See the answer from #Helio to see more about AJAX.
Your input should be placed inside a <form>, which has an action attribute, that calls to your logout.php. Then when submit is called, it is available to you through the $_POST superglobal, and you can check if it is pressed. Then you simply log out the user.
That doesn't appear to be valid Javascript.
Within the Javacript function, you are dropping a PHP statement as if you were writing it to the HTML, this will not work. I'm surprised you got the dialog to popup.
PHP is a server side language and Javascript is not, therefore you should not even call PHP code like that from any kind of Javascript.
To help your curiosity, you could get away with using the document.write() function, but don't use this.
I would recommend rewriting your function to redirect to a specific PHP page.
function logout() {
if (confirm("Are you sure you want to logout ?") == true)
{
// try to avoid this....but still works
document.write('<?php echo "Hello world !"; ?>');
// try this instead
window.location.href = '/helloworld.php';
}
else
{
// try to avoid this....but still works
document.write('<?php echo "Goodbye world !"; ?>');
// try this instead
window.location.href = '/goodbyeworld.php';
}
}

how to execute a php function from a separate php file onClick

I have two php files (1.php and 2.php) linked with require
php.1 has a qr <img src="http://chart.googleapis.com/chart?chs=125x125&cht=qr&chl=<?php echo $_jattu; ?>" width="50%"> which gets its value from a string variable in 2.php $_jattu;
What I want is for <?php echo $_jattu; ?> to only echo when <a class="w3-button2 w3-black2"></a> is clicked and not when the page is loaded or refreshed, what can I do to achieve this?
This is imposible to do on the server side. Because the "onClick" event jumps on the client side when de user do the action.
You have few options.
Enable another URL for load the content of $_jattu and when the user click load it with an AJAX request. Is the best way to do it and the result is more smooth and user friendly
As you say you want to do it refreshing. So, slightly refresh the page with a new parameter on your url that tolds you that the "onClick" event has jump. Like:
.../your/path?hasClick=true
And in your php code:
if(isset($_GET["hasClick"]) && $_GET["hasClick"]){
echo $_jetty;
}
http://php.net/manual/en/reserved.variables.get.php
if you want to remember that the user has clicked "forever" you can setup a cookie.
http://php.net/manual/en/function.setcookie.php
You can use ajax. Make a request to whatever php script you want which will return $_jattu when clicking on the link. Then update your img link in javascript using the return of the ajax request.

Calling multiple html page from php consecutively

I am not well versed in php. I tried different answer from stackoverflow but was not successful in solving the problem.
I got a HTML form with a submit button. After submitting I call a php script and which in turn calls an executable file which runs some algorithms on the submitted data from the html. At the end I echo the result of the analysis through the php.
<?php
$ex=shell_exec("...");
if($ex == "Run Successfully\n"){
echo"<html>
<meta http-equiv= refresh content='0.1;URL=--.txt'>
</html>";
}
?>
Till this works fine but my algorithm takes 30-40 sec to run and all that time my original html page remains in screen which looks like nothing is happening there. So I created a new html page with a progress bar animation. Now I want to show the progress bar while the executable is running and when the result is available I want to replace the progress bar page with the result page as before.
I tried echo file_get_contents("waiting.html");
header ("location: waiting.html");
But none of them works as I planned. All the time they are coming up only after the executable finish working and not before that.
If someone can help me with some suggestion I shall be grateful.
Thanks in advance.
This is where jQuery and AJAX would work very nicely. What you could do is start with the loading animation, and use jQuery to call the php file with the shell_exec with ajax. Once the ajax is .done(), then you can replace the text with the results. If you need me to clarify, just let me know.
However, if you don't want to use AJAX, PHP is run line by line. Therefore, you would want to put your progress bar before the shell_exec. This would mean that you would not be able to use header location since headers have already been sent.
Edit (AJAX Example):
This would be a quick example of how to make this happen.
Create two php files:
progress.php
Load jQuery
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url:'algorithm.php',
type: 'post',
cache: false,
success: function(data) {
//Replace with how you want to format the page
}
});
});
</script>
Loading Bar
algorithm.php
<?php
$ex=shell_exec("...");
if($ex == "Run Successfully\n"){
die('{"status":"success"}');
}
?>
Now you don't have to use json as an output. You can also have html output. Let me know if I should clarify anything.

Click Button on Website with scheduled script

I have a website with external like buttons (from likebtn.com) on it. To encourage users to use them I have a script that randomly gives likes to random posts. However I have the problem that this could only be done via the REST API from likebtn.com if the post already has min 1 Like from a button click. It is not possible for me to send an API request to achieve this (as told by likebtn.com support).
My question now is:
Is it possible (with javascript) to run a cron that opens the url with the post and clicks the like button once?
Any help or tips are appreciated!
I am not sure if I understand your question correctly but you could do something like this.
Run this code from a cronjob on set intervals. It simulates the click of the like button on page load.
http://jsfiddle.net/m3gN2/1/
<?php ?>
<button id="virtualLike">Like Me!</button>
<script>
var likeBtn = document.getElementById('virtualLike'); // get a reference to your element
likeBrn.onclick = clickHandler; // assign its click function a function reference
function clickHandler() {
alert("Button is clicked");
}
document.getElementById('virtualLike').click();
</script>
<?php ?>
Let me know if it was what you wanted and if it works for you.

.js file executes every time I click a link

I've been googling the whole day for this... I'm still a beginner at html/css/php/javascript, so I probably have some rookie mistakes, but that's why you guys are here to help me!
So, I have a dynamic website with a static template and dynamically loaded content. For example, when I click the "About Us" link, the template remains the same, but the content gets loaded from another .php file and printed out in a iframe in that same index, using the $_GET method. I'm using iframe so I don't affect the template layout. My problem is that my .js file with animations gets executed each time I click any of the navigation links, so it makes my wish to, for example, fade in the whole website once it's loaded impossible. Each time I click a link the entire website would dissapear and fade in again. I don't know did I use Google wrong, but I cannot find the solution to my problem. I only want that script to run once when the page is loaded, not whenever I click a link! Here are some parts of the code:
Part of index.php:
<?php
include('setup/setup.php');
?>
<html>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="javascript.js"></script>
<body>
<div class="wrapOverall">
<div class="header">Logo, language buttons etc.</div>
<div class="wrapMainNav">Main navigation (Home, About us etc.)</div>
<div class="content">
<iframe src=<?php echo "content_$language/$pg.php"; ?> frameborder="0" style="width:951px; height:486px;">aaa</iframe>
</div>
</div>
</body>
</html>
where "content_$language" is the folder from which I get the file, and "$pg.php" is the file itself.
The setup.php file:
<?php
error_reporting(E_ALL ^ E_NOTICE);
if($_GET['page'] == '')
{
$pg = 'naslovna';
}
else
{
$pg = $_GET['page'];
}
if($_GET['lang'] == '')
{
$language = 'cro';
}
else
{
$language = $_GET['lang'];
}
?>
The javascript.js file:
$(document).ready(function() {
$(".wrapOverall").hide(); //Hide the website
$("html").css("visibility", "visible");
var bg = new Image();
bg.src = "images/background.jpg";
bg.onload = function(){ //Load the background image
$("html").css("background-image", "url(images/background.jpg)");
$("html").css("background-repeat","no-repeat");
$("html").css("background-attachment", "fixed");
$("html").css("background-position", "center");
$(".wrapOverall").fadeIn(1000); //Fade in the site
$(".content").animate({height:'468px'},1000); //Animate content loading
}
});
That's about it, if you guys think you need more code I can send it.
Each time you click a link, and the URL changes, the browser makes a GET request to the server for that page. PHP will return the page and the browser will reload it, even if it's 95% the same as the last page you were on. It'll re-render the DOM and hence the $(document).ready event will fire again.
What you're looking to do is to refresh a part of the page without making a GET request to the server for the whole page. To do this you need to use AJAX.
One of the simplest ways to do this is using jQuery's load() method (click for documentation).
Have a look at the documentation and try a simple example, hopefully that will get you started.
NOTE: as has been mentioned already in the comments, there are plenty of frameworks that try to make achieving this functionality easier. Take a look at backbone.js, angularjs and ember.js to name a few. They also add a lot more, so depending on what you're trying to do, might be overkill, but it's worth a look.
Since your javascript is included in every page, it runs each time the page loads, and therefore hides and then shows the whole page. You should exclude it when loading other pages.
Have you tried to call the the iframe content with ajax ? That way the php will be called in the same time than your js functions.

Categories