Ok , so what I'm trying to do is trigger PHP code, only when the if condition is true (in javascript) , I understand that php is server side, and javascript is client side. The include of the php code works perfect except 1 thing , it gets triggered on page load actually , not when the if condition happens. If you can help me how to do this will be rly appreciated. I want the php file to be included ONLY when the if condition is true
thanks in advance
here's the code am using :
<html>
<script src="//cdnjs.cloudflare.com/ajax/libs/visibility.js/0.5/visibility.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script>
var seconds=20;
var flag=false;
$(document).ready(function(){
if (!flag)
Visibility.every(1000, tick);
function tick()
{
display();
if (seconds>0)
{
seconds--;
}
else
{
if (!flag){
document.getElementById('more').innerHTML +="<?php include_once('Code.php');
?>";
document.getElementById('more').style.visibility='visible';
flag=true;
}
}
}
function display()
{
$("#timer").html(seconds);
}
});
</script>
<div id="TrafficHeader" style="height:100px; background-color:grey; padding:20px;">
<div id="timer"></div>
<div id="more" style="visibility: hidden;">View Next Ad</div></div>
<iframe id="myframe" src="<?php echo ''.$URL;?>" height="100%" width="100%" frameborder="0">
</iframe>
</body>
</html>
This is not possible, at least not the way you are going about it.
The reason is that the if condition is evaluated on the client machine long after the server finish evaluating your php script.
First server has to finish procesing your php script, then imagine it has to pack it and then send the whole package to the client, which then unpacks it and renders the html and evaluates the javascript in html, or asks for external files like images, css or other script files.
If you are trying to include some extra javascript ,than you can add extra script tag in the head programatically. If you want to do something on the server, you can call a script on a server just as easily.
Here is how you can exeecute that script from javascript only if the if is true:
...
if (!flag){
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", "http://link/to/your/code.php?and=special¶meters=sent", false );
xmlHttp.send( null );
document.getElementById('more').innerHTML += xmlHttp.responseText;
document.getElementById('more').style.visibility='visible';
flag=true;
}
...
The php code is server side so it's executed before the javascript so javascript CAN'T control what php does. You need to use an Ajax script to make javascript can request a php file from the server, and then it'll work.
You can't do it that way... you said it yourself, PHP is server-side. In order to run PHP, you have to have the browser query something against your web server. This will most definitely not work as you intended... it'll always be included:
innerHTML +="<?php include_once('../../Includez/Traffic/Traffic_Code.php'); ?>";
You can, however, cause the JavaScript to fetch something more from the server which can run some PHP code and return something new to your page...
Did you try solution with "load"?
<div id="special_block"></div>
<script>
var a = 1;
if (a == 1){
$('#special_block').load('code.php');
}
</script>
Related
I'm new at dealing with web programming and not used to dealing with the flow of data through a site.
I was looking for a way to call PHP from Java Script or from HTML and came across the following code with many other answers from this site. One thing that I got from Stack Overflow was that Ajax was the only good way to do this and JQuery would be the best way to go about that.
Is the code below safe? Are there holes in it that I don't know about at this point of learning?
<?PHP
$a="hello";
?>
<script>
function echoHello(){
alert("<?PHP hello(); ?>");
}
</script>
<?PHP
FUNCTION hello(){
GLOBAL $a;
ECHO $a;
}
?>
<button onclick="echoHello()">Say Hello</button>
This is not AJAX, but server-side code that only loads at first request.
A mockup of your functionality using AJAX is:
functions.php file:
<?php
$clientSideMethodRequested = $_POST['method'];
if ($clientSideMethodRequested == "sayhello"){
tellHimHello();
}
function tellHimHello(){
echo 'Hello!';
}
?>
client-side AJAX call:
$(document).ready(function(){
$.ajax({
type: "POST",
url: "mydomain.com/functions.php?method=sayhello",
success: function(returnedString){
alert(returnedString);
}
});
});
It will not work. PHP is executed on server, JS is executed in your browser. When you are opening page, the server will at first interpret your code. The result of your code, after this will be like that:
<script>
function echoHello(){
alert("hello");
}
</script>
<button onclick="echoHello()">Say Hello</button>
As you see, everything what was between <?php and ?> was "removed" from the origin file. By "removed" I mean executed.
Sometimes, when your server is not configured to interpret PHP, you will see PHP code in page source in browser. But it still won't work, because no browser supports PHP.
PHP is a server side language, so the code that your browser will "receive" will contain nothing related to PHP. What will happen is that this PHP file will be parsed and executed still in the server, and your browser will get only the following code:
<script>
function echoHello(){
alert("hello");
}
</script>
<button onclick="echoHello()">Say Hello</button>
which is the result of your server's PHP execution. This might be just what you expected in this particular case, but what if we wanted to pass parameters to echoHello function?
<script>
function echoHello(speech){
alert("<?PHP hello(speech); ?>");
}
</script>
<?PHP
FUNCTION hello($speech){
return $speech;
}
?>
<button onclick="echoHello('hello')">Say Hello</button>
<button onclick="echoHello('bye')">Say Bye</button>
One could expect this to alert 'hello' when the user clicks the first button, or 'bye' for the second one. This is not true, as the server starts executing this code before the buttons even exist (as they will only exist when the browser downloads the processed document to render the elements), and thus won't even be able to execute echoHello since speech isn't a valid variable. For this case and many others, AJAX is indeed the most appropriate way to go.
This tutorial should be good for a start.
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";
}
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>
i need to have some php code inside javascript
<script ...>
<?php
echo " ... ";
?>
</script>
but this doesnt work. how can u implement php inside javascript that is in a own file javascript.php?
That doesn't do what you probably think it does. It'll work, but the PHP gets run once, when the page is loaded, not every time the JavaScript function is called.
Just for clarification, this is what will happen
index.php
<script type="text/javascript">
<?php echo "alert('hello!');"; ?>
</script>
output html in browser
<script type="text/javascript">
alert('hello!');
</script>
If that is what you want to do, then you can output all the javascript you like. What you cannot do is execute PHP code in the user's browser.
your can use php to dynamically generate javascript code, but you cannot execute php client side. If you need to execute php you will need to postback or use AJAX
There seems to be a good bit of misunderstanding of the question... Here is what you want to do to generate JS from PHP on the server:
file javascript.js.php
<?php
header('Content-Type: text/javascript');
?>
// javascript code here
function PrintTime()
{
alert("The time is " + <?php echo json_encode(time()); ?>);
}
Now, include it on the HTML page using normal script tags:
<script type="text/javascript" src="/url/to/javascript.js.php"></script>
The server will process the PHP file, and return javascript from it.
You can't run PHP inside a javascript file. Primarily because PHP runs server side and is processed before the client is sent any actual http info. JavaScript is processed by the browser on the client side and is sent as text.
It looks like you want to pass some kind of dynamic info to the JavaScript. You can do this by passing a variable like this:
<?php $variable="its me"; ?>
<script>
alert('<?php print($variable)?>')
</script>
The output passed to the client is:
<script>
alert('its me')
</script>
What are you trying to accomplish and maybe we can help you come up with a better solution?
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