PHP code in JavaScript to get variable - php

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.

Related

In jquery use php variable to execute the jquery

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();
}

Calling a PHP function through an HTML Link (no form)

I have a PHP Function that I would like to integrate into my (existing) web page. Further, I would like it to execute when the user clicks a link on the page. The function needs to accept the text of the link as an input argument.
Everything I've researched for sending data to a PHP script seems to involve using forms to obtain user input. The page needs to accept no user input, just send the link-text to the function and execute that function.
So I guess the question is two-part. First, how to execute a PHP script on link click. And second, how to pass page information to this function without the use of forms. I am open to the use of other technologies such as AJAX or JavaScript if necessary.
EDIT:: Specifically what I am trying to do. I have an HTML output representing documentation of some source code. On this output is a series of links (referring to code constructs in the source code) that, upon being clicked, will call some python function installed on the web server (which leads me to think it needs called via PHP). The python function, however, needs the name present on the link as an input argument.
Is there some sort of interaction I could achieve by having JavaScript gather the input and call the PHP function?
Sorry for the vagueness, I am INCREDIBLY new to web development. If anything is unclear let me know.
You'll need to have a JS function which is triggered by an onclick event which then sends an AJAX request and returns false (so it won't be redirected to a new page in the browser). You can do the following in jQuery:
jQuery:
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function doSomething() {
$.get("myfile.php");
return false;
}
</script>
And in your page body:
Click Me!
In myfile.php:
You can add whatever function you want to execute when the visitor clicks the link. Example:
<?php
echo "Hey, this is some text!";
?>
That's a basic example. I hope this helps.
You will need to use AJAX to accomplish this without leaving the page. Here is an example using jQuery and AJAX (this assumes you have already included the jQuery library):
First File:
<script language="javascript">
$(function(){
$('#mylink').click(function(){
$.get('/ajax/someurl', {linkText: $(this).text()}, function(resp){
// handle response here
}, 'json');
});
});
</script>
This text will be passed along
PHP File:
$text = $_REQUEST['linkText'];
// do something with $text here
If you are familiar with jQuery, you could do the following, if you don't want the site to redirect but execute your function:
in your html head:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
the link:
Execute function
in ajax.php you put in your function to be executed.
Maybe something like this:
....
<script>
function sendText(e)
{
$.ajax({
url: '/your/url/',
data: {text: $(e).html()},
type: 'POST'
});
}
</script>
You can use query strings for this. For example if you link to this page:
example.php?text=hello
(Instead of putting a direct link, you can also send a ajax GET request to that URL)
Inside example.php, you can get the value 'hello' like this:
<?php
$text = $_GET['hello'];
Then call your function:
myfunction($text);
Please make sure you sanitize and validate the value before passing it to the function. Depending on what you're doing inside that function, the outcome could be fatal!
This links might help:
http://net.tutsplus.com/tutorials/php/sanitize-and-validate-data-with-php-filters/
http://phpmaster.com/input-validation-using-filter-functions/
Here's an overly simplistic example of what you're trying to do..
Your link:
Some Action
Your PHP file:
<?php
if (isset($_GET['action']))
{
// make sure to validate your input here!
some_function($_GET['action']);
}
PHP is a server side language i.e. it doesn't run in the web browser.
If you want a function in the browser to operate on clicking a link you are probably talking about doing some Javascript.
You can use the Javascript to find the text value contained in the link node and send that to the server, then have your PHP script process it.

Send PHP variable to JavaScript function [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
I have a php file that generates a variable and I would like the variable to be put into a JavaScript function which is called by onclick on the main page. Is this possible to send from PHP to JavaScript?
You can do the following:
<script type='text/javascript'>
document.body.onclick(function(){
var myVariable = <?php echo(json_encode($myVariable)); ?>;
};
</script>
Just write:
<script>
var my_variable_name = <?php echo(json_encode($php_string)); ?>;
</script>
Now it's available as a JavaScript variable by the name of my_variable_name at any point below the above code.
Your JavaScript would have to be defined within a PHP-parsed file.
For example, in index.php you could place
<?php
$time = time();
?>
<script>
document.write(<?php echo $time; ?>);
</script>
If I understand you correctly, you should be able to do something along the lines of the following:
function clicked() {
var someVariable="<?php echo $phpVariable; ?>";
}
A great option is to use jQuery/AJAX. Look at these examples and try them out on your server. In this example, in FILE1.php, note that it is passing a blank value. You can pass a value if you wish, which might look something like this (assuming javascript vars called username and password:
data: 'username='+username+'&password='+password,
In the FILE2.php example, you would retrieve those values like this:
$uname = $_POST['username'];
$pword = $_POST['password'];
Then do your MySQL lookup and return the values thus:
echo 'You are logged in';
This would deliver the message You are logged in to the success function in FILE1.php, and the message string would be stored in the variable called "data". Therefore, the alert(data); line in the success function would alert that message. Of course, you can echo anything that you like, even large amounts of HTML, such as entire table structures.
Here is another good example to review.
The approach is to create your form, and then use jQuery to detect the button press and submit the data to a secondary PHP file via AJAX. The above examples show how to do that.
The secondary PHP file receives the variables (if any are sent) and returns a response (whatever you choose to send). That response then appears in the Success: section of your AJAX call as "data" (in these examples).
The jQuery/AJAX code is javascript, so you have two options: you can place it within <script type="text/javascript"></script> tags within your main PHP document, or you can <?php include "my_javascript_stuff.js"; ?> at the bottom of your PHP document. If you are using jQuery, don't forget to include the jQuery library as in the examples given.
In your case, it sounds like you can pretty much mirror the first example I suggested, sending no data and receiving the response in the AJAX success function. Whatever you need to do with that data, though, you must do inside the success function. Seems a bit weird at first, but it works.
You can pass PHP values to JavaScript. The PHP will execute server side so the value will be calculated and then you can echo it to the HTML containing the javascript. The javascript will then execute in the clients browser with the value PHP calculated server-side.
<script type="text/javascript">
// Do something in JavaScript
var x = <?php echo $calculatedValue; ?>;
// etc..
</script>

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

call php class functions through jquery

I have a dropdown which i want to fill through jquery. Problem that i am facing is that i want to call a class function directly from jquery. eg
My class_function PHP class contains get_locations function. how can i call this get_locations function using jquery .post method without introducing a third page?
The way I usually do that is to have an if statement at the top of the php page checking for a special mode.
jquery
$.get(
'page.php?mode=ajaxGetLocations&someVar=' + $('#someVar').val(),
function(data) { $('#myDropDown').html(data); }
);
PHP - near the top of the code
<?php
if (isset($_REQUEST['ajaxGetLocations'])
{
$someVar = $_REQUEST['someVar'];
// Get your data here
// Output your select box here
?>
<select>
...
</select>
<?php
exit; // You don't want to keep processing the page
}
?>
Have your PHP page upgraded with
if (isset($_GET['get_locations'])) {
echo $this->get_locations();
return;
}
and call it from jQuery with
$.ajax({
//..
data: "get_locations=1",
//...
});
You can't, because jQuery and PHP run in entirely different environments - PHP on the server, jQuery on the client. jQuery runs after PHP is done.
You want to look into jQuery's Ajax functions to find out how to call a PHP script from Javascript.
Ajax is used to make an HTTP request from the browser, using JavaScript, without leaving the page.
so you cant call a class function directly... but you can handle it by allowing the constructor to call this function depending on the parameters you have passed

Categories