Calling a javascript function by using onClick in a hyperlink - php

I have been looking online, but I have failed to find a direct answer to my question:
Can you use onClick for a tags?
In other words can you do this (note echoed through php)?
echo "\n";
I tried to run this, but when I click on the link, my counter function is not being called.
The rest of my code snippet:
echo "<script type=\"text/javascript\" src=\"src\jquery\jquery.js\">\n";
echo "function counter(){\n";
echo "alert(\"HELLO WORLD!\");\n";
echo "}\n";
echo "</script>\n";
echo "\n";

Although that should work, it's better practice not to bind events inline. I would suggest looking into addEventListener and for older versions of IE, attachEvent. More information on these can be found in a topic here: Correct usage of addEventListener() / attachEvent()?
If you wait for the window to be ready, you ensure that the element is on the page and defined for you to access it.
window.onload = function(){
//add any event listeners using the above methods in here
}
Example:
<script>
window.onload = function(){
var t = document.getElementById("test");
t.addEventListener("click", sayHi, false);
function sayHi(){
alert("Hi");
}
}
</script>
<div id="test">test</div>​
According to your above echo statements, if you are determined to make it work that way then you can try this:
echo "<script type='text/javascript' src='src/jquery/jquery.js'></script>\n";
echo "<script>\n"
echo "function counter(){\n";
echo "alert('HELLO WORLD!');\n";
echo "}\n";
echo "</script>\n";
echo "<a href='#' id ='loginbutton' onClick='counter()'></a>\n";
notice that I closed the script tag including jQuery and added a new opening tag right below it.
EDIT:
Script tags that reference external resources (via the src attribute)
are no longer able to execute script embedded within the tag itself.
Read more here

Made a little Demo code, Note that the function fires and then the href is followed. You can turn this off with JS by returning false.
<script type="text/javascript">
function counter() {
alert("do something here")
var FollowHref_Or_Not = false;
// true would simply follow the href after the function is activated
return FollowHref_Or_Not;
}
</script>
Test Link

To add more context to the comments above, here's a working example. Where I put the HTML comment about simulating an echo, just put your PHP echo line. Also note that I added a return false; This prevents the default link click behavior from executing. Since your href is "#" it would modify your URL to put "#" in the URL so if you used your browser back button you'd still be "stuck" on the same page.
http://jsfiddle.net/6pEbJ/
<html>
<head>
<script type="text/javascript">
function connect()
{
alert('connected!');
}
</script>
</head>
<body>
<!-- simulated echo result here -->
Testing
</body>
</html>

Related

Integrating JQuery into php file

I am trying to tweak a website so users will be able to swipe through the photo galleries on their mobile devices. I tried doing this by using JQuery. The website was not written by me, so I can't really explain the choices the previous programmer made regarding their code.
Currently, users can change pictures by clicking (tapping) on the current picture. The code for this is found in a php file called home.php. This is it:
<?php
...
$main_content .= "\n <div class='main_image'>
<a href='$next_slideURL' style='display:block'>
<img src='$root/$item_path/$slideFile' alt='$slideCaption from $projectTitle\n [xxxxxxxxxxxxx]' style='max-width:832px; max-height:500px' title='$projectTitle: $slideCaption. \nclick for next slide ($next_slideCaption). '></a>
</div>\n";
...
?>
To add swiping capabilities, I added the following code right after the one above:
echo "<script type='text/javascript'>";
echo "(function(){
$(\"div.main_image\").on(\"swipeleft\", swipeleftHandler);
$(\"div.main_image\").on(\"swiperight\", swiperightHandler);
function swipeleftHandler(event){
$.mobile.changePage(\"$next_slideURL\", {transition: \"slideleft\", changeHash: false});
}
function swiperightHandler(event){
$.mobile.changePage(\"$previous_slideURL\", {transition: \"slideright\", changeHash: false});
}
});";
echo "</script>";
While I'm not sure exactly why this isn't working, I have a few possible reasons (which might all be true unfortunately).
1) Since the div class='main_image' is done as a variable declaration, the JQuery line "div.main_image" doesn't have a reference (i.e. it doesn't know what main_image is). I'm not sure why the div is created as a variable declaration ($main_content keeps being added on throughout the php file, and in the end it's echoed along with a bunch of other variables).
2) I need to include the following code for JQuery but I have it in the wrong place:
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css">
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
right now I have it in the header section of index.html file. Is this wrong?
3) I've never used JQuery before, so any number of things might be wrong about the short script I wrote.
Sorry about the long post, I'm not sure how to explain this in a simpler way.
I'd appreciate it if anyone could help me either with this approach, or propose a different one.
Cheers!
Use $ while writting ready function
<?php
echo "$(function(){
// ---^--- use $ here
....
....";
echo "</script>";
?>
If $ conflicts then your can use jQuery like,
Full Code:
<?php
echo "<script type='text/javascript'>";
echo "jQuery(function(){
jQuery('div.main_image').on('swipeleft', swipeleftHandler);
jQuery('div.main_image').on('swiperight', swiperightHandler);
function swipeleftHandler(event){
$.mobile.changePage('".$next_slideURL."', {transition: 'slideleft', changeHash: false});
}
function swiperightHandler(event){
$.mobile.changePage('".$previous_slideURL."', {transition: 'slideright', changeHash: false});
}
});";
echo "</script>";
?>
Looks like you need to put your javascript in the $main_content variable, like the other code.
But to be honest you should seperate your javascript from the html/php.
Best way is to break out of php tags
and change this (function () to $(function ()
<?php
//php code
?>
<script type='text/javascript'>
$(function () {
$("div.main_image").on("swipeleft", swipeleftHandler);
$("div.main_image").on("swiperight", swiperightHandler);
function swipeleftHandler(event) {
$.mobile.changePage("$next_slideURL", {
transition: "slideleft",
changeHash: false
});
}
function swiperightHandler(event) {
$.mobile.changePage("$previous_slideURL", {
transition: "slideright",
changeHash: false
});
}
});
</script>;
<?php
//php code
?>

How to execute PHP code within JavaScript

<button type="button" id="okButton" onclick="funk()" value="okButton">Order now </button>
<script type="text/javascript">
function funk(){
alert("asdasd");
<?php echo "asdasda";?>
}
</script>
When the button is pressed I want to execute PHP code (at this point to echo asadasda)
You could use http://phpjs.org/ http://locutus.io/php/ it ports a bunch of PHP functionality to javascript, but if it's just echos, and the script is in a php file, you could do something like this:
alert("<?php echo "asdasda";?>");
don't worry about the shifty-looking use of double-quotes, PHP will render that before the browser sees it.
as for using ajax, the easiest way is to use a library, like jQuery. With that you can do:
$.ajax({
url: 'test.php',
success: function(data) {
$('.result').html(data);
}
});
and test.php would be:
<?php
echo 'asdasda';
?>
it would write the contents of test.php to whatever element has the result class.
Interaction of Javascript and PHP
We all grew up knowing that Javascript ran on the Client Side (ie the browser)
and PHP was a server side tool (ie the Server side). CLEARLY the two just cant interact.
But -- good news; it can be made to work and here's how.
The objective is to get some dynamic info (say server configuration items) from the server into the Javascript environment so it can be used when needed - - typically this implies DHTML modification to the presentation.
First, to clarify the DHTML usage I'll cite this DHTML example:
<script type="text/javascript">
function updateContent() {
var frameObj = document.getElementById("frameContent");
var y = (frameObj.contentWindow || frameObj.contentDocument);
if (y.document) y = y.document;
y.body.style.backgroundColor="red"; // demonstration of failure to alter the display
// create a default, simplistic alteration usinga fixed string.
var textMsg = 'Say good night Gracy';
y.write(textMsg);
y.body.style.backgroundColor="#00ee00"; // visual confirmation that the updateContent() was effective
}
</script>
Assuming we have an html file with the ID="frameContent" somewhere,
then we can alter the display with a simple < body onload="updateContent()" >
Golly gee; we don't need PHP to do that now do we! But that creates a structure for
applying PHP provided content.
We change the webpage in question into a PHTML type to allow the server side PHP access
to the content:
**foo.html becomes foo.phtml**
and we add to the top of that page. We also cause the php data to be loaded
into globals for later access - - like this:
<?php
global $msg1, $msg2, $textMsgPHP;
function getContent($filename) {
if ($theData = file_get_contents($filename, FALSE)) {
return "$theData";
} else {
echo "FAILED!";
}
}
function returnContent($filename) {
if ( $theData = getContent($filename) ) {
// this works ONLY if $theData is one linear line (ie remove all \n)
$textPHP = trim(preg_replace('/\r\n|\r|\n/', '', $theData));
return "$textPHP";
} else {
echo '<span class="ERR">Error opening source file :(\n</span>'; # $filename!\n";
}
}
// preload the dynamic contents now for use later in the javascript (somewhere)
$msg1 = returnContent('dummy_frame_data.txt');
$msg2 = returnContent('dummy_frame_data_0.txt');
$textMsgPHP = returnContent('dummy_frame_data_1.txt');
?>
Now our javascripts can get to the PHP globals like this:
// by accessig the globals
var textMsg = '< ? php global $textMsgPHP; echo "$textMsgPHP"; ? >';
In the javascript, replace
var textMsg = 'Say good night Gracy';
with:
// using php returnContent()
var textMsg = '< ? php $msgX = returnContent('dummy_div_data_3.txt'); echo "$msgX" ? >';
Summary:
the webpage to be modified MUST be a phtml or some php file
the first thing in that file MUST be the < ? php to get the dynamic data ?>
the php data MUST contain its own css styling (if content is in a frame)
the javascript to use the dynamic data must be in this same file
and we drop in/outof PHP as necessary to access the dynamic data
Notice:- use single quotes in the outer javascript and ONLY double quotes in the dynamic php data
To be resolved: calling updateContent() with a filename and
using it via onClick() instead of onLoad()
An example could be provided in the Sample_Dynamic_Frame.zip for your inspection, but didn't find a means to attach it
You can't run PHP with javascript. JavaScript is a client side technology (runs in the users browser) and PHP is a server side technology (run on the server).
If you want to do this you have to make an ajax request to a PHP script and have that return the results you are looking for.
Why do you want to do this?
If you just want to echo a message from PHP in a certain place on the page when the user clicks the button, you could do something like this:
<button type="button" id="okButton" onclick="funk()" value="okButton">Order now</button>
<div id="resultMsg"></div>
<script type="text/javascript">
function funk(){
alert("asdasd");
document.getElementById('resultMsg').innerHTML('<?php echo "asdasda";?>');
}
</script>
However, assuming your script needs to do some server-side processing such as adding the item to a cart, you may like to check out jQuery's http://api.jquery.com/load/ - use jQuery to load the path to the php script which does the processing. In your example you could do:
<button type="button" id="okButton" onclick="funk()" value="okButton">Order now</button>
<div id="resultMsg"></div>
<script type="text/javascript">
function funk(){
alert("asdasd");
$('#resultMsg').load('path/to/php/script/order_item.php');
}
</script>
This runs the php script and loads whatever message it returns into <div id="resultMsg">.
order_item.php would add the item to cart and just echo whatever message you would like displayed. To get the example working this will suffice as order_item.php:
<?php
// do adding to cart stuff here
echo 'Added to cart';
?>
For this to work you will need to include jQuery on your page, by adding this in your <head> tag:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
Any server side stuff such as php declaration must get evaluated in the host file (file with a .php extension) inside the script tags such as below
<script type="text/javascript">
var1 = "<?php echo 'Hello';?>";
</script>
Then in the .js file, you can use the variable
alert(var1);
If you try to evaluate php declaration in the .js file, it will NOT work
put your php into a hidden div and than call it with javascript
php part
<div id="mybox" style="visibility:hidden;"> some php here </div>
javascript part
var myfield = document.getElementById("mybox");
myfield.visibility = 'visible';
now, you can do anything with myfield...
We can use php in JavaScript by creating a form element and put the action as a .php page.
Then we use JavaScript to submit that form.
EX:
<!doctype html>
<html>
<head>
<title>PHP Executed with JS</title>
</head>
<body>
<form action="phpCode.php" id="phpCode">.
</form> <!-- This is the form-->
<script>
function runPhp() {
var php =
document.getElementById("phpCode")
php.submit() //submit the form
}
</script>
</body>
The PHP file name would be phpCode.php.
In that file would be your PHP code.
May be this way:
<?php
if($_SERVER['REQUEST_METHOD']=="POST") {
echo 'asdasda';
}
?>
<form method="post">
<button type="submit" id="okButton">Order now</button>
</form>
If you do not want to include the jquery library you can simple do the following
a) ad an iframe, size 0px so it is not visible, href is blank
b) execute this within your js code function
window.frames['iframename'].location.replace('http://....your.php');
This will execute the php script and you can for example make a database update...
Use ajax to send request and echo the response
when successfully executed. Like this:
$.get("site.com/ajax", function(status,data){
alert(status);
});
This can be achieved with jquery library.
You could run PHP at the start of the Page and grap the results from inputs
<?php
c = a * b;
?>
<input type="hidden" name="c" value="<?php c ?>"/>
<button type="submit">Submit</button>
</form>
<script>
let cValue = $('input[name="c"]').val();
alert(cValue);
</script>

Printing a javascript variable in php echo

To clarify:
I have an echo statement as follows:
$striptitle .= ' - <a onclick="getnewurl();" href="'.SGLink::album($aid). '">'. $namek .'</a></h1>
<a href="https://twitter.com/share" class="twitter-share-button" data-lang="en" data-via="jb_thehot" data-text="Pictures of '. $hashfinal .'" teens>Tweet</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>';
echo $striptitle ;
The onclick does this:
<script type="text/javascript">
function getnewurl()
{
var url = document.URL;
alert( url );
}
</script>
What I need is essentially to add the my anchor tag a data-url="INSERT_VAR_URL_HERE"
Is that possible?
Let me know if this isn't clear enough
Thanks!
Edit: to clarify, the alert in the function is only for testing. What I need is to be able to use the variable obtained in the function, in the same $striptitle variable.
My problem is that the url changes with AJAX, and the twitter button's data-url does not get updated. I was hoping to be able to get the new url by getting it everytime it is clicked. If there are other ways to do that, I'm open to suggestions!
Why not pass it as an argument?
$striptitle .= " - <a onclick=\"getnewurl('URL-HERE');\"...>";
Then in your script:
<script>
function getnewurl(url) {
alert(url);
}
</script>
Building on #Kolink's answer one way to not repeat the url in two places you could generate the link as:
<a onclick="getnewurl(this);" href="...">
then your JS could look like:
function getnewurl(link) {
link.setAttribute('data-url', location.href);
}
EDIT apparently jQuery.data doesn't update the dom properly, but setAttribute does

Scriptaculous highlight effect on php print

I want this effect when php print gets called . How can i do it?
I have tried with
print "<span id=\"highlight\" onLoad=\"Effect.Highlight(highlight);\"><em>Your post was successfully added.</em></span>"."<hr>";
but this is not working. Help!
if it does not need to be in the php itself then use (advise against using short tags to open and close):
?>
<span id="highlight" onLoad="Effect.Highlight(this.id);"><em>Your post was successfully added.</em></span><hr>
<?php
and continue your script.
alternatively,
<head>
...
object.onload="SomeJavaScriptCode";
...
</head>
--EDIT--
Javascript would look like:
<script type="javascript/text">
body.onload=Effect.Highlight(getElemenyById('highlight'));
</script>
-- EDIT --
Javascript, I believe, (thanks to comments) will look like:
document.addEventListener('DOMContentLoaded', function () {
Effect.Highlight(getElemenyById('highlight'));
}, false);
onload=""
Does only work inside of a <body>, <frame>, <frameset>, iframe, <img>, <input type="image">, <link>, <script> or <style> Tag.
if you are using javascript why not print in your script section?
in your body you can have the notice hidden,
and after the post is added to the database you can show and highlight the alert.
are you using Ajax?
an example:
<span id="hightlight" style="display:none"><em>Your post was successfully added.</em></span>
<scrpt type="text/javascript">
<?php
print "$('highlight').show(); Effect.Highlight('highlight')";
?>
</script>

How do I run a function only when a div gets loaded?

I want to run a function only when a div gets loaded.
When I load the page, a number of files are loaded. At the end of the list, PHP echoes a div. When this one is displayed, jQuery should run a function.
I can do this with a click-event, but I want it to work automatically, without pushing a button.
This is how it works with a click:
$("#PP_end_show").live("click",function(){
$("#PP_head_bar").slideToggle("slow");
$("#PP_info_file_wrap").slideUp("slow");
});
This is the div echoed by PHP:
<?php echo "<div id=\"PP_end_show\"></div>"; ?>
The output is generated after an AJAX call:
<form id="PP_search_input" method="post" name="search_ID" ONSubmit="xmlhttpPost('PP_search_stream_client.php', 'PP_search_input', 'PP_thumb_output', '<img src=\'images/wait.gif\'>');return false; ">
<input name="search_string" type="text" class="PP_input" id="search_string" value="<?php echo $_POST['search_string']; ?>"/>
<button type="submit" class="PP_submit" id="search_submit"> search </button>
at the end of the generated output the specific div will be printed and should trigger the new jQuery function.
This is how I would tackle this issue, assuming I've understood it correctly in which the submission of the form PP_search_input, returns the html needed, in which then a the javascript code should be executed.
$('#PP_search_input').submit(function() {
$.ajax({
url: 'PP_search_stream_client.php',
type: 'post',
data: $(this).serialize(),
success: function(html) {
$(html).insertAfter('#whereToInsert') //change to however you want to insert the html
.find("#PP_head_bar").slideToggle("slow").end()
.find("#PP_info_file_wrap").slideUp("slow");
}
});
});
Try putting your javascript code inside the generated ajax code.
For example if your ajax is generated from the php code
<?php echo "<div id=\"PP_end_show\"></div>"; ?>
then try smth like this
<?php
echo "<div id=\"PP_end_show\"></div>";
echo '$(function(){$("#PP_head_bar").slideToggle("slow");';
echo '$("#PP_info_file_wrap").slideUp("slow");});';
?>
You could use the livequery plugin
You would then use it as follows :
$('#PP_end_show').livequery(function(){
$("#PP_head_bar").slideToggle("slow");
$("#PP_info_file_wrap").slideUp("slow");
});
The code in the function would execute when the element in the selector (#PP_end_show) was added to the DOM
Why not echo your javascript along with the DIV code?
You can use PHP to echo Javascript like this:
After your code:
<?php echo "<div id=\"PP_end_show\"></div>"; ?>
Write this:
echo "<script type='text/javascript'>
$('#PP_head_bar').slideToggle('slow');
$('#PP_info_file_wrap').slideUp('slow');
";
echo "</script>";
This should work.
In your JS, wrap the code you want to execute in a function. i.e.
function showInfoBlock() {
$("#PP_head_bar").slideToggle("slow");
$("#PP_info_file_wrap").slideUp("slow");
}
In your PHP, write out the JS needed to call that function after writing out the PP_end_show div. i.e.
<?php echo "<div id=\"PP_end_show\"></div><script>$(function() { showInfoBlock(); })();</script>"; ?>
This does what you are asking:
(function($){
var checkForEndInterval = window.setInterval(function(){
if ($('#PP_end_show').length) {
// stop interval
window.clearInterval(checkForEndInvertal);
// call your code now
$("#PP_head_bar").slideToggle("slow");
$("#PP_info_file_wrap").slideUp("slow");
}
},200);
})(jQuery);
However this is not a good idea because its silly and what you are asking for hints you not understanding but that is why you are here. Since you already know when your AJAX is called, call it explicitly and attach a success handler to it.
$.ajax({
/* your other setup code here */
success : function(data) {
// run your code
}
});
If you were not doing AJAX as you say, I would put a script tag at the end of your output and have it call your code as the simplest approach. Even still, you could use the jQuery.load method (not event) which by default executes JavaScript from your response.
Happy coding.
keep that jquery live-click-function as it is
& run the below code in php
<?php
echo "<div id=\"PP_end_show\"></div>";
echo "$(function(){ $(\"#PP_end_show\").click(); });";
?>
$.ready(function(){
$("#wrapper").add("div").attr('id','PP_end_show');
$("#PP_head_bar").slideToggle("slow");
$("#PP_info_file_wrap").slideUp("slow");
});
<div id='wrapper'>
</div>
Bind the live event to a custom event that is triggered by the document:
$(document).trigger('echo');
$("#PP_end_show").live("echo", function(){
$("#PP_head_bar").slideToggle("slow");
$("#PP_info_file_wrap").slideUp("slow");
});
References
jQuery API: .trigger()
JQuery API: .live()
Jason Brumwell enter right answer, also you can use the $.when function of JQuery.
http://api.jquery.com/jQuery.when/
If the action you want to perform once the desired div loads is bound to a click event, simply trigger click at the end of the ajax request something like:
$.ajax({
url:'whatever.php',
type:'post', //guessing obviously
success: function(data){
$('#PP_end_show').click(); //etc
}
});
These guys are right though, you are doing this all backwards mate
Does it have to be that exact div? It seems to me that you should just execute the function on load of the document. That way you know all your elements are loaded.
$(function()
{
// This function is executed when the DOM is ready, including that last div.
// Could be that images are still loading, but your code usually won't depend on that.
}
Try this,
if(window.isBodyLoaded){
try{
$("#PP_head_bar").slideToggle("slow");
$("#PP_info_file_wrap").slideUp("slow");
}catch(d){
alert(d)
}
}
Use a callback function.
Its a function that will be triggered as soon as your event is handled.
so for Jquery:
$("#PP_end_show").live("click",function(){
$("#PP_head_bar").slideToggle("slow");
$("#PP_info_file_wrap").slideUp("slow");
}, myCallback());
function myCallback(){
//Do what ever you want to happen after
//the div creationin this function
}
And I think that should do the trick

Categories