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>');
?>
Related
I am trying to use some jQuery functions inside of my php page which I am using for a wordpress plugin. I have imported the jquery api using the below code however I'm not sure how to write the function.
<?php
echo "Custom Book Settings Page";
echo '<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>';
this produces syntax error
<?php
$("#form1").submit(function() { $.post("customBook-index.php"); return false; alert ("submit form 1"); });
?>
Like the others have said, you can't use JavaScipt (or any of its libraries) inside PHP. You certainly can, however, use PHP to print out JavaScript which will be run at the appropriate time.
<?php echo "<script type='text/javascript'>
$(document).ready(function(){
$('#form1').submit(function() {
$.post('customBook-index.php');
return false;
alert ('submit form 1');
});
});
</script>";
?>
why wouldnt you just have the syntax without the tags?
$("#form1").submit(function() { $.post("customBook-index.php"); return false; alert ("submit form 1"); });
if you have to have php write the statement, you forgot the echo
<?php
echo '$("#form1").submit(function() { $.post("customBook-index.php"); return false; alert ("submit form 1"); });';
?>
You cannot use jQuery like that within your PHP. JQuery is a JavaScript library. It is essentially code that is pre-written for you and abstracted in such a way that it makes it easy to use. When you call $('#myElementId) you are calling an abstraction of a JavaScript function (or set of functions).
Using jQuery within PHP won't work, because the PHP interpreter has no way to make sense of it. It would be like speaking giving instructions in Chinese to a (monoglot) Anglophone. Furthermore, there is a significant difference between PHP and JavaScript in as much as PHP is executed on a web server, and JavaScript is executed on a client's machine. This is an important concept to understand for any web programmer.
In short, you either need to write your JS function into a <script> tag on the page such that the navigator parses it as JavaScript, or determine the PHP equivalent for what you are trying to do.
// turn off php
?>
$("#form1").submit(function() {
$.post("customBook-index.php");
return false;
alert ("submit form 1");
});
<?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);
I am wondering whether this is possible:
I have a page. The user clicks a link and that calls a PHP script. The PHP script returns true or false.
Depending on the true or false, I was hoping to be able to toggle a div.
I am wondering whether I need to do it the AJAX way? How do people usually accomplish this?
Seems pretty common.
I am using this YUI library already:
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/combo?2.8.2r1/build/reset-fonts-grids/reset-fonts-grids.css&2.8.2r1/build/base/base-min.css">
jQuery:
$.post('/path/to/url', {data: 'some data'}, function(data) {
if (data) $('#some-div').show();
else $('#some-div').hide();
}, 'json');
PHP:
echo json_encode(true);
For more information see:
http://api.jquery.com/category/ajax/
http://php.net/manual/en/function.json-encode.php
Yes, you should use AJAX to create a good flow in your site. Instead of implementing your own AJAX handling functions, you could use one of the big JavaScript frameworks, I recommend http://jquery.com/. There, you can read about (and see examples of) jQuery.ajax - http://api.jquery.com/category/ajax/.
This should get you started, but the main idea is to bind that link to an AJAX function, that will call your PHP script, and based on the contents of the returned data, toggle your DIVs on/off.
Good luck!
Set the php script to add a hidden field ... such as...
<input type="hidden" id="passed-value" value="passed-val-is-true" />
Then in your Javascript when you fire the toggle event .. check that element ...
In jQuery would be something like this ...
$foo.click(( if (passed-value.value === "passed-val-is-true") { foo.toggle(); }
Sorry for syntax .. but you should get the general idea.
Also, if you need it to do without page reload, i would def recommend Ajax (pref via jQuery)
Yes, very easy, no need for Ajax. Here's two ways:
Using straight PHP:
<?php
if($test) {
echo "<div>Content...</div>";
}
?>
Or, using inline Javascript (in the PHP script), assuming you have a <div id='targetDiv'> in your HTML, and a $testVar in your PHP:
<script type='text/javascript'>
function toggle(testVar) {
if(testVar) { document.getElementById('targetDiv').style.display = ""; }
else { document.getElementById('targetDiv').style.display = "none"; }
}
window.onload = function() { toggle(<?php echo $testVar; ?>); }
</script>
The second method can be easily altered to degrade gracefully.
I can access a PHP var with Javascript like this:
<?php
$fruit = "apple";
$color = "red";
?>
<script type="text/javascript">
alert("fruit: " + "<?php echo $fruit; ?>"); // or shortcut "<?= $fruit ?>"
</script>
But what if I want to use an external JS file:
<script type="text/javascript" src="externaljs.js"></script>
externaljs.js:
alert("color: " + "<?php echo $color; ?>");
You don't really access it, you insert it into the javascript code when you serve the page.
However if your other javascript isn't from an external source you can do something like:
<?php
$color = "Red";
?>
<script type="text/javascript">var color = "<?= $color ?>";</script>
<script type="text/javascript" src="file.js"></script>
and then in the file.js use color like so:
alert("color: " + color);
You can also access data from php script in Javascript (I'll use jQuery here) like this
Create input hidden field within you php file like this
<input type="hidden" id="myPhpValue" value="<?php echo $myPhpValue ?>" />
in your javascript file:
var myPhpValue = $("#myPhpValue").val();
//From here you can the whaterver you like with you js Value
if(myPhpValue != ''){
//Do something here
}
This will do the job as well :)
What I've seen done is let .js files run through the php interpreter. Which I can not recommend.
What I do recommend is fetching the values through AJAX and have the PHP file return the value to the JS file. Which is a much cleaner method.
First of all you have to understand that no program can actually have access to the other program's variable.
When you realize that, the rest is simple.
You can either set up a js variable in the main file and then include your external js, or make this external js dynamic, generated by PHP as well
What you likely want, is called Asynchronous JavaScript and XML (AJAX): http://www.w3schools.com/ajax/default.aspa
Basically, imagine being able to send messages from the clients JavaScript to your PHP scripts on the server. In the example you gave (externaljs.js), you would have the script ask the server what $color is, via HTTP. You can also point the script tag at a PHP script that generates the JavaScript you want. It depends on what you need to do.
It helps to have some understanding of taint checking, data verification, and security ;)
As the others are saying, javascript doesn't have access to php variables. However, it does have access to the DOM. So, you can use php to add attributes to some page element. And then you can access those attributes with javascript.
e.g. <div id='apple' class='red'> is completely available to javascript
Don solution is good, furthermore if you want to use a php array in an external javascipt this can help you:
PHP:
<?php
$my_php_array = [];
?>
HTML:
<script type="text/javascript"> var my_js_array = <?php echo json_encode($my_php_array);?> ; </script>
<script src = "../public/js/my-external-js.js"></script>
Javasript: (You can now use the array like a normal Javascript array)
my_js_array[0]
my_js_array.length
externaljs.js is a static file. Of course it can't access PHP data. The only way to pass PHP data to a js file would be to physically alter the file by writing to it in your PHP script, although this is a messy solution at best.
Edit in response to Ólafur Waage's answer: I guess writing to the js file isn't the only way. Passing the js through the PHP interpreter never crossed my mind (for good reason).
<script type="text/javascript" src="externaljs.js"></script>
You could change it to
<script type="text/javascript" src="externaljs.php"></script>
And the PHP script could just write JavaScript like that :
<?php
$fruit = "apple";
echo 'var fruit = '.json_encode($fruit);
...
Though using AJAX like said Sepehr Lajevardi would be much cleaner
2017-2018 and above solution:
Since nobody bringed it up yet and I guess no one thought of combining the functions base64_encode and json_encode yet, you could even send PHP Array variables like that:
index.php
<?php
$string = "hello";
$array = ['hi', 'how', 'are', 'you'];
$array = base64_encode(json_encode($array));
Then you could just load your desired js file with the parameter for a query string like this:
echo '<script type="text/javascript" src="js/main.php?string='.$string.'&array='.$array.'">';
Then js/main.php will look like this for example. You can test your variables this way:
js/main.php
<?php
if ($_GET['string']) {
$a = $_GET['string'];
}
if ($_GET['array']) {
$b = $_GET['array'];
}
$b = json_decode(base64_decode($b));
echo 'alert("String $a: + '.$a.'");';
echo 'alert("First key of Array $array: + '.$b[0].'");';
exit();
?>
The following will then output when you open your index.php. So you see, you don't open js/main.php and you still got the javascript functionality from it.
You can include() them just as you would anything else:
<?php
$fruit = "apple";
$color = "red";
?>
<script type="text/javascript">
<?php include('/path/to/your/externaljs.js'); ?>
</script>
This will basically render the external file as inline js. The main disadvantage here is that you lose the potential performance benefit of browser caching. On the other hand, it's much easier than re-declaring your php variables in javascript.
You cant do that and dont try to as this is not a recommended approach, However you can pass php variables as a function parameters to function written in external js
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>