Variable Transfer: Web Form that connects with PHP to Database - javascript

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

Related

How to write input value to a file in PHP?

i am quite a beginner in PHP and i wanted to create a input: If you click a button, Javascript will submit it and add linebreak (\n) at the end of what you wrote in the input box, and PHP will write the final result into a file called result.txt. However, when checking result.txt, there is nothing written at all.
HTML
<input id="test" type="text">
<form id="formie" action="test.php" method="post">
<input id="testz" type="text" name="really" hidden="hidden" disabled="disabled"><br>
<button onclick="trigger1()">Submit</button>
</form>
<!-- 2 input boxes, the hidden one is meant to be set to have the final result and with it i do the request -->
<script>
var int;
function trigger1() {
int = document.getElementById('test').value;
document.getElementById('testz').value = int + "\n";
document.getElementById('formie').submit();
}
</script>
PHP
<?php
$postreq = $_POST["really"];
$finaldata = $postreq;
file_put_contents("result.txt", $finaldata, FILE_APPEND);
header("Location: https://domain.tld/test.html");
exit;
?>
No error when stopping the redirect (domain.tld/test.html) and no error in server logs. Why is this happening? I even tried to check this with jshint.com and phpcodechecker.com and both told me no errors
Credit to #user3783243: The problem lies here:
<input id="testz" type="text" name="really" hidden="hidden" disabled="disabled">
Disabled elements cannot have values
Working code:
<input id="testz" type="text" name="really" hidden="hidden">
To answer the question, elements with the disabled attribute are not submitted or you can say their values are not posted
Try removing the "disabled" attribute from your hidden input.
Refer to: Disabled form inputs do not appear in the request, which has reference to the w3 specs explaining that as well.

Submit same form with two action?

I have a form to submit and send data to 2 pages via POST.
I have tried the code with javascript. One form submit is working but other submit is not working
<form id="add">
<input type="text" name="test">
<input type="submit" onclick="return Submit();">
</form>
javascript
function SubmitForm()
{
document.forms['add'].action='filecreate.php';
document.forms['add'].submit();
document.forms['add'].action='filecreate.fr.php';
document.forms['add'].submit();
return true;
}
The first submission is not working but 2nd submission is working.
Since you appear to send the exact same data to two different handlers, you can flip the coin - and say that you just submit one form, and process them both in filecreate.php.
As you are sending a form, you cannot send two separate forms in the same HTTP request - so you can either do them both through asynchronous methods, or process them both backend after the submission of one form.
Since you haven't shown any PHP code, I'm making some assumptions and writing some pseudo-code, but it should be enough to get you started.
So first off, set a static action-property to your form.
<form id="add" action="filecreate.php">
<input type="text" name="test">
<input type="submit">
</form>
If you are sending it over POST, then you need to specify the method as well,
<form id="add" action="filecreate.php" method="POST">
Then, in PHP, you can get both files executed if you include it to the other. Meaning, in your filecreate.php, you include the filecreate.fr.php. Once you do that, the contents of that file will be executed as well.
<?php
// Once you require the file, it will be executed in place
require "filecreate.fr.php";
// .. handle the rest of your normal execution here.
That said, if you are doing the very similar thing multiple times, just with different data, you may want to create functions for it instead - going with the DRY principle ("Don't Repeat Yourself"), you can probably create a function that handles the structure and processing, then send the data separately through that function.
Try this :
<form id="add">
<input type="text" name="test">
<input type="button" onclick="return SubmitForm();">
</form>
function SubmitForm()
{
if(document.forms['add'].onsubmit())
{
document.forms['add'].action='filecreate.php';
document.forms['add'].submit();
document.forms['add'].action='filecreate.fr.php';
document.forms['add'].submit();
}
return true;
}

Make hyperlink a form submit button

I am trying to get a hyperlink element to act as a form submit button. This sort of question has been answered multiple times over the years but, for some reason, I am not able to get it to work even with cut-n-pasted code and I'm wondering if I'm missing something trivially simple that my eyes are too bugged out to see. The full code is here:
<html>
<head>
<script language="JavaScript" type="text/javascript">
<!--
function signup() {
alert("Form is " + document.signup_form);
document.signup_form.submit() ;
}
-->
</script>
</head>
<body>
<?php
echo("Submit is [" . $_POST['submit'] . "]");
?>
<form method="post" name="signup_form" id="signup_form" action="" >
<input type="text" name="from_email" placeholder="e-mail address"><br>
<input type="submit" name="submit" value="Send Email">
Sign Up!<br>
</form>
</body>
</html>
The input submit element ("Send Email") works fine. The hyperlink ("Sign Up!") also works fine and calls the javascript function so that the alert() box in the function shows up.
So, it's just the submit() call that's not doing anything--I even printed out document.signup_form in an alert() box to confirm that it's defined (it is). So what am I missing here?
Thanks for any help!
There is a weird thing with how forms work with Javascript - each field is accessible by using formElement.fieldName. Unfortunately, that means that if you name a field input submit, all of a sudden the built-in formElement.submit() function is replaced by your input element. So in your code, document.signup_form.submit() is failing because it is calling the element, not the method, and you can't call an element as a function. See this SO QA for details.
The fix is easy - change:
<input type="submit" name="submit" value="Send Email">
to:
<input type="submit" name="submitBtn" value="Send Email">
Also, as others have noted, you will want to give your form a valid action. Also, in general it might be preferred to access things by id (document.getElementById()) instead of by things like document.signup_form.
Your <form> element is missing a value in it's action attribute. Quoting the specs:
You also have to specify the URL of the service that will handle the
submitted data, using the action attribute
Link here

Submit 2 forms with one button in Javascript does not work

I want to submit 2 forms from the same page with one button, so I tried to use the Javascript technic described in this post.
Here is my code:
send.php:
<form action="receive.php" method="post" id="form1">
<input type="text" value="2nd Form" name="q1" />
</form>
<form action="receive.php" method="post" id="form2">
<input type="text" value="3rd Form" name="q2" />
</form>
<input type="button" value="Click Me!" onclick="submitForms()" />
<script>
submitForms = function(){
document.getElementById("form1").submit();
document.getElementById("form2").submit();
}
</script>
receive.php:
echo $_POST['q1'];
echo $_POST['q2'];
But when it redirects to receive.php only the value of $_POST['q2'] appears, and not the value from the 1st input.
I can't see why is it so. Thank you.
Unfortunately I cannot setup an example because it's pretty long. But this is what is happening to me.
You move inside your code two submit requests, one after the other to the same PHP file, but with two different forms.
Supposing this is your PHP code:
echo $_POST['q1'];
echo $_POST['q2'];
When you actually make the first request, q1 gets printed. But immediately after you send the second submit, which "overrides" the first step and you see only the output of the second submit.
You can verify it in two ways:
1) Invert the order of the submits:
submitForms = function(){
document.getElementById("form2").submit();
document.getElementById("form1").submit();
}
and you should see only q1 printed.
2) Try adding a timeout to the second request, and you should see both the echo:
submitForms = function(){
document.getElementById("form1").submit();
setTimeout(function() {
document.getElementById("form2").submit(); }, 10000);
}
so after 10 seconds you should see the second output too.
So actually your requests do happen. If you log values to a file instead of the echo, you should see both the requests happening with your code.
Although this should be the reason to me, I strongly suggest you to change your logic. There is no obvious need to start ALWAYS two submit requests to the same PHP file.
Group the two forms and send just one request, maybe adding an input hidden field in order to detect which fields have been sent or which case are you in.
There is no need for two forms. Move "name="q2"" to first form.
Moreover, you are trying to call same form action. That is not appreciated.

Form data won't send using Javascript to email

I am new to HTML and Javascript, but I have tried to do research on how to get a form to send its information to an e-mail address when the submit button is selected. Most of my research showed that PHP is needed, but when I asked my professor, he said it can be done using only javascript and the assignment needs to be submitted that way. Below is what I am trying to get to work.
<SCRIPT LANGUAGE="JavaScript">
function mailMe(form){
Subject=document.Registry.name.value;
location = mailto:XXXXXX#yahoo.com?subject="+Subject;
return true;
}
</SCRIPT>
<FORM NAME=“Registry” onSubmit="return mailMe(this.form)" >
<h3><font size=6pt> Visitor Registration </font></h3>
</br>
Name <input type="text" name=“name”><br>
<br>
E-Mail Address <input type="text" name=“mail”><br>
<br>
<INPUT TYPE="submit"><br>
</FORM>
It can't be done using only javascript or client-side technologies.
But you can probably open a new window with a mailto link.
Please note this won't send an e-mail, but instead open your local e-mail application to send an e-mail.
This is a really bad idea. You should use AJAX and PHP, this is really the better method.
If you really want your code, you have a few errors. This is correct:
var Subject = document.getElementById("name").value;
window.location = "mailto:XXXXXX#yahoo.com?subject=" + Subject;
Then you have to add an ID to the name field:
<input type="text" name=“name” id="name"><br>
But let me say that you really should use PHP mail(), because then not the client email program is used to send the mail and all is done in background.
I just tried the example below which I found at Microsoft and it worked fine. Can even be done without Javascript by simply adding the "mailto:" to the form action attribute. Also note that the form element names correspond to mailto query string parameters, i.e., "subject" and "body".
References: Microsoft mailto Protocol and RFC2368:The mailto URL scheme
Micosoft SharePoint, Adobe LiveCycle, and other middleware are able to process the emailed forms on the back end. Or one could roll their own using Java, C#, PHP, etc. Yet, that wasn't part of the class assignment ... er ... I mean question.
<html>
<body>
<form action="mailto:user#example.com" method="get">
<input name="subject" type="hidden" value="Message Title">
Feedback:<br/>
<textarea name=body cols="40">
Please share your thoughts here
and then choose Send Feedback.
</textarea>
<input type="submit" value="Send Feedback">
</form>
</body>
</html>

Categories

Resources