PHP: Invoking Javascript Command - php

I'm using a plugin called Reveal, and trying to fire it based on whether a variable is present in the URL (i.e. www.mysite.com?status=new). I have tested the GET status code (works fine, echoed it) and also set up reveal to work when a button is pressed. Both work flawlessly. However, the goal is to fire the event if the status == new. This is my code:
<?
if($status == 'new'){
echo '<script type="text/javascript">$(\'#myModal\').reveal();
</script>';
}
?>
Doesn't work :/ Any help? I've tried many combinations with this and nothing seems to be working. My code is placed near the bottom of the page (in the body section), not sure if that matters..
EDIT: Also tried this (didn't work):
<?
if($status == 'new'){
echo '<script type="text/javascript">
$(document).ready(function() {
e.preventDefault();
$(\'#myModal\').reveal();
});
</script>';
}
?>
Zach

Try this:
echo '
<script type="text/javascript">
$(document).ready(function(){
$(\'#myModal\').reveal();
});
</script>';
as m90 already suggested, probably a good idea to load up the DOM before you execute the script. And you can place it anywhere, usually I place it in the head though, but it's all good.

Be aware that this kind of inline JS will be executed immediately by the browser, so it might be that the element you are trying to reveal isn't ready to be revealed yet (therefore nothing happens). Usually you will fix this by calling your scripts on $(document).ready(). See this article on the jQuery website

just wanted to put here a little bit different approach:
// Example URL:
// test.php?status=Message
var $_GET = <?php echo json_encode( $_GET ); ?>;
// alert( $_GET['status'] );
// console.log($_GET);

Related

php variable pass to java script and alert it

index.php
<?php
$loginmessage = "this is message";
?>
$(document).ready(function(){
$("#sb-btn").click(function() {
alert("<?=$loginmessage?>");
return false;
});
});
i have a button i wanted to when the button is clicked , it alert the $loginmessage by java script , but when i clicked it noting happen and no error as well. what i have to do to make the php variable pass to javascript and alert it when user clicked.
Don't forget to call jquery library. then try this-
<?php
$loginmessage = "this is message";
?>
<script>
$(document).ready(function(){
$("#sb-btn").on("click", function() {
var getvalue = '<?php echo $loginmessage; ?>';
alert(getvalue);
});
});
</script>
Depending upon your PHP version and host, the short tags could be disabled. They recently came back into use with PHP7, which is still in Release Candidate state.
What this means is that you might have to replace the short tags with the full <?php echo use. Look in the generated HTML code on the client, to find out if this is the case.
One small thing I'd like to nitpick on, is your terminology. :P
You're not actually passing a variable to JavaScript from PHP, as much as you're using PHP to generate parts of said JS. It might seem trivial, but the difference is a crucial one. Passing the variable implies something being handled in the same program, which isn't the case at all here. The PHP code gets executed on the server side, which generates plain text output to the client. The client (web browsers) in turn parses said content, and figures out what kind of content the different part of this text actually is.
Having this clear mental separation in mind when developing web applications/sites will make it a lot easier for you to understand the details of how things work, and in turn make it easier for you to come up with clean and simple solutions that works as intended. :)
Try to write in console. Maybe your browser blocks alert messages. And-> are you see JavaScript errors in your console?
<script>
$(document).ready(function(){
$("#sb-btn").on("click", function() {
var getvalue = '<?php echo $loginmessage; ?>';
console.log(getvalue);
});
});
</script>
Create a function that is called when a button is clicked. Pass the message that you want to alert to that function. Hope this helps. Checkout the code in snippet.
function alertSomething(test){
alert(test);
}
<button name="samplebtn" onclick="alertSomething('test alert')">Test Alert</button>

Calling Javascript based on PHP conditional when libraries load in the footer

I have the following in the body of a php page:
<?php if($foo) : ?>
<script>
js_func();
</script>
<?php else: ?>
//Do Something else
<?php endif; ?>
Based on the PHP conditional I either do or do not want to run js_func().
However if I am loading all of my scripts (including the script the defines js_func()) at the bottom of my page this will results in an error.
One possible solution would be to load the external script BEFORE calling js_func() but I understand that for performance reasons I shouldn't do that.
I could use $(document).ready(function() {}); but this just moves the error as jQuery is also loaded in the footer.
The only other options I can think of is to use window.onload or never call a js function inline. How does everyone else solve this issue?
Many thanks.
EDIT:
#Nile - Im not sure what you mean. Why would I comment out code that I want to execute?
#haynar1658 - I don't want to execute JS in the else scenario.
#Matthew Blancarte - Understood. That leads to my question, what's the best way to make sure that the js I need loads before that function is instantiated? Include the script before it? Use window.onload? etc.
I think you are making a rod for your own back. Depend on the question you described, you want to put all the function definition script block after the place where them being called. It's Impossible!
If you indeed need to do this, does this can help? :
<script>
var fns = []; /* use fns to keep all the js code
which call the functions defined after. */
</script>
<script>
//wrapp your code in a function and then push it into fns.
fns.push(function(){
js_func();
})
</script>
//script tags for loading your function definition js script.
<script src="path/to/jquery-any-version.js"></script>
<script src="path/to/other-libraries.js"></script>
<script>
//after your definition js scripts are loaded , call all functions in fns
for(var i=0, len=fns.length; i<len; i++){
var fn = fns[i];
fn.apply(this, []/* arguments that provided as an array */);
}
</script>
Just move the script to the top.
The difference (if there is one) is very small.
The believe that putting the <script>s in the <head> slows down the page is not "accepted" by all developers.
Did you try to echo it in PHP?
<?php if($foo) {
echo "<script> js_func(); </script>";
}else{
echo "something else";
}

Put php inside of javascript thats inside of php

exactly as title says, I need to put php inside of the javascript that is echoed by php
ex:
<?
echo ('<script language="javascript" type="text/javascript">
if (something) then (some php)')
?>
thats not real code just might help get the idea and please note the best way to do what im trying is this way, if its possible.
You can't do that, PHP is a server-side language, that means it renders when the page loads and not after that.
The solution can be to call a PHP via AJAX, that PHP can have the case conditions and then it will render what you want.
Example:
The javascript (using jQuery):
$(".yourbutton").click(function(event){
event.preventDefault();
$.post("yourPHP.php", {var: somethingdynamicpassedviajavascript},
function(data){
//get ther result
$("#yourdiv").html(data);
}, "html");
});
What this does is place a click event into something with a class named "yourbutton", and when you click that, it will call an external PHP via an AJAX post, sending a var (in this example), you can send something dynamic, change the "somethingdiynamicpassedviajavascript" with some var.
PHP (yourPHP.php):
$myvar = $_REQUEST['var'];
//do your cases here:
switch ($myvar) {
case "1":
echo "this is for the case 0";
break;
case 1:
echo "this is for the case 1";
break;
}
Here you get that var, and depending on the case, send a different output.
Notice that this may need to add a test for POST and other anti-vandalism methods...
yes you can do that.. your php scirpt generates/echoe the javascript code in your html page.
You just need to play with single and double quotes and escape them properly
In large scripts this is quite messy - better to put your js code in a seperate js file
if you're trying to dynamically create a javascript based on some conditions you're looking for something link this:
<script language="javascript" type="text/javascript">
<?
if ($something == $somethingelse)
{
echo 'var something = 10;';
}
else
{
echo 'var somethingelse = 25;';
}
?>
</script>
if you're to execute php-code via javascript ... that can't really be done, at best you can use PHPjs to emulate php-functions.
u may try this
<?php
echo ('<script language="javascript" type="text/javascript">
if (something) then (some php)')
echo ('</script>');
?>

Calling JavaScript within Php block and vice-versa

echo "<a href=#> Delete </a>";
Whenever a user hits Delete, a javascript function should be called for confirmation. Somewhere in the Javascript function, php code should be used for delete operation. How do I do that? Use something like "some php code goes here" and "some javascript function();" for me to know where to put what. Thanks.
This assumes that you are using jQuery...
<a href='javascript:delete();'>Delete</a>
<script type="text/javascript">
function delete()
{
$.post("/your_script.php", {}, function(result) {
});
}
</script>
JavaScript functions execute on the client (in the browser) and PHP executes on a server. So, the JavaScript must send a message - via HTTP - to the server to be handled by PHP. The PHP would perform the delete. Make sense?
The message sent to the server might be sent via AJAX.
Maybe you should use Ajax: http://en.wikipedia.org/wiki/Ajax_%28programming%29
PHP is a server-side technology, while JS is a client-side. They cannot interact with each other - in other words: they're completely independent.
PHP can only output code that is a JS code:
echo 'document.getElementById("test").appendChild(document.createTextNode("' . $myVar . '");';
It's all PHP can do. JavaScript cannot direct interact with PHP as well. You'll have to use AJAX to send a new HTTP request and process returned data.
PHP is a server-side language, thus you can not output PHP script to the browser and expect that it will parse it with the PHP engine.
What you're looking for is probably AJAX, or simply redirecting the user to another page (with different URL parameters) or submitting a form.
AJAX doesn't require from the browser to reload the page, while the two other methods does.
Anyway, you can execute a JS script with the "onclick" method, that's executed when the user clicks on the element: Delete
But the following approach looks better and considered as an ideal one:
Delete
<script type="text/javascript">
document.getElementById("myId").onclick = myFunc;
</script>
Since this involves Ajax, let's assume you can use jQuery to handle the XHR an so on.
<script>
$('#del').click(function(ev){
ev.preventDefault();
var del_conf=confirm('Are you sure you want to delete this item?');
if(del_conf){ $.post('delete.php',{'del':1,'id':123123},function(data){
alert(data.result);},'json');
}
});
</script>
<a id='del'>Delete</a>
Okay, so that's some JS and HTML. Now, you need a separate PHP script to handle the post. To go with the example, this would be saved in the same directory, named 'delete.php'.
<?php
$del=(int)$_POST['del'];
$id=(int)$_POST['id']
if($del<1 || $id<1){ exit; }
else{
//do your DB stuff
}
if($db_success){
echo json_encode(array('result'=>'success'));
}
else{
echo json_encode(array('result'=>'error'));
}
here is another example using jQuery:
<div id="message"></div>
<a class="action" type="delete" rel="1234567">delete</a>
<script type="text/javascript">
$('a.action').click(function(){
var $this = $(this);
var processResponse = function(data){
//optionaly we can display server response
$('#message').html(data);
return;
};
var postPparams = {
module:'my_module_name',
action:$this.attr('type'),
record_id: $this.attr('rel')
};
$.post('/server.php',postPparams, processResponse);
});
</script>

How do I run PHP code when a user clicks on a link?

I want to have a page run some PHP code when a user clicks on a link, without redirecting them. Is this possible with
or with the javascript onclick event?
Yeah, you'd need to have a javascript function triggered by an onclick that does an AJAX load of a page and then returns false, that way they won't be redirected in the browser. You could use the following in jQuery, if that's acceptable for your project:
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function doSomething() {
$.get("somepage.php");
return false;
}
</script>
Click Me!
You could also do a post-back if you need to use form values (use the $.post() method).
As others have suggested, use JavaScript to make an AJAX call.
whatever
<script>
function myJsFunction() {
// use ajax to make a call to your PHP script
// for more examples, using Jquery. see the link below
return false; // this is so the browser doesn't follow the link
}
http://docs.jquery.com/Ajax/jQuery.ajax
If you haven't yet installed jquery (because you're just a beginner or something), use this bit of code:
link
<script type="text/javascript">
function thisfunction(){
var x = new XMLHttpRequest();
x.open("GET","function.php",true);
x.send();
return false;
}
</script>
I know this post is old but I just wanted to add my answer!
You said to log a user out WITHOUT directing... this method DOES redirect but it returns the user to the page they were on! here's my implementation:
// every page with logout button
<?php
// get the full url of current page
$page = $_SERVER['PHP_SELF'];
// find position of the last '/'
$file_name_begin_pos = strripos($page, "/");
// get substring from position to end
$file_name = substr($page, ++$fileNamePos);
}
?>
// the logout link in your html
Log Out
// logout.php page
<?php
session_start();
$_SESSION = array();
session_destroy();
$page = "index.php";
if(isset($_GET["redirect_to"])){
$file = $_GET["redirect_to"];
if ($file == "user.php"){
// if redirect to is a restricted page, redirect to index
$file = "index.php";
}
}
header("Location: $file");
?>
and there we go!
the code that gets the file name from the full url isn't bug proof. for example if query strings are involved with un-escaped '/' in them, it will fail.
However there are many scripts out there to get the filename from url!
Happy Coding!
Alex
You cant run PHP when a user clicks on a link without leaving the page unless you use AJAX. PHP is a serverside scripting language, meaning the second that the browser sees the page, there is no PHP in it.
Unlike Javascript, PHP is ran completely on the server, and browser wouldn't know how to interpret it if it bit them on the rear. The only way to invoke PHP code is to make a Page request, by either refreshing the page, or using javascript to go fetch a page.
In an AJAX Solution, basically the page uses javascript to send a page request to another page on your domain. Javascript then gets whatever you decide to echo in the response, and it can parse it and do what it wants from there. When you are creating the response, you can also do any backend stuff like updating databases.
There is the only better way is AJAX as everyone is suggest in their posts.
The alternative is using IFrames like below:
<iframe name="f1" id="f1"> </iframe>
<a href='yourpage.php' target='f1'>Click </a>
Now you will get the output in IFrame (you can place IFrame wherever you need in the page or event hide it and the result from the script).
Hope for non Ajax solution this is better.
Well you said without redirecting. Well its a javascript code:
Whatever!
<script type="text/javascript">
function confirm_delete() {
var delete_confirmed=confirm("Are you sure you want to delete this file?");
if (delete_confirmed==true) {
// the php code :) can't expose mine ^_^
} else {
// this one returns the user if he/she clicks no :)
document.location.href = 'whatever.php';
}
}
</script>
give it a try :) hope you like it
either send the user to another page which does it
Execute PHP
or do it with ajax
<script type="text/javascript">
// <![CDATA[
document.getElementById('link').onclick = function() {
// call script via ajax...
return false;
}
// ]]>
</script>
...
Execute PHP
<a href='javascript:void(0)' id='yourId'>Click Me</a>
$(document).ready(function() {
$("#yourId").click(function() {
$.get("yourpage.php");
return false;;
});
});
This should work as well
Submit
<script type="text/javascript">
function callFunction()
{
<?php require("functions.php"); ?>
}
</script>
Thanks,
cowtipper

Categories