Pass URL into JS function - php

I have a PHP page with where I also use jQuery UI functionality. User drags Item from left panel into a box on the right. After it is dropped a dialog appears. If user clicks the first button he/she is redirected to a URL. I need to be able to change URL based on a user.
I can get the URL into a var or $_SESSION but I can't figure out how do I change it inside my JS function?
Here's the DEMO (drop item into box to get dialog).
UPDATE:
Below are all valid suggestions, however, my problem is that I have most of JS functions in external JS file (dragdrop-client.js).
I have added new var to my main PHP file
var endURL = "http://google.com";
but how do make my function checkLaunchpad() use it?

There are a number of different ways to do it, but often it is as simple as:
<script type="text/javascript">var myURL = '<?php echo $url; ?>'</script>
Where $url is the url you want them to go to (perhaps '/boxes.php?uid='.$_SESSION['id'];?)
That will translate to:
<script type="text/javascript">var myURL = 'http://whatever.and.stuff'</script>
EDIT
You just asked how you would have a function declared on an external JS page use the variable.
Well, fortunately, JS doesn't care when you declare the variable, so long as it has some value before you use it. And, if it doesn't have a value then, it will supply undefined;. This means you can declare functions which rely on global variables which won't exist for another three or for seconds/minutes/years/eons/whatever.
Additionally, the earlier a script tag is on a page, the earlier it will be evaluated -- a variable declared in the first tag will exist when the second js file loads.
So, if you want to have the above work as expected you have two options.
You could define the variable as the first script tag in the body of the page (thus, it is defined before checkLaunchpad is.
<script type="text/javascript">var myURL = '<?php echo $url; ?>'</script>
<script type="text/javascript" src="path/to/js"></script>
Or, if checkLaunchpad isn't called until after the body has loaded, you can place the definition anywhere in a script tag!

Find below code to redirect users to new page
<script type="text/javascript">
var endURL = "http://google.com";
function checkLaunchpad(url) {
location.href=url;
return false;
}
</script>
Test
for more reference check http://snook.ca/archives/javascript/global_variable

I would say store the url in a hidden field like:
<input id="hidUrl" type="hidden" value="<?php echo $url ?>"/>
And then change your javascript so it uses the value:
window.location = $("#hidUrl").val();

Related

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.

Trying to run php code within a Javascript (.js) file

First off I am very new to php so bear with me. I have a javascript (.js) file from a wordpress template that reads the key from var googledockey. In order to change it I have to manually open the .js file and change that variable. What I would like to do is have the .js file grab the key from where it was saved on a page I made. Here is the code for the admin page that has the textfield for me to enter in a key.
<?php
if($_POST['gdocs2wp_hidden'] == 'Y') {
//Form data sent
$gdkey = $_POST['gdocs2wp_gdkey'];
update_option('gdocs2wp_gdkey', $gdkey);
?>
<div class="updated"><p><strong><?php _e('Options saved.' ); ?></strong></p></div>
<?php
} else {
//Normal page display
$gdkey = get_option('gdocs2wp_gdkey');
}
?>
The key saves and whenver I open the page they key shows up so I know this half is working. This is where I am stumped. Within my .js file which is in a subdirectory of the admin page, the var googledockey is where I have had to manually save the key which works everytime. I have tried <?php echo $gdkey; ?> and get_option('gdocs2wp_gdkey'); to try and get the key but I havent had any luck. Can php work within a .js file? Does anyone have any insight to help me along? Thanks
var jqueryNoConflict = jQuery;
//var googledockey = <?php echo $gdkey; ?>
var googledockey = "INSERTmyKEYhere";
// begin main function
jqueryNoConflict(document).ready(function(){
initializeTabletopObject(googledockey);
});
You could always have the JS run an Ajax call to get the data. Alternatively, you could move the variable declaration to the PHP/HTML file where you include the JS, and just add
<script type='text/javascript'>
var googledockey="<?echo $gdkey;?>"
</script>
1. Register your script
Create a JavaScript file, place it in your theme folder, and register it with WordPress.
wp_register_script(
'google-docs',
get_bloginfo('template_directory') . '/scripts/google-docs.js'
);
Documentation: http://codex.wordpress.org/Function_Reference/wp_register_script
2. Enqueue your script
Whenever your script is needed in a template, you enqueue the file.
wp_enqueue_script(
'google-docs'
);
Documentation: http://codex.wordpress.org/Function_Reference/wp_enqueue_script
3. Localize your script
This allows you to make PHP variables available in your JavaScript.
wp_localize_script(
'google-docs',
'google_docs_vars',
array(
'key' => $google_doc_key
)
);
Documentation: http://codex.wordpress.org/Function_Reference/wp_localize_script
4. Use variable in your script
Now you have access to the variable in your script.
var google_docs_key = google_docs_vars.key;
That's it. I think this would solve your problem and it's also the proper way to do it.
JS files are not generally parsed for PHP. The easiest (albeit not the prettiest) way to do this is probably to either:
1) Echo the value in a hidden DOM element in the page template itself, and then use JS to grab that element and set the variable (so, put the value inside a hidden element on the page, or as an attribute or something, then grab that value using JS and assign it to your variable).
2) Similar to above, just put the variable declaration in an inline script (<script>code</script>) because that WILL get parsed for PHP - see Seriyia's answer.
3) Use simple AJAX calls which are really easy with jQuery and let you pass data from JS to a PHP function somewhere else like functions.php and then back to the JS. This might be more trouble than it's worth though if you aren't familiar with AJAX.
This is quite simple
You are recently using this code snipet
var jqueryNoConflict = jQuery;
//var googledockey = <?php echo $gdkey; ?>
var googledockey = "INSERTmyKEYhere";
// begin main function
jqueryNoConflict(document).ready(function(){
initializeTabletopObject(googledockey);
});
Where you need to Replace this with following code
var jqueryNoConflict = jQuery;
var googledockey = "<?php echo $gdkey; ?>"
var googledockey = "INSERTmyKEYhere";
// begin main function
jqueryNoConflict(document).ready(function(){
initializeTabletopObject(googledockey);
});

Declaring a Javascript variable into a PHP form

Preapring for a Facebook competition while I have spare time, the Publish function with facebook has a once posted javascript function that you can define.
What I am looking to do is call a function to write a value unto a php form which will then be posted and submitting data into a database. I have tested to the extent that I know the idea is sound just calling a basic alert, I am just not sure how to get from calling the function to writing the value into the form.
This value I need to be able to call on in the page that the data is being posted to, to base an "if function" off, basically if "True/Yes" then I need it to process another php script in addition to the data its posting to the database
What I have now is:
<script type="text/javascript">
function isShared()
{
alert("Yes");
}
</script>
<input class="fieldbox" name='shared' type='hidden' value="value of 'display_alert()'"/>
I know it cannot be an alert, but this is pretty much where my current javascript skills leave me stranded.
<script type="text/javascript">
function isShared()
{
document.getElementById('xshared').value = 'Yes';
}
</script>
<input class="fieldbox" id="xshared" name="shared" type="hidden" value="" />
This will add the value Yes To the hidden field once isShared is called.
Are you looking to have the form automatically posted without the user clicking anything but the share button? The only reason I ask is that it sounds like what you are looking for is AJAX, to post data to the database silently without the need of the user to navigate away from their current page.
I'm still not 100% clear on what you're asking, but are you just looking to emit a server-side PHP variable into client-side JavaScript code? Something like this?:
<?php
// some code, etc.
$myVariable = "foo"; // some value
// more code, etc.
?>
<script type="text/javascript">
var myVariable = '<?php echo $myVariable; ?>';
// more JavaScript code, etc.
</script>
This would emit to the page as:
<script type="text/javascript">
var myVariable = 'foo';
// more JavaScript code, etc.
</script>
Basically anywhere that you need the literal value from the PHP variable, you'd write:
<?php echo $myVariable; ?>
I am not clear how exactly you are aiming to post the form data but you can set the input value using jquery like this:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
$('#input1').val($('#input1').val() + 'more text');
<input id="input1" class="fieldbox" name='shared' type='hidden' value=""/>

pass variable from input box to php

Hi all i know this question has been posted but being a total noob i couldnt get what answers meant. Please help. I want to pass inputbox value dynamically to a php variable . i am using javascript here please suggest if there's another way without using form submission , _GET or _POST. i want it done dynamically without any submission.
function showHint(str)
{
document.getElementById('TK').innerHTML = str;
var str = str
}
</script>
<html>
<head>Inputbox</head>
<title>TEST PAGE </TITLE>
<body>
<input type='text' id='TK' name='TK' onkeyup='showHint(this.value)'/>
<?php
$str = var str ;
echo "<a href = 'newpage.php?S=$str'/>" ; ?>
</body>
</html>
No. You can't. PHP is NOT a dynamic language, and it does NOT run client side. PHP runs once, and only once, and that's when the page is loaded. It runs its script and it stops. What you can do is get javascript to do an AJAX call. AJAX is basically a way of passing information to another page and getting the data, all in JavaScript. Do some research on it, but in short, you can't make PHP run once it's already been run
<script type="text/javascript" >
function process(){
var field1 = 'whatever';
var field2 = 'more whatever';
$.post("go.php",{field:field1,bext_field:field2},function(result){
alert(result);
});
};
</script>
This will alert out whatever you ECHO from GO.PHP.
You will also need a handler like:
onClick="process();"
on a div, button, image, just about anything you want to "initiate" your post
I would imagine the other answers you found probably would have said the following:
PHP executes before the user has a chance to see the page.
JS let you control what happens after.
Therefore, your problem is that you are trying to use PHP to do something it simply cannot.
Use those points to help guide your decisions when developing your applications. In this case, if you're trying to build a link based on what a user types in a box, your solution to the problem isn't PHP at all (the page is already loaded, you're too late!) -- your solution is JS.
Think about it like this:
/*
assumes you already have an <a> on the page. if not, you'll
have to create a new <a> element dynamically. (google "mdn createElement"
for help)
*/
function showHint (str) {
document.getElementById('TK').innerHTML = str;
var link = document.getElementById('your-a-link');
link.setAttribute('href', 'newpage.php?S=' + str);
}

Access a JavaScript variable from PHP

I need to access a JavaScript variable with PHP. Here's a stripped-down version of the code I'm currently trying, which isn't working:
<script type="text/javascript" charset="utf-8">
var test = "tester";
</script>
<?php
echo $_GET['test'];
?>
I'm a completely new to both JavaScript and PHP, so I would really appreciate any advice.
UPDATE: OK, I guess I simplified that too much. What I'm trying to do is create a form that will update a Twitter status when submitted. I've got the form working OK, but I want to also add geolocation data. Since I'm using Javascript (specifically, the Google Geolocation API) to get the location, how do I access that information with PHP when I'm submitting the form?
The short answer is you can't.
I don't know any PHP syntax, but what I can tell you is that PHP is executed on the server and JavaScript is executed on the client (on the browser).
You're doing a $_GET, which is used to retrieve form values:
The built-in $_GET function is used to collect values in a form with method="get".
In other words, if on your page you had:
<form method="get" action="blah.php">
<input name="test"></input>
</form>
Your $_GET call would retrieve the value in that input field.
So how to retrieve a value from JavaScript?
Well, you could stick the javascript value in a hidden form field...
<script type="text/javascript" charset="utf-8">
var test = "tester";
// find the 'test' input element and set its value to the above variable
document.getElementByID("test").value = test;
</script>
... elsewhere on your page ...
<form method="get" action="blah.php">
<input id="test" name="test" visibility="hidden"></input>
<input type="submit" value="Click me!"></input>
</form>
Then, when the user clicks your submit button, he/she will be issuing a "GET" request to blah.php, sending along the value in 'test'.
As JavaScript is a client-side language and PHP is a server-side language you would need to physically push the variable to the PHP script, by either including the variable on the page load of the PHP script (script.php?var=test), which really has nothing to do with JavaScript, or by passing the variable to the PHP via an AJAX/AHAH call each time the variable is changed.
If you did want to go down the second path, you'd be looking at XMLHttpRequest, or my preference, jQuerys Ajax calls: http://docs.jquery.com/Ajax
_GET accesses query string variables, test is not a querystring variable (PHP does not process the JS in any way). You need to rethink. You could make a php variable $test, and do something like:
<?php
$test = "tester";
?>
<script type="text/javascript" charset="utf-8">
var test = "<?php echo $test?>";
</script>
<?php
echo $test;
?>
Of course, I don't know why you want this, so I'm not sure the best solution.
EDIT: As others have noted, if the JavaScript variable is really generated on the client, you will need AJAX or a form to send it to the server.
If showing data to the user, do a redirect:
<script language="JavaScript">
var tester = "foobar";
document.location="http://www.host.org/myphp.php?test=" + tester;
</script>
or an iframe:
<script language="JavaScript">
var tester = "foobar";
document.write("<iframe src=\"http://www.host.org/myphp.php?test=" + tester + "\"></iframe>");
</script>
If you don't need user output, create an iframe with width=0 and height=0.
try adding this to your js function:
var outputvar = document.getElementById("your_div_id_inside_html_form");
outputvar.innerHTML='<input id=id_to_send_to_php value='+your_js_var+'>';
Later in html:
<div id="id_you_choosed_for_outputvar"></div>
this div will contain the js var to be passed through a form to another js function or to php, remember to place it inside your html form!.
This solution is working fine for me.
In your specific geolocation case you can try adding the following to function showPosition(position):
var outputlon = document.getElementById("lon1");
outputlon.innerHTML = '<input id=lon value='+lon+'>';
var outputlat = document.getElementById("lat1");
outputlat.innerHTML = '<input id=lat value='+lat+'>';
later add these div to your html form:
<div id=lat1></div>
<div id=lon1></div>
In these div you'll get latitude and longitude as input values for your php form, you would better hide them using css (show only the marker on a map if used) in order to avoid users to change them before to submit, and set your database to accept float values with lenght 10,7.
Hope this will help.
Well the problem with the GET is that the user is able to change the value by himself if he has some knowledges. I wrote this so that PHP is able to retrive the timezone from Javascript:
// -- index.php
<?php
if (!isset($_COOKIE['timezone'])) {
?>
<html>
<script language="javascript">
var d = new Date();
var timezoneOffset = d.getTimezoneOffset() / 60;
// the cookie expired in 3 hours
d.setTime(d.getTime()+(3*60*60*1000));
var expires = "; expires="+d.toGMTString();
document.cookie = "timezone=" + timezoneOffset + expires + "; path=/";
document.location.href="index.php"
</script>
</html>
<?php
} else {
?>
<html>
<head>
<body>
<?php
if(isset($_COOKIE['timezone'])){
dump_var($_COOKIE['timezone']);
}
}
?>
JS ist browser-based, PHP is server-based. You have to generate some browser-based request/signal to get the data from the JS into the PHP. Take a look into Ajax.
I'm looking at this and thinking, if you can only get variables into php in a form, why not just make a form and put a hidden input in the thing so it doesn't show on screen, and then put the value from your javascript into the hidden input and POST that into the php? It would sure be a lot less hassle than some of this other stuff right?
<script type="text/javascript">
function gotzpl(){
var query = window.location.search.substring(1);
if(query){
}else{
var timez = Intl.DateTimeFormat().resolvedOptions().timeZone;
if(timez != 'undefined'){
window.location = "https://sks.com/searches.php?tzi="+timez;
}
}
}
</script>
<?php
// now retrieve value from URL and use it in PHP;
// This way you can get script value in PHP
$istzg = $_GET['tzi'];
?>
<body onload="gotzpl()">

Categories