Passing a PHP Function (With parameters) through an HTML Button - javascript

Basically, I'm trying to create a login system, and I'm using it what I call "Dynamically" meaning it's included from my other files, and if I wanted to use a different database I would simply pass that database to the login function. I know how to do this by default, but as soon as using a button came in I got a little confused.
Here's what I have in it's most basic form.
<?php
createLogin('test', 'test2');
function createLogin($SQLConnection, $SQLConfig) {
echo "<h1> You are currently not logged in!</h1>";
echo "<form action='handleLogin(".$SQLConnection.",".$SQLConfig.") method='post'>";
echo "<div align='center'>";
echo "<table style='width: 475px'>";
echo "<thead>";
echo "<th>";
echo "<tr>Enter your e-mail and password.</tr>";
echo "</th>";
echo "</thead>";
echo "</table>";
echo "<input type='submit' value='Login' />";
echo "</form>";
}
function handleLogin($foo, $bar) {
echo $foo . " || " . $bar;
}
?>
When I click the submit button however, it simply takes me here...
http://localhost/handleLogin%28test,test2%29%20method=
Now, I read about using Javascript to do this, and to do something like
<script>
function processLoginRequest($SQLConnection, $SQLConfig) {
alert("<?php handleLogin($SQLConnection, $SQLConfig) ?>");
}
</script>
Then I could use
echo "<form action='processLoginRequest(".$SQLConnection.",".$SQLConfig.") method='post'>";
However, the code causes the entire php script to die. (Without error?)

You're using action incorrectly, and the result is as expected. action stores the page to which the form will be submitted. So, yes, when you hit submit it is trying to take you to a page called handleLogin%28test,test2%29%20method= because that is what your action says to do.
What you can do is simply leave the action blank, which will submit the form to the current page. Then, on that page, check if the form has been submitted, and if so, call your function.
Inside the function that creates the form make these changes:
function createLogin() {
...
echo "<form action='' method='post'>";
....
echo "<input type='submit' value='Login' name='login'/>";
}
Then, at the top of the page that renders the form, add something like this:
// Check if login form has been submitted - if so, handle
if (isset($_POST['login'])) {
handleLogin($SQLConnection, $SQLConfig);
}
// Render login form. No need to pass config parameters here.
createLogin();
If you really want to keep everything in a single function, I suppose you could also do it like this:
function createLogin($SQLConnection, $SQLConfig) {
if (isset($_POST['login'])) {
handleLogin($SQLConnection, $SQLConfig);
}
else {
echo "<h1> You are currently not logged in!</h1>";
echo "<form action='' method='post'>";
echo "<div align='center'>";
echo "<table style='width: 475px'>";
echo "<thead>";
echo "<th>";
echo "<tr>Enter your e-mail and password.</tr>";
echo "</th>";
echo "</thead>";
echo "</table>";
echo "<input type='submit' value='Login' name='login'/>";
echo "</form>";
}
}

You do NOT want to pass your SQL Configuration parameters back to JavaScript, because anyone can look at your JavaScript code when they browse your page, and then they'll have everything they need to connect and play around in your database.
You will have to pass some kind of flag to your form, to let your PHP code know (when it receives the form's data later) what kind of SQL settings it should use.
Example:
<form method="POST" ...>
<type input="hidden" name="loginMode" value="<?php echo $loginMode; ?>" />
</form>
Again, don't pass any sensitive data in there, just have some kind of unique value like "mySql" for $loginMode or the other options.
And then, when you're handling the HTTP POST in your PHP:
if ($_POST['loginMode'] == 'mySql')
{
// ... create connection based on $SQLConnection, $SQLConfig
}
else if ($_POST['loginMode'] == 'otherMethod') ...

Your JavaScript is probably failing because of the the contents of $SQLConnection and $SQLConfig. If you have a double quote in them it would fail.
Also designing and implementing a safe and robust login system is actually pretty difficult and you should opt using a framework that has been tested over time.

Related

Passing a PHP variable using Javascript Void 0 as the HREF?

I am creating a page that allows a user to edit a user. The table gives me the row ID which is in the button shown below. It works fine when having it direct to another script. However, I wanted to open the users details dynamically which this program does.
Although I don't understand where to place the $row to have the page be able to access it? My research was more about just passing between both programs when I just need to link it up.
I just want this to when the button is pressed, send the $row['usersid'] variable to the page which I can then use.
EDIT: It seems I've confused both myself and you all. I want to keep this in PHP if possible. All I need is the $row['usersid'] or a variable that stores it which is in PHP currently. To be sent to the page without it refreshing.
echo "<td><a href='javascript:void(0);' onClick=".$row['usersid']."' id='showButton'><span class='glyphicon glyphicon-edit'></span></a></td>";
echo "<td><a href='javascript:void(0);'".$row['usersid']."' id='showButton'><span class='glyphicon glyphicon-edit'></span></a></td>";
There are many ways to pass the information in page to another one, let me list some of them:
approach
echo "<td><a href='/path_to_another_php_page.php?userId=$row['usersid']' onClick= id='showButton'><span class='glyphicon glyphicon-edit'></span></a></td>";
then you can access to this information searching in $_GET['userId'].
If your want to use this userId, only for make ajax request, you could do simply doing:
echo "<td><a href='javascript:void(0);' data-user-id='$row['usersid']' onClick= id='showButton'><span class='glyphicon glyphicon-edit'></span></a></td>";
as you can see I added a data-user-id attribute that contains the real userId from php, so in your Javascript you can do this:
document.getElementById("showButton").addEventListener("click", function(){
var userId = this.getAttribute("data-user-id");
// here you can call your ajax ...
}, false);
I hope this be useful for you.
if you want to check your value then use this code which you get your value
you can also get data using this code
<?php
$row['usersid'] = 10; // fot test case
$row['usersid1'] = 13; // fot test case
?>
<script type="text/javascript">
$(document).on('click', '.getValue', function(){
// send data to PHP
var id = this.getAttribute("userId");
alert(id)
});
</script>
<?php
echo "<td><a href='javascript:void(0);' class = 'getValue' userId = ".$row['usersid']." id='showButton'>Button</a></td>";
echo "<br>";
echo "<td><a href='javascript:void(0);' class = 'getValue' userId = ".$row['usersid1']." id='showButton'>Button</a></td>";
this is second option
<script type="text/javascript">
function getValue(value){
alert(value)
}
</script>
<?php
echo "<td><a href='javascript:void(0);' onClick=getValue(".$row['usersid'].") id='showButton'>Button</a></td>";

How to fire a javascript function after setting a radio button value with a mysql query result when the page loads

I'm using php & mysql (with a pinch of javascript). This is a simple "edit" form, that auto-fills the various elements from data in a table. On the form is a set of radio buttons which are set by the data when the page loads. As in the "add new" form, this "edit' form has javascript functions which are triggered by onclick(), which display either another set of radio buttons or a text entry box, when the user makes a selection. (That part works just fine.)
How can I trigger/fire these scripts to display the appropriate elements automatically when the page loads? (Really don't want to delve into the jQuery arena at this time - as I need to get this piece of the project wrapped up ASAP.)
echo "<tr>";
echo "<td align=right>Transport: </td>";
echo "<td><input type=radio id=transppnd name=transp value='pnd'";
// $prepdel: var holding 1 or 0 from database table field
if($prepdel>0){
echo "checked";
}
echo" onclick='showpnd()'>Prep & Deliver";
echo " <input type=radio id=transpcpu name=transp value='cpu'";
// $prepdel: var holding 1 or 0 from database table field
if($prepdel<1){
echo "checked";
}
echo " onclick='showcpu()'>Customer pickup</td>";
echo "</tr>";
Looks like you want to call your showcpu() and showpnd() methods on page load. Just add a script like this at the bottom of your html page:
<script type="text/javascript">
showpnd();
showcpu();
</script>
</body>
I don't know php but maybe something like this?
if($prepdel>0){
echo "<script type="text/javascript">showpnd();showcpu();</script>";
}
*****************************UPDATE********************************
echo "<input type=hidden id=porc name=porc value='$prepdel'>";
<script type="text/javascript">
if(document.getElementById("porc").value > 0)
{
showpnd();
showcpu();
}
</script>
</body>

Show a timed message between submit and reload

I have a "Bootstrap" form. When the user press "Submit" data is sent to file.php If the database is updated, I have an alert in that php file which echos an alert with "success". Now I'd like to alert a timed message. Not the alertbox with "OK" button. Is there some small simple code for this?
This is what I have now!
PHP
//Echo succes
echo "<script type='text/javascript'>";
echo "alert('Välkommen ".$row['usr_fname']." ".$row['usr_lname']."');";
echo 'window.location = "../back_to_form.html"';
echo "</script>";
die();
You could potentially use something like Jquery UI to fake a dialog box. Then the reloading could happen just like you want it to. The code would look something like this (untested, you'd need to adapt it to your app):
echo "<html><body>";
echo '<script src="//code.jquery.com/ui/1.11.3/jquery-ui.js"></script>';
echo "<div id="dialog" title="Basic dialog">";
echo "<p>Välkommen ".$row['usr_fname']." ".$row['usr_lname']."</p>";
echo "</div>";
echo "<script type='text/javascript'>window.settimeout(window.reload(), 5000)</script>";
echo "</body></html>";
More info with a better javascript example for the jquery ui message box can be found here

PHP autogenerated divs with delete button

So I am learning PHP and mySQL, know HTML and JS. I am making a small note-taking webapp for my self, and stumbled upon a problem. I am generating divs by using a foreach and echo. The notes are stored in a db and requested using "SELECT"-mysql. The delete-button (works as a button but is text) is connected to a form which is also generated; One form for every note.
echo "<form method='post' id='" . $row['id'] . "form" . "' action='handler.php'>";
echo "<input type='hidden' name='deleteRecord_button'";
echo "<input type='hidden' name='" . $row['id'] ."'>";
echo "</form>";
When I submit the form using the delete-button a form is send as POST to a handler.php-file, however I can't seem to find a good way of sending the "id" of the note so that I can
delete it from the database using mysqli "DELETE FROM notes WHERE id = THE ID OF THE NOTE...
Sorry if this makes no sense, but I want to know if there is a good solution as to how I can send the id from notes.php (the picture below) to the handler.php file where I can handle and delete the note from the database. I prefer using "plain" JS, PHP, but I am using jQuery as well.
Change this line ...
echo "<input type='hidden' name='" . $row['id'] ."'>";
to
echo "<input type='hidden' name='id' value='" . $row['id'] ."'>";
Since you're making your form field names contain the ID, you'd need something like this:
$formIDs = preg_grep('/^\d+form$/', $_POST);
foreach ($formIDs as $id_string) {
$id = substr($id_string, 0, -4);
... do something with the ID ...
}
e.g..
<input type="hidden" name="42form" ?>
producing
$formIDs = array('42form');
You didn't specify the value of the 'deleteRecord_button' input. If you add it like I did, it'll work.
<form method="POST" id="<?php echo $row['id'] ?>form" action="handler.php">
<input type="hidden" name="deleteRecord_button" value="<?php $row['id']; ?>"/>
</form>
.
Now, a tip you can ignore if you want.
Instead of using a form to post a value to another page you can also use the GET method. This can be done with less code.
Delete
If you catch the GET in handler.php and if necessary check if there is a user logged in and then execute the database command. If you do, make sure if the delete variable is a number. You could use is_numeric for that.

closing tab after submiting form

I have researched as much as I can about this issue, and have so far not found a solution that works.
Essentially what I have is a PHP page where the user enters match results, the form action includes a header that takes them to the updated league table. I have disabled caching from the page where the user enters results, but this does not accommodate for the 'back' button being clicked in the browser. If they do click back, the page shows it's previous state, before the last scores they entered, which, if submitted, causes a real problem with the league tables.
At the minute I have got the form action to run in a new tab, meaning they cannot click 'back' in the browser, and instead must use a 'back' link, which means the page will always be re-rendered. Great, but the issue is that the form page is stil open in it's original tab.
Is there a way around this. I realise that calling a javascript closeWindow() function 'onSubmit' will close the window before the database is updated.
This is what I have so far, the new tab opens, but the original one remains open.
For added info, the page that I need to close, is opened in a new tab itself from a link on the homepage.
<?php
require_once "pdo_enl_connect.php";
$database=dbNB_connect();
echo "<table>";
echo "<form action=\"update_table_a.php\" target=\"_blank\" method=\"post\">";
$query=$database->query("SELECT team_id, team_name, team_score, opposition_score, opposition_id, opposition_name from results_a");
while ($row = $query->fetch(PDO::FETCH_NUM)) {
echo "<input type=\"hidden\" name=\"team[]\" value=\"$row[1]\">
<input type=\"hidden\" name=\"opposition[]\" value=\"$row[5]\">
<input type=\"hidden\" name=\"team_id[]\" value=\"$row[0]\">
<input type=\"hidden\" name=\"opposition_id[]\" value=\"$row[4]\">
<tr><td>$row[1]<td><input type=\"text\" name=\"team_score[]\" value=\"$row[2]\" <td>
<input type=\"text\" name=\"opposition_score[]\" value=\"$row[3]\"><td>$row[5] </tr>";
}
echo "</table>";
$query2=$database->query("SELECT team_score, opposition_score from results_a");
while ($row = $query2->fetch(PDO::FETCH_NUM)) {
echo "<input type=\"hidden\" name=\"prev_team_score[]\" value=\"$row[0]\">
<td><input type=\"hidden\" name=\"prev_o_score[]\" value=\"$row[1]\">";
}
echo "<input type=\"submit\" value=\"Go\" name=\"go\">";
echo "</form>";
if(isset($_POST['go'])) {
echo "<script>window.close();</script>";
}
?>
<?php
if(isset($_POST['buttonname']))
echo "<script>window.close();</script>";
?>
and Remove the window.close() from the onSubmit
Maybe try using AJAX for the onSubmit?
var request = new XMLHttpRequest();
request.open("POST","submitdata.php",false);
request.onload = function(){ window.close(); };
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
request.send("name="+name+"&surname="+surname+"&pass="+pass...);
This will send the form data to a php script that updates the data, then after the response loads, it will close the window. This is synchronous ("false" in the request opening), so users shouldn't be able to mess your database up.

Categories