javascript and php do not work together - javascript

I'm writing the register page for my website.Here is my register page.Can anyone show me why it does not check whether The username is already in use or not.I don't know whether PHP and javascript can work together or not.
The html page is as follows:
<html>
<head>
<title>Register</title>
</head>
<body>
<script language="javascript">
function checkInput()
{
if(document.register.username.value=="")
{
alert("Fill in username");
document.register.username.focus();
return false;
}else if(document.register.password.value==""){
alert("Fill in your password");
document.register.password.focus();
return false;
}else {
<?php
if(isset($_POST['submit'])){
include "connect.php";
$username=$_POST['username'];
$query="SELECT username FROM user";
$result=mysql_query($query);
while($row=mysql_fetch_array($result)){
$arr[]=$row['username'];
}
if(in_array($username,$arr)){
?>
alert("Username is already in use");// this part does not work!
document.register.username.focus();
return false;
<?php
}
}
?>
}
}
</script>
<form name="register" method="post" action="dangki.php" onsubmit="return checkInput();">
<table width="289" height="185" border="1">
<tr>
<td colspan="2">register</td>
</tr>
<tr>
<td width="83">Username</td>
<td width="190"><input type="text" name="username" id="textfield" ></td>
</tr>
<tr>
<td>Password</td>
<td><input type="text" name="password" id="textfield2"></td>
</tr>
<tr>
<td>Re-type Password</td>
<td><input type="text" name="repassword" id="textfield3"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="submit" id="button" value="Submit"> </td>
</tr>
</table>
</form>
</body>
</html>

Not, Javascript and PHP do not "work together" in that way. Javascript runs in your browser, PHP runs on the server before that. Therefore, you cannot use PHP for client side validation, only server side. For a first demonstration of this, just "view source" on what your page looks like to the browser.
You have to think of them separately. You have to have PHP just check what the form submits, and return a new page that indicates whether it was a valid/new username and allows the user to try again if needed.
You can sort of fake it with ajax, but even that is just sending a request to the server, which is run separately, and returns a result to the page, to be processed by a different function. It would get more complicated that your attempt.

PHP is evaluated on the server side. JavaScript is evaluated on the client side. That is to say: when a user makes a request to the server, the php is evaluated on the server, the resulting output is sent to the user, if there is javascript involved, it is evaluated on the client, after the php has evaluated.
This means that PHP can give messages to javascript, but javascript cannot send messages to php. In your code it looks like you want php to evaluate the user input that javascript is taking. This cannot be done because when the javascript is running, the php is already finished.
One way you could provide the functionality you want is to write php code to write the code for an array in javascript, containing all usernames. The javascript could then look through this array to tell the user if the username is taken. This has some flaws though, if you have a lot of users, you will be transmitting a lot of text to a new user. This may be a security problem too because everyone would be able to know all the user names of all the people registered with the site, there is also the potential for someone to load the page, type in their user name, wait a long time, have someone else create an account with their same name, and then the first person come back, submit the page, and then you will have two users with the same user name.
It may be easier, but less fun, to write the whole site in php first, and after it's all working, add the javascript to spruce up functionality.

Related

How do I add a data to the database on PHP then have the result appear immediately without refreshing the page?

I am working on a grading system and I want it so that you can add the grade of a student on a text box with a button then after submitting it, the text box and the button will then immediately change to the resulted answer, WITHOUT refreshing the page
Kind of similar to how one adds a value in Excel
I want to be like this:
Before entering grade:
before
After entering grade:
after
My current code is this, but this only works because I have to refresh the page
<?php
if($row['grade'] == '0')
{
?>
<td>
<label for="">Grade</label>
<input type="text" name="grade" id ="grade" class="form-control">
<button type="submit" name="add_grades" id = "add_grades" class="btn btn-primary"> Add Grade </button>
</td>
<?php
}
elseif(!$row['grade'] == "0")
{
?>
<td>
<?=$row['grade'];?>
</td>
With your approach it is impossible. You need to separate your Serverside code from the clientand use Ajax requests for this. The easiest way (but the ugliest) is to move the backend code to insert the grade in a db into a separate php file and call it via ajax. Ajax is a whole topic and I could write the code here, but it will be too large and meaningless. You need to change a lot.
Here are some links you could try to explore about ajax :
MDN: https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX
Video Tutorial: https://youtu.be/tNKD0kfel6o

Can I force a page in history to be removed?

Re editing... this question has NOT been answered before!
I had understood that changing the contents of a current page with window.location replaced the cached version of the original page ( from the "last" history), so that you really couldn't go back with the browser BACK button. I had even seen this posted as a solution to preventing a malicious visitor from using the BACK button to to re-submit a mail form many times. But it is NOT workable because in the case of a mail form, the BACK button will just take the user back to the pre-POST version of the page.
So, I can use javascript to reset the form, disable the SUBMIT button, change to another page after success, or do whatever I want to the page. But its all for nothing if a simple click of the BACK button followed by SUBMIT causes the form to post again with just 2 clicks.
I know there are a lot of solutions to preventing malicious form resubmissions I can try, but I've had trouble getting them to work, and so I'd just like to know if removing the last history is a dead end. If there is a way, and it is pretty cross browser friendly, then I can just make it part of my scripted actions once my form is successfully processed, and my "thank you" page displays. Basically I'd want my "thank you" page's 'onload' event to either erase the last history, or in a browser compatible way disable the BACK button!
For what its worth, I've included code from simple test I've been working with. You can put some junk in the fields and hit submit. The vars are cleared in the PHP, the form fields are force cleared in javascript, and a new 'location' is invoked. Unfortunately, hitting BACK button will take you back to the "pre-posted" form, with all the strings you added still intact.
<!DOCTYPE HTML>
<html>
<head>
<title> Form Behavior Test</title>
</head>
<!--
<?php
$name = $email = $comments = "";
$formDone = false;
if ($_SERVER["REQUEST_METHOD"] == "POST" )
{
$formDone = true;
$name = $email = $comments = "";
}
?>
-->
<body >
<table border="1"><tr><td style ="text-align:right;" width=100%>
<form name="contactform" id="contactform" method="post" enctype="multipart/form-data" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name" id="name" value="<?php echo $name;?>"><br>
Email: <input type="text" name="email" id="email"value="<?php echo $email;?>"><br>
<br>
<div align="center"> ---- <span class="error">*</span> Message ---- <br>
<textarea name="comments" id="comments" wrap="physical" cols="40" rows="10" ><?php echo $comments;?></textarea>
</div>
<input name="submit" id="submit" type="submit" value="Submit" >
</form>
</td></tr></table>
<script language="JavaScript">
if (<? echo ($formDone == true) ? 'true' : 'false'; ?>)
{
document.getElementById("name").value = "";
document.getElementById("email").value = "";
document.getElementById("comments").value = "";
document.getElementById("submit").value="Disabled";
document.getElementById("submit").disabled=true;
// substitute with a thank you page
window.location = "http://google.com";
}
</script>
</body>
</html>
After searching pretty exhaustively, I don't believe there is any way to remove a page from history, except on the very latest browsers that support newer HTML-5 history methods. I'm still open to solutions but at this point I think the easiest thing will be for me to set a cookie anytime a successful email is processed by my PHP code. Then, I can also make the PHP or a javascript snippet look for the cookie and if found, I can take all kinds of actions... wipe out all filled in fields (as they would be if the BACK button is pressed), block the email, politely inform the user that he/she must wait (until my cookie expires) to send another email though the form, etc.
I didn't want to do this originally because the BACK button doesn't actually re-load the page, it just displays it. If there were a universal browser compatible way to make pages reached by back buttons actually re-load, this would never have been a problem to begin with. So even with a cookie, my defensive actions couldn't activate until the SUBMIT button is pushed. I guess I can live with that. Also, even today, some people are paranoid about cookies and turn them off. But if I want to be adamant about it, I can just detect when I can't set a cookie, and inform the user that cookies are required to use my email form. If that's too big a deal, oh well!
Thanks to those that contributed. The fact is, the LACK of answers is really a very useful answer sometimes. When I post on any stackoverflow forum and don't get any answers pretty quickly, its a good red-flag that things are going to get convoluted really fast if I don't consider an alternate approach! :-)

Variable Transfer: Web Form that connects with PHP to Database

Hello and thank you for viewing my question. I am a complete beginner and am looking for simple ways to do the following...
What I have in seperate linked documents:
HTML, CSS, Javascript, PHP
What I am having trouble with:
I need to use something like JSON (although I would also accept XML requests or Ajax at this point if they work) to transfer variables from Javascript to PHP. I need the variables to search in a database, so they need to be literally available within PHP (not only seen on a pop-up message or something).
I have seen a LOT of different ways to do this, I have even watched tutorials on YouTube, but nothing has worked for me yet. The things I am having the biggest problem with is that when I add a submit button to my form it doesn't submit my form and I don't know why.
Form code snippet:
<form id="form" name="input" method="post" action="javascript:proofLength();">
<input id="userinput" type="text" autofocus />
<input id="submit" type="button" value="submit" onsubmit="post();">
</form>
The second to last line there doesn't work. Do I need javascript to submit the form? Because I really thought that in this case it was part of the functionality of the form just like method="post"...
The other thing is that for JSON, I have no idea what to do because my variables are determined by user input. Therefore, I cannot define them myself. They are only defined by document.getElement... and that doesn't fit the syntax of JSON.
Those are really my main problems at the moment. So if anyone could show me a simple way to get this variable transfer done, that would be amazing.
After this I will need to search/compare in my database with some php/sql (it's already connecting fine), and I need to be able to return information back to a in HTML based on what I find to be true. I saw one example, but I am not sure that was very applicable to what I am doing, so if you are able to explain how to do that, that would be great also.
Thank you very, very much.
April
You don't need ajax to submit this form. You don't even need javscript. Just do this:
<form id="form" name="input" method="post" action="mytarget.php">
<input id="userinput" name="userinput" type="text" autofocus />
<input id="submit" type="submit" value="submit" />
</form>
This will send the form data to mytarget.php (can be changed of course)
See that i have added the name attribute to your text-field in the form and i changed the type of the button to submit.
Now you can work the Data in mytarget.php like this:
<?
$username = $_POST['userinput'];
echo "Your name is: ".$username;
?>
You wanted to have a check for length in the submit. There are two ways to this:
Before the input is send (the server is not bothered)
Let the server Check the input
for 1 you will have to append a event listener, like this:
var form = document.getElementById("form");
form.addEventListener("submit", function(event){
console.log("test");
var name = form.elements['userinput'].value;
if(name.length < 3){
alert("boy your name is short!");
event.preventDefault();
}
});
Enter a name with less then 3 characters and the form will not be submitted. test here: http://jsfiddle.net/NicoO/c47cr/
Test it Serverside
In your mytarget.php:
<?
$username = $_POST['userinput'];
if(strlen($username) > 3)
echo "Your name is: ".$username;
else
echo "your name was too short!";
?>
You may also do all this with ajax. You will find a lot of good content here. But I'd recommend a framework like jQuery to do so.
The problem is in this line
<form id="form" name="input" method="post" action="javascript:proofLength();">
The action should be a PHP page (or any other type of server script) that will process the form.
Or the proofLength function must call submit() on the form
In the php page you can obtain variable values using $_GET["name"] or $_POST["name"]
To summarize; your code should look like this
<form id="form" name="input" method="post" action="yourpage.php">
<input id="userinput" type="text" autofocus />
<input id="submit" type="button" value="submit">
</form>
and for your php page:
<?php
$userinput = $_POST["userinput"];
//Do what ever you need here
?>
If you want to do something in your javascript before submitting the form, refer to this answer

Submit form to email, then redirect to new page (without php)

The client has a section of her site that is not navigable through any other pages. To get to these pages she wants the user to fill out this form. It's a non-for-profit, so she basically just wants to see how many people are getting to these pages that have a product available for free so she can report on that. So there is a page with a form. She wants the user to submit the form and then be re-directed to another page. Normally I would do this really easily with PHP but unfortunately she hosts the site through some local fools and they don't support PHP
So the question is, how do I get this form to submit to her email, then redirect to a different page (videos.html) from the current page with the form (video-form.html)?
I have this form:
<form id="myForm" action="mailto:mail#mail.net" method="post" name="VideoFormAction">
<table cellspacing="1" cellpadding="1" width="46%">
<tr>
<td valign="top" class="shade1"><font color="red"><b>*</b></font> Email Address</td>
<td valign="top"><input type="text" name="Mail" value="" size="30"></td>
</tr>
<tr>
<td valign="top" class="shade2">Name</td>
<td valign="top"><input value="" name="Name" type="text" size="30" maxlength="100"></td>
</tr>
<tr>
<td valign="top" align="center">
<font color="red"><b>*</b></font> = required field
</td>
<td valign="top">
<button class="button">Submit</button>
</td>
</tr>
</table>
</form>
I have tried some javascript:
<script>
document.getElementById("myForm").onsubmit = function() {
setTimeout(function(){
window.location.href = "http://www.funducate.net/videos.html";
}, 1);
};
</script>
Which for whatever reason will not work. I have found multiple suggestions through search to try many different variations of the above, all of which failed. The last ditch effort was even putting a timeout into it as you see above. I imagine it doesn't work because the submit button performs the action="" and then doesn't continue.
Are there any other alternatives? Remember, I can't use PHP (i know it's ridiculous but it's what I got)
You could read the form values via either jQuery or javascript, save them to variables, construct a message body and email the form contents.
See below for more information:
How to send an email from JavaScript
More information on Mandrill
After sending the email, redirect the page as you have done (correctly) in your code -- but without the setTimeout.

Create a local file from user input and list existing files

I need to use the input from a user to create a filename.html on the server they are attached to. The program normally takes the input and writes it TO an existing html file. In this one case, I need to add the ability to create the file they are writing to before they begin writing to it.
While I am wishing :) I would like to start out by showing the user a directory of the html files are already there in case someone else has already created it.
The logic of the input would be to use the data input to create the file IF the file does not already exist. If it does exist, then they would open to the pre-existing file by that name.
This is an adaptation of "Microchat" php script which normally writes to msg.html.
It works fine as-is but this one project needs the added ability of creating multiple Name.html files and then letting the user continue as normal except they will be writing to the filename they chose or created rather than the using the generic msg.html. I have been working on the assumption that I will have to create a variable of their input to use for creating the file.
The entire script for Microchat is only 144 lines. But too long to post in its entirety
It can be viewed at www.phptoys.com. The area I need help with is this:
function createForm () {
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<table align="center">
<tr><td colspan="2">Please eneter a nickname to login!</td></tr>
<tr><td>Your name: </td>
<td><input class="text" type="text" name="name" /></td></tr>
<tr><td colspan="2" align="center">
<input class="text" type="submit" name="submitBtn" value="Login" />
</td></tr>
</table>
</form>
<?php
This is normally used to create the users login. I have tried a few variations on the input to achieve a variable for creating a file but sadly, I know my limits. I doubt I will find a way without help.
I am not sure what you are trying to make. Possibly you can use database for the purpose but purpose is not clear to me so I don't know. By the way you can use following approach. Then you can do customization as per your requirements.
<?php
$fileName = "newHTMLFileName";
$path= "../yourFolder/".$fileName.".html";
if (!file_exists ($path))
{
$code = "<!DOCTYPE html><html><body><h1>Information</h1></body></html>";
$handle = fopen ($path, "w");
$write = fwrite ($handle,$code);
fclose($handle);
echo "created";
}
else
{
echo "already created";
}
?>

Categories

Resources