In jquery use php variable to execute the jquery - php

I am loading some jquery within a Wordpress page, the jquery works as I want it to but now I need to have that jquery only fire if a php variable exists.
In php I would just do:
if( $foo ) {
do this;
}
In Wordpress I am enqueuing the a file bla.js that contains this:
jQuery(document).ready(function($){
$('#someID.some-class > a').append('<div class="caption"></div>');
$(".caption").text("Add this text");
});
I am confused as how to add the php check if $foo exits. There seems to be several approaches but all I end up doing is producing an unexpected token error.

Javascript exists only on the clients computer in their browser; PHP only exists on the server, far away from their browser, so your JS can't just use the PHP variable. You can do it two ways:
Only include the JS if the variable is true:
<?php if ($foo) : ?>
jQuery(document).ready(function($){
$('#someID.some-class > a').append('<div class="caption"></div>');
$(".caption").text("Add this text");
});
<?php endif; ?>
Or set a JS variable from the PHP variable:
jQuery(document).ready(function($){
var foo = <?php echo $foo; ?>;
if (foo) {
$('#someID.some-class > a').append('<div class="caption"></div>');
$(".caption").text("Add this text");
}
});
Note that in either case, the page is "created" on the server with PHP. Once it's displayed in the browser, you can't use PHP variables. If you need to call another PHP page to check some additional stuff, look at Ajax.

So php is a server side language, javascript is a front end language. So basically php runs then javascript runs...so basically if $foo exists output the jquery you want to run and it will display on the front end. If it doesn't exists output different jquery that you want to run....here is as simple example...
<!-- JS -->
var foo = <?php echo $foo; ?>
if (foo == 'test'){
} else {
}
// More PHP based
if ($foo == "test"){ ?>
javascript function() <!-- Note how I closed php -->
<? } else { ?>
javascript function2()
<? } ?>

PHP and jQuery (which is a framework written in Javascript) run in entirely different scopes.
PHP is executed on the server and the generated result is the HTML page (which will likely include some Javascript code).
That resulting page is then delivered from the server to the browser and when the browser renders it, the jQuery/Javascript will execute.
The key part is that the PHP code is actually generating the HTML and Javascript code.
So, if you'd like to run some jQuery code only if a PHP variable exists:
<?php
if( $foo ) {
?>
<script type="text/javascript"> /* Some jQuery stuff here */ </script>
<?php
} else {
?>
As an example, I generate this text in the "else" condition.
<?php
}
?>
If $foo is true then PHP will generate this HTML:
<script type="text/javascript"> /* Some jQuery stuff here */ </script>
otherwise, PHP will generate this:
As an example, I generate this text in the "else" condition.
Keep in mind that once PHP has delivered the page to the browser, it is no longer running, and the generated result will be "permanent". At that point, the page is loaded into the browser DOM (document object model) and the DOM can only be changed through Javascript.

Put the Javascript inside the PHP conditional.
<script type="text/javascript>
...
<?php
if ($foo) : ?>
jQuery(document).ready(function($){
$('#someID.some-class > a').append('<div class="caption"></div>');
$(".caption").text("Add this text");
});
<?php endif ?>
...
</script>

Usually i just create a hidden input like so:
<input type='hidden' id='some_id' value='the_value'>
Note that I don't add the name attribute so it doesn't get posted (if it happens to be in a form).
Then you can access it with jQuery by its id.
if($('#some_id').val() == what_you_want)
{
do_something();
}

Related

using javascript in PHP [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 9 years ago.
i have this php and js code:
<script type="text/javascript">
function StartScript(script)
{
<?php require("StartScript.php"); ?>
}
</script>
Start
How can i get the "script" from the javascript function onto the end of the php file?
for example rather than:
<?php require("StartScript.php"); ?>
to have:
<?php require("StartScript.php?script=scriptname"); ?>
The full excerpt (provided that StartScript.php at the same level of current page, otherwise add absolute path):
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
function StartScript(script) {
jQuery.getScript('StartScript.php?script=' + escape(script));
}
</script>
This will call StartScript.php with the parameter script. StartScript.php will generate the JavaScript code which will be executed in the client browser.
Reference: http://api.jquery.com/jQuery.getScript/
It's impossible to write server-side code (PHP) with a client-side code (Javascript). This will not work unless you use something like Ajax.
Maybe I misunderstood your question but this seems pretty easy...I would include all the js in the php file so the html side of things would have only....
<?
$script = "Page1";
include("StartScript.php");
?>
and the php would be...
<? if ($script == "Page1"){ ?>
function StartScript(script)
{
alert("IN");
}
</script>
<? } ?>
The problem is that you're mixing up the client (JS) and the server (PHP). PHP is executed on the server and produces some HTML which gets sent to the browser ("the client"). Browsers cannot run PHP because it's a server-side language.
You should evaluate what the desired interaction is between the client and the server here. For example, if you just need to execute some PHP to pass data to JavaScript, you can build up a JavaScript object:
<script type="text/javascript">
<?php // include script that gives you back some data, e.g.: ?>
<?php $somePhpData = array('red', 'yellow', 'blue'); ?>
<?php $jsonData = json_encode($somePhpData); ?>
var dataFromPhpScript = <?php echo $jsonData; ?>
// do something with the data
</script>
Otherwise, if you really need JavaScript to trigger a PHP script running, you're essentially doing AJAX. You'll likely want some sort of REST API. The idea is that you expose a URL from PHP that the JavaScript can call:
<script type="text/javascript">
jQuery(document).ready(function() {
function startScript(scriptName, success) {
$.get('/path/StartScript.php?script-name=' + scriptName)
.done(success)
.fail(fail);
}
startScript('name-of-php-script', function(data) {
// trigger some JavaScript that relies on the output of the PHP script
});
});
</script>

PHP code in JavaScript to get variable

When I press on any of the ‘region’ names in the list ('href' links), the matching list of 'cities' is showing underneath.
<?php while(has_list_regions()) { ?>
<?php } ?>
<script type="text/javascript">
function show_region(chosen_region_id)
{
;
$(this).slideDown(200);
;
<?PHP $clicked_tag = 'chosen_region_id'; ?>
}
</script>
Is it possible to include PHP code within a section of JavaScript? Because I need to get the ID of the selected ‘href’ that I clicked. I am trying to include the PHP code in the above JavaScript function but it doesn’t work.
PHP runs on the server, generates the content/HTML and serves it to the client possibly along with JavaScript, Stylesheets etc. There is no concept of running some JS and then some PHP and so on.
You can however use PHP to generate the required JS along with your content.
The way you've written it won't work.
For sending the value of clicked_tag to your server, you can do something like (using jQuery for demoing the logic)
function show_region(chosen_region_id) {
...
$.post('yourserver.com/getclickedtag.php',
{clicked_tag: chosen_region_id},
function(data) { ... });
...
}
In your script the variable chosen_region_id is already in the function so you don't really need to declare it again with PHP.

inserting JQuery function into php

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

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>');
?>

php in javascript?

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?

Categories