I have a login system and I would like to introduce a feature where the user can change his email...
However if I click change the site reloads and nothing happens.
Here is the script in the function:
function changeemail($newemail, $mysqli) {
$sql="UPDATE members SET email = '$newemail' WHERE userid='$_SESSION[user_id]";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param();
$stmt->execute();
$stmt->close();
}
And here's the html part:
<form method="post" action="<?php echo esc_url($_SERVER['PHP_SELF']);?>">
<input type="text" id="newemail"><br>
<input type="submit" value="Ă„ndern!" onclick="return changeemail(this.form,
this.form.newemail);"/>
</form><br>
Thanks in advance!
It is not possible to call a php function from a javascript onclick, because php is a serverside language and javascript a client side.
I don't need a function at all, because I can get the value, entered in the form, by POST.
Since php is server side you can not do that. But what you could do is use Javascript/jquery to load in a page onclick and then update the email
Then use Javascript to upload the page
$( "#result" ).load("yourpage.php");
Related
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.
I have problem, when I press submit button in my contact form all input values refreshing, it's good if all fields are filled correct, but if are some warning users must see previaus values, but all are cleared. My Javascript skills are low, maye are solution to solv this problem with php and html ?
a simpler way is use html5 storage . store value on onkeyup event and destroy if submit successful
for an example
<input id="title" type="text" value="" name="article_name">
script
to check support of html5
function supports_html5_storage() {
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch (e) {
return false;
}
}
script to store
if(supports_html5_storage()){
$("#title").keyup(function(){
var articel_title = $("#title").val();
localStorage.setItem("articel_title",articel_title);
localStorage.getItem("articel_title");
});
to clear storage ,you can fire this if form successfully submit it will clear storage
<script type=text/javascript>
localStorage.removeItem("articel_title");
</script>
you can also make ajax call on change or keyup event and store value to database so that if html5 is not supported by browser it will still work but it will cause more load on server
return values to client:
<input type="text" name="val1" value="<?echo $_POST['val1']?>" />
Post your values to an iframe within the page and if the entries are correct then redirect to another page.
So if the entries are wrong you would not have to do anything
You will need ajax with jquery. The follwoing tutorials will help you:
http://www.queness.com/post/160/create-a-ajax-based-form-submission-with-jquery
http://www.tuttoaster.com/create-an-ajaxjqueryphp-contact-form/
hi i am new to all html javascript and php. this is suppose to save the input from a html form to my database... but i have no idea why this doesnt work... the code dosent seem to go into the php section to execute the command...
kindly advise thank you
<html>
<script type = "text/javascript">
function processInputs()
{
//get data from html form
var email_data;
email_data=document.getElementById('txtInput').value;
//document.write(email_data);
<?php
//connect database
$con = mysql_connect("localhost","admin","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("internet", $con);
$newemail = $_GET['email_data'];
echo $newemail;
//query
mysql_query("INSERT INTO user_data (email) VALUES ($newemail)");
mysql_close($con);
?>
}
</script>
<FORM action="test.php" method="post">
<INPUT type="text" value="this is a text" name"txtInput" id="txtInput" />
</FORM>
<button type="button" onclick=processInputs() >click!</button>
You have multiple flaws:
you cannot "embed" like that a PHP script into a javascript function, for that you should use AJAX - try jQuery. PHP is server side, Javascript is browser based.
You have a MySQL injection hole there, you should escape your $_GET with mysql_real_escape_string()
Stop using mysql_* as those functions are deprecated. Read this article
onclick is invalid, it should be <button type="button" onclick="processInputs()">click!</button>
If you have a perception that -
On calling the js function on some user actions such as button click/hover, etc would trigger the php code and populate the data,
then YOU ARE WRONG.
PHP is a server side scripting language, and you can't use it this way. The complete page is parsed at the server end and given as response to the browser. To do dynamic updates use Ajax calls that would call a php page and populate the html for you.
I suggest refer the coredogs.com site for better understanding of php flow.
your function is not being called !!!
Change this
onClick = processInputs()
to
onClick = "processInputs()"
and try for an alert statement to see if function is being called or not
Also you cannot have php script within script tag
from my this code
<script type="text/javascript">
function getValue()
{
console.log("<?php echo $_POST['input_value'] ; ?>") ;
return false ;
}
</script>
<form id="request_form" action="" name="request_form" method="POST" >
<input id="input_value" type="text" size="45" name="input_value"></br>
<button class="button" id="btForm" onclick="return getValue()" >submit</button>
</form>
I expect it will print some value that I put but it show nothing.
What am I wrong?
Your form isn't actually submitting to a php page. It's just calling getValue, which won't have anything in it yet.
There are two halves to what you are trying to do, and your mistake is that you have mixed them together. The first is the server side, with the PHP. When you submit a form, you should use:
<input type=submit value="Submit" />
This refreshes the page (because the form action is blank), which, using PHP, can read your POST value and print it back out along with the rest of the page. Once the page is finished loading, PHP is no longer involved and cannot affect the behavior.
As you have it right now, when you load your page it looks like this:
<script type="text/javascript">
function getValue()
{
console.log("") ;
return false ;
}
</script>
Since the POST value wasn't there the first time the page loaded, the javascript sent to the browser looks like that - there is no value to print. Clicking the button will execute getValue() as it appears here.
PHP is server side, and is done before the page is loaded in the browser. When first loaded there is no $_POST at the time, so the log is empty.
When submitting the form, you are calling the console.log function which has no text in it, and then returning FALSE, so the form never actually gets submitted.
You need to either set the action attribute in the form tag to point to a PHP page to process the $_POST data, or you need to use AJAX to post the form.
function getValue() {
console.log(document.request_form.input_value.value) ;
return false ;
}
could have a sense, at the moment whe you execute getValue () in JS (client-side) - PHP (server-side) is not involved so no way to echo $_POST....
You can't write out actual server-side code from javascript, and expect it to execute client-side.
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"