PHP variable creating link for button - php

So I wanted to make an easy way for me to see my school projects. I tried to make in webpage HTML input and output as a clickable link that contains mysite.com/"Input".I tried using PHP variable probably in wrong way.
I tried using PHP variables to make output for the button.
<input type="button" value="View item" onClick="parent.location='/view/<?PHP echo $output ?>.html'"/>
Thanks!

although i do not know how you are going to fetch the php variable and from where, i am giving an option. you can write the function like this:
<?php
$input_vars = 'some-place';
?>
<button onclick="onclickRedirect()">redirect</button>
<script>
function onclickRedirect(){
window.location.href = "http://www.yoursite.com/<?php echo $input_vars ?>";
}
</script>
make sure you do all in a php file. hope this will help you.

Related

how to echo a PHP variable before it has been declared

I have a HTML button:
<button>Button Name</button>
below the button i have a div which i am requiring a file in:
<div id="my_div"><?php require_once 'file.php'; ?></div>
in the file.php file i have a PHP variable, i want to echo this variable on the button name (Button Name var_here)
but its not showing the variable as the variable is being declared after i echo it
is there any way round this?
No. You can not echo out something that is not declared.
Three suggestions:
Rearrange your HTML so that your button is below the declaration. Then use CSS to let your button appear above the div-container.
Change your php scripts so the declaration is done somewhere else before your button.
Use Jscript to change your button (p.e. like Amir Noori suggested).
you can add the variable with javascript
<button>Button Name</button>
<div><?php require_once('your_file.php'); ?></div>
<script> $('#btnID').html('<?php $var ?>')</script>
note:I don't think it is possible to use a variable before declaring it. with my code you actually using it after declaring it.
Is there any reason that you can't do the require before the button? If so, that's the real problem that you're trying to solve, because no, before you put the value in the variable, it isn't in the variable, and hence can't be echoed.
So to answer the question-behind-the-question, it's necessary to know more about what you're trying to do.
Something about this design doesn't sit right with me, you usually include all your php up top, but I understand that for layout reasons you may want to go this way.
One way around it is to set this via javascript. This is a bit hacky (real hacky) but it would work. Use jQuery for ease of JS use after your include:
<script type="text/javascript" >
$('#my_div').text('<?php echo $my_var ?>');
</script>
I have sorted this now. In the required file rather than echoing the results creating a new variable ($var_display.= ...) then echoing $var_display under the HTML button
The file Is being required right at the top of the page

PHP - Call a function from a link\button

I know that PHP is only server-side and it's impossible to call directly a PHP-FUNCTION from a link.
But I can't use JavaScript \ jQuery \ Ajax
This is my code in main.php
function refreshgt2(){
for($l=1; $l!=$max_cicle; ++$l ) {
$data->query("INSERT IGNORE INTO `table` (`name1`,`name1`,`anothername`,`dog`) VALUES ('ME','".$img[$l]."','".$l."','".$hello[$l]."')");
}
}
And the html,
<a href="#" >Do something</a>
I've just tried with this need a button that calls a php function but didn't work for me.
Someone can help me?
I need something that load the function only when I will press the link\button\image
this should work. it gives a button, support multiple function call and is pure php + html
<form action="<?php $_PHP_SELF ?>" method="post">
<input type="hidden" name="function" value="refreshgt2">
<input type="submit">
</form>
<?php
if($_POST!=null && array_key_exists('function', $_POST)){
if(strcasecmp($_POST['function'],'refreshgt2')==0){
for($l=1; $l!=$max_cicle; ++$l )
{
$data->query("INSERT IGNORE INTO `table` (`name1`,`name1`,`anothername`,`dog`) VALUES ('ME','".$img[$l]."','".$l."','".$hello[$l]."')");
}
}else if(strcasecmp($_POST['function'],'some_other_function')==0){
//do things
}
}
?>
But i cant's use a javascript\jquery\ajax
Then the answer is No, you can not. Only option is to link your button to a new page which will generate the PHP output. PHP itself does not know anything about what you do at client side and whether you have clicked a link, PHP functions cannot execute at that time since PHP has already done its job and gone.
If you dont mind a redirect
<a href="your_php_script.php" >Do something</a>
you_php_script.php
<?php
refreshgt2();
If you can't use javascript/ajax (why not? we are in 2013), you can't refresh part of the page on the fly. Your only chance is to call a page like
Do something
and my-script.php then renders the page again after doing some stuff.
Use querystrings, set the href in your html to point to your page, and add a querystring parameter so that your php can decide which function to execute:
HTML
<a href='main.php?fn=some_function'>Do something<a/>
PHP
switch($_GET['fn']) {
case 'some_function':
//call your function
break;
default:
//Handle this
}
Otherwise, redirect to another php script like the other answers mentioned.

jQuery is messing with my PHP

I have a registration form that I'm working on and it's turning out to be a pain.
I'm very new to PHP, so please cut me some slack - haha.
I installed a jQuery plugin that allowed me to make inline labels for my textboxes. I also created an error box for any errors that occur during the registration process (invalid email, etc.). Here's some of my HTML/PHP code.
<?php
if($_POST['submit'])
{
$signuperror = "Hello World";
?>
<?php if($signuperror != "") { ?>
<span id="signuperror"><?= $signuperror; ?></span>
<?php } ?>
The problem was that the "error" of "Hello World" was not displaying when I clicked the submit button on my form. I copied and pasted this code onto a test.php document and it worked fine. So I knew that it had to be from my other html code. After troubleshooting almost every line of code, I found the culprit. It turns out that the jQuery plugin initialization for the inline labels was the problem.
$(function(){
$.fn.formLabels();
$("form").submit(function(){
var formVal = $("form").serialize();
parent.$("#default div.results").html(formVal);
return false
})
});
When I deleted this, it worked just fine (without my inline labels, of course).
What could I do to make BOTH the PHP and jQuery work.
Thanks.
- Ryan
Notice the return false at the end of the $("form").submit() function. That means the jQuery function is taking the place of your form's POST action. You're not reloading the page synchronously, so you don't have any value for $_POST["submit"]. Get rid of the return false line, and see if the page reloads as you're expecting.
There are lot of things here that are going on. Need to do this step by step.
Your PHP should either use <?php format or use <? short form but to be sure i would code all in <?php so its compatible everywhere
When you need to echo or output something use <?php echo $variable; ?> rather than <?=. Not that its no good or so but it will take out any php config issues with asp style output.
First test php output then check if statement.
Jquery is not messing with your PHP. That title is just as random as my answer.

javascript method onclick is executing even submit button is not yet clicked

Im new to php and javascript so please bear with me.
index.php:
<?php
$_SESSION['test'] = 1;
?>
<div>
<?php echo "Before: " . $_SESSION['test']; ?>
<input type="submit" value="CLICK" onclick="<?php $_SESSION['test'] = 0; ?>;" />
<?php echo "After: " . $_SESSION['test']; ?>
</div>
Why is it that $_SESSION['test'] is already 0 when I haven't clicked the button yet??? Please help me...
PHP is a preprocessor. Everything you write in PHP is executed BEFORE the page is presented, while javascript executes clientside as the page is running. Therefore, you cannot set a PHP value with a javascript event.
PHP is a server-side language; it is parsed and run before anything is even sent to the browser. It does not interact with JavaScript.
You will need to use AJAX to call the php set the session on click via javascript. I suggest having a look at XMLHTTPRequest: http://www.w3.org/TR/XMLHttpRequest/ , or if you don't want to read all of that and learn it, I suggest looking at a javascript library such as http://www.jquery.com, which should simplify what you need to do.
You need to call session_start() before anything can be stored in the session.
The way you are trying to do it is impossible.
Use AJAX

PHP variable as part of a jQuery function doesn't work, but plain text does

I have the following jQuery code in my PHP file (edited Jan 19 2010 # 10:40 MST):
<?php
$count = 0;
foreach($attachments as $attachment) :
echo '<script type="text/javascript">
$(\'#a_'.$count.'\').click(function() {
$(\'#d_'.$count.'\').show(200);
});
// if "no" is clicked
$(\'#d_'.$count.' .no\').click(function() {
$(\'#d_'.$count.'\').hide(200);
});
// if "yes" is clicked
$(\'#d_'.$count.' .yes\').click(function() {
$(\'#d_'.$count.'\').hide(200);
// update database table -- this is why I need the script inside the for loop!
var jsonURL = \'http://path/to/update_db_script.php\';
$.getJSON(jsonURL, {\'post_id\' : '.$attachment->ID.'}, function(data) {
alert(\'Thank you. Your approval was received.\');
});
$(\'#a_'.$count.'\').replaceWith(\'<span>Approved</span>\');
});
</script>';
echo '<li>';
if($attachment->post_excerpt == 'approved') {
// Check the proof's status to see if it reads "approved"
echo '<span>Approved</span>';
} else { ?>
// If not yet approved, show options
<a class="approve" id="a_<?php echo $count; ?>" href="#">Click to Approve</a>
<div class="confirm-approval" id="d_<?php echo $count; ?>">
<p>Please confirm that you would like to approve this proof:</p>
<a class="yes" href="#">Yes, I approve</a>
<a class="no" href="#">No, not yet</a>
</div><?php
} ?>
</li>
<?php $count++;
endforeach; ?>
The page in question is available here. The "click to approve" links do not work (that's my problem).
When I view source, the PHP variables appear to have echoed properly inside the jQuery:
<script type="text/javascript">
$('#a_0').click(function() {
$('#d_0').show(200);
});
... etc ...
</script>
This looks correct, but nothing happens when I click any of the links. However, when I replace the PHP echo statements with plain numbers (0, 1, etc.) the click functions work as expected.
You may be asking: why on earth do you have this inside a for loop? The reason is that I need to retrieve the attachment->ID variable and pass it to an external PHP script. When someone clicks "approve" and confirms, the external script takes the attachment->ID and updates a database value to read "approved".
Why won't the click function fire when PHP is in place? Is there some kind of greater force at work here (e.g., hosting limitation), or am I missing a fundamental piece of how PHP and JavaScript interact?
Since you didn't post your HTML its a little hard to troubleshoot.
First, I am not sure why one is working and the other is not since the code it is outputting looks correct. Either way, I still would make some changes. Move your a_0,a_1, etc and d_0,d_1, etc into the id attribute instead of a class:
<div>Click Me</div>
<div class="confirm_approval" id="d_0">Show Me</div>
<div>Click Me</div>
<div class="confirm_approval" id="d_1">Show Me</div>
Now, instead of outputting your code in a loop in PHP, place this jQuery code once on your page:
$(document).ready(function(){
$("a.approve[id^='a_']").click(function(e){
var id = this.id.replace('a_',''); // Get the id for this link
$('#d_' + id + '.confirm-approval').show(200);
e.preventDefault();
});
});
This code finds any a element with the approve class that has an id that starts with a_. When this is clicked, it grabs the number off the id a_0 = 0 and uses that id to find the confirm-approval element and show it.
Since the javascript is run on the client and has no way of knowing whether the script was generated using PHP or not, I think that particular part is a wild goose chase...
When I replace the PHP echo statements
with plain numbers (0, 1, etc.) the
click function works as expected.
Do this again and compare the actual output using view-source in a browser. I'll bet you find that there is a difference between the working and failing scripts, other than one of them being generated by PHP.
It seems that the problem is in jQuery selectors. Instead of dynamically binding click() events on multiple objects with an output of PHP code, use just one class selector and bind to objects with this class. And you can specify an id attribute to make them unique.
Something strange too is to have the script tag and the
$(document).ready(function()
in the loop. I don't know if this causes any problems, but it's sure not very efficient, one time is enough.

Categories