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.
Related
I have PHP code like this: (for signing out - located in a php page together with other php handlers for different functions and this file is included in pages like index.php or other relevant pages.)
if(isset($_POST['signout'])) { // logout button
// Clear and destroy sessions and redirect user to home page url.
$_SESSION = array();
session_destroy();
// redirect to homepage (eg: localhost)
header('Location: http://localhost/index.php');
}
I normally use a <form action="index.php" method="post"> where the function is currently included and <input type="submit" name="signout"> for such things but this time i would like to use an anchor tag like:
<a href="" >Sign Out</a> for signing out.
Would anyone be kind enough to show an example code that will trigger a submit that will be handled by the given PHP code above.
Either a jQuery or Javascript solution would do. I would just like to see a complete example on how this works.
There's good reason for using a POST for submitting authentication tokens which usually commences or alters the session state - but these don't really apply to the problem of closing the session - why not just just trigger this via a GET?
But if you really must do a POST, and you really must do it via a a href (rather than styling a submit button) and you really must do it via javascript (which will break if the client has javascript disabled) then...
<script>
function sendForm(formId)
{
if (document.getElementById(formId).onsubmit())
document.getElementById(formId).submit();
}
<script>
<form id='logout'>
<input type='hidden' name='signout' value='1'>
</form>
logout
So basically my question is very simple, I have two buttons, I for page forward, one for page backwards, If one of those is pushed, a javascript function is called inside an onClick Event. Javascript then gets the variables of the page and then redirects to the next page, the only problem is, that I need to pass those variables to PHP in order to put them into the Database. So for that I make a load of cookies to pass the variables.
However, I was wondering if something like this would work :
<form>
<a onClick="nexpage();" onSubmit="phpScript.php"> <img src = "previous button.jpg"/> </a>
</form>
The idea behind this is that I want to store the variables in a PHP script, which will put them in a display:none; <div> and then for javascript to get the variables out. This instead of using cookies.
So is it possible to run a PHP script to get the variables and when the script is finished to get them, Javascript kicks in to redirect to the next page...
The reason I don't test this at this moment, is that my code is 100% complete, I don't want any sudden changes that maybe won't work at all. Yes I know back-up this and that, but I thought just asking here, maybe someone will know the answer!
Sincerly,
Harmen Brinkman
You can also use onClick = "this.form.submit(); return false;".
There is no any event like onSubmit for link, instead form do have onSubmit event.
Normal Way as OP asked.
<form action = "phpScript.php" method = "POST">
you can use document.getElementById("my_form").submit();
#Dipesh Parmar – Good point. You could also do:
window.onload=function() {
document.getElementById('my-form').onsubmit=function() {
// do what you want with the form
// AJAX POST CALL TO PHP PAGE
// Should be triggered on form submit
alert('hi');
// You must return false to prevent the default form behavior
return false;
}
});
Inspiration by Capture a form submit in JavaScript
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
I'm trying to echo information on a page after and anchor has been clicked
<a id="anchor">Information</a>
<?php
if(?){
echo 'INFORMATION';
}
?>
<a id="anchor" onclick="document.getElementById('information').style.display='block';">Information</a>
<div id="information" style="display:none"><? echo 'INFORMATION' ?></div>
I think you must use javascript here. PHP would need a page refresh to process your echo statement.
That's where you might want to utilize AJAX. You can often approach it like this:
<a onClick=" $('#output').load('output.php') ">click here</a>
<div id="output"><!-- This is where the content goes --></div>
Then define the according PHP script output.php like this:
<?php
echo $whatever;
?>
jQuery will then issue another HTTP request, invoking a PHP script, and finally injects it where you told it to (#output div).
Since PHP (your httpd, exactly) doesn't know anything about anchors, you'll need to handle this with javascript. Try jQuery.
You cant do this in PHP I'm afraid. PHP lives on the server and the page is on your client (browser). In order to do something (other than go to another page) when some clicks, you'll need to use javascript. Look at jquery.
You can't do it like this.
PHP works in the server side, therefore once the anchor information has come to the client browser, you won't be able execute any PHP code there.
There are several workarounds if you really want to achieve that.
i) Use client side JavaScript.
ii) Use Ajax to maker requests to server side and update page accordingly.
If you really want to show the information after clicking into a link can use the following code:
<html>
<title>lasdfjkad</title>
<head>
<script type="text/javascript">
function showhide(id){
if (document.getElementById){
obj = document.getElementById(id);
if (obj.style.display == "none"){
obj.style.display = "";
} else {
obj.style.display = "none";
}
}
}
</script>
</head>
<body>
Show/Hide Details
<div id="abc" style="display:none;">
your codes......
</div>
</body>
</html>
The real beauty of Javascript.....Hope this help you
I have a button in my abc.html page
<input type="button" onclick="javafun();">
on the click it goes to javascript, which further send info to my abc.php ...and the javascript function looks like:
function login()
{
xmlhttp=GetXmlHttpObject();
//alert("pass");
if(xmlhttp==null)
{
alert("Your browser does not support AJAX!");
return;
}
var url="login.php";
url=url+"?id="+username+"&passwrd="+passwrd;
xmlhttp.onreadystatechange=statechangedLogin;
xmlhttp.open("GET", url, true);
xmlhttp.send(null);
}
}
function statechangedLogin()
{
//alert(xmlhttp.readyState);
if(xmlhttp.responseText=="<font color='red'>Your User Name or Password is incorrect. Please try again.</font>")
{
document.getElementById("response").innerHTML=xmlhttp.responseText;
}
else
{
//hwin=window.location="http://forum.research.bell-labs.com/zeeshan/qotw/login.php";
document.getElementById("mainbody").innerHTML=xmlhttp.responseText;
//hwin.document.innerHTML=xmlhttp.responseText;
//alert();
}
}
Everything works fine, but the address of the website in the address bar remains the same:
http://severname.com/abc.html
i want this address bar to change, according to the php. it should come to ...
http://severname.com/abc.html/login.php
but still should not show ?id=username&passwrd=passwrd
Is this possible, and if it is how??
Zeeshan
POST the request to ../login.php ?
instead of using ajax, wrap your form elements in
<form method=POST action="login.php">
User Name: <input name="username"><br>
Password: <input name="passwrd" type="password"><br>
<input type="submit" name="Login">
</form>
Why are you doing AJAX if you want the address bar to change?
Edit
Added real values to the form
Edit 2 More clarity.
You really should do the login via form (see #nathans post).
Rename your html login form into a php page. Lets call it loginForm.php.
Remove all the javascript functions from loginForm.php
Insert the form into loginForm using the form tag.
In login.php, you check to see if they user logged in successfully,
If the login suceeded:
$failMsg = urlencode("Logged in successfully")
header("Location: loginForm.php?okMsg=$msg&redirect=home.php");
If the login failed:
$failMsg = urlencode("Failed to login")
header("Location: loginForm.php?failMsg=$msg");
In your loginForm.php where you are displaying your error messages now, put:
<? echo htmlentities($_REQUEST['failMsg']);?>
In loginForm.php where you are displaying success log in message put
<? echo htmlentities($_REQUEST['okMsg']);?>
And in the head tag put
<? if(array_key_exists($_REQUEST,'redirect'))
{
echo "<meta http-equiv='refresh" content='5;url=/".$_REQUEST['redirect']."' />";
}
?>
There no javascript and the user gets nice pretty error messages and is forwarded to the home page after logging in.
<form method="post" action="login.php">
You don't need AJAX to do that at all. If you're using the Javascript to validate the input you can add onSubmit="return my_validation_function() ... your validation function should return true if everything was okay or false if it was not. (The false return value will stop the form from submitting)
It sounds like you don't want AJAX at all, just a regular form, unless I'm missing something.
I think you have misunderstood the whole point of AJAX. Ajax is supposed to work in the background, i.e. not changing the url. If you want that, try document.location="foobar";
Ajax hides JS interaction with your server. That's what is for. If you want your browser to point to some URL, then you shouldn't use Ajax.
The thing you're trying to archieve can be easily implemented using a simple POST request, using the good old <form>.
HTTP POST requests hide the parameters of the request from the URL, passing them inside the header of the message itself. So URLs can be clean.
As other commenters have touched upon, the real answer is that you can't change the URL of a web page (other than the "#" fragment identifier, but that's not useful to you) without causing the browser to send a request to that url.
You want to not bother trying to change the URL if you're submitting via AJAX. Or, you can make a post request as suggested in other comments.
<form method="post" action="login.php">
Your method is somewhat insecure and vulnerable to some scripting attacks. I'd look at not doing an Ajax login and just use a regular form as well. This article helped me a ton:
http://www.evolt.org/PHP-Login-System-with-Admin-Features
Evolt has another one that looks similar to what you were trying to accomplish, but I've not read it -- just Google "evolt ajax login"