How to access form data from javascript - javascript

I am a javascript newb so any help on this matter would be appreciated!
I am trying to get the user submitted data back after submission.
I have a javascript function that replaces one form with another. A kind stackoverflow user helped me create this function.
function Vanish(event) {
event.preventDefault();
// Specify the id of the form.
var IDofForm = "quest";
// Specify the id of the div containing the form.
var IDofDivWithForm = "question";
// Specify the id of the div with the content to replace the form with.
var IDforReplacement = "entryform";
if(document.getElementById(IDofDivWithForm).innerHTML = document.getElementById(IDforReplacement).innerHTML){
return true;
}
else{
return false;
}
}
Then I have my forms :
<div id="question">
<form action="" method="POST" name="quest" id="quest" onsubmit="Vanish(event)">
<textarea name="question" class="question-field" placeholder="Ask your question..."></textarea><br><br>
<input type="submit" name="qsubmit" onclick=" Change();">
<!-- Change() only swaps images on the screen-->
</form>
</div>
<!-- Vanishing Form -->
<div id="entryform" style="display:none;">
<form action="" method="POST" id="email">
<input type="text" name="fName" placeholder="First Name" class="forms" value="<?echo $_POST['question'];?>">
</br>
<input type="text" name="sName" placeholder="Second Name" class="forms">
</br>
<input type="text" name="email" placeholder="Email" class="forms">
</br>
<input type="image" src="images/submit.png" name="esubmit" onclick="submitForm()">
</br>
</div>
As you can see from above I have two forms. the entry form replaces the question form after it has been submitted.
My question today is how do I get the entered data?
I prefer php as I understand it more so if there was a php method to this that would be great however all solutions will be helpful!.
For PHP I have tried using the $_REQUEST and $_POST methods to try and get back the data but it does not work.
My forms all submit to the page they are on.

First of all JavaScript is client side programming language so to get data to server you need to make a http/https request to server and send/receive data
Good read What is the difference between client-side and server-side programming?
and to do that you can either use html Form or ajax
Form
In form you simply send data to url in action ( if no url specified it will make request to current page else specified action url)
Ajax
you can send data using ajax for that you just need to make ajax request like below (i highly recommended to use JavaScript ( but if you are good at JavaScript that you can use Jquery framework too )
var yourFormId = document.getElementById("email");
email.onsumbit = function(e){
e.preventDefault();
var formData = new FormData(yourFormId );
var request = new XMLHttpRequest();
request.open("POST", "your-url");
request.send(formData);
}
// here by formData object you can get all data in single code of line
and to do with jquery see this post it has very simple example jQuery Ajax POST example with PHP
Now couple of good Reads
FormData Objects
Ajax : MDN its really good source

Related

Adding variables to a form post url with javascript

On my website there is a form a new user will have to fill out and then after a text message will be sent to the user. This is how the form action looks
http://example.com/app_api.php?view=send_sms&&user=username&&pass=password&&message=hello+there+welcome+to+our+group&&sender_id=example&&to=00000000&&key=4
But since every user's phone number is different, i want to replace the to variable in the form action with the one the user will input in the textfield phone
can anyone help me through
<form id="new_member_sms" name="new_member_sms" method="post" action="http://example.com/app_api.php?view=send_sms&&user=username&&pass=password&&message=hello+there+welcome+to+our+group&&sender_id=example&&to=00000000&&key=4">
<label for="phone"></label>
<blockquote>
<p>
<input name="phone" type="text" id="phone" />
</p>
</blockquote>
</form>
Pretty trippy form with sends via POST and also includes GET variables via the action's query string, but here's a quick jquery solution for replacing the phone number in the query string:
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js"></script>
<script type="text/javascript">
$('#new_member_sms').submit(function(){
var formAction = $(this).attr('action');
var newAction = formAction.replace('00000000', $('#phone').val());
$(this).attr('action', newAction);
});
</script>

AJax variable not getting send to php variable

Im very new to Ajax and Jquery and learning through SO and online tutorials so please keep in mind im a rookie should you read and be kind enough to answer my post.
I have managed to create the following which is a form that displays a message on submit. If form was successfully submitted a message is displayed without page refreshing as you can see in image below:
FORM
<form name="message-form" action="" id="contact-form" method"post">
Message<br /> <input type="text" name="msg" value="" /><br />
<input type="submit" value="Contact Us" name="contact" class="buttono" />
</form>
<div class="form-feedback" style="display:none">
Thank You We will Get Back to you
</div>
<div class="form-feedback" style="display:none">
Ooops....Something Went Wrong
</div>
<div>
JQUERY
$(function(){
$("#contact-form").submit(function(e){
e.preventDefault();
$form = $(this);
$.post(document.location.url, $(this).serialize(), function(data){
$feedback = $("<div>").html(data).find(".form-feedback").hide();
$form.prepend($feedback)[0].reset();
$feedback.fadeIn(1500)
})
});
})
What I want to do
Retrieve the value from text field message and assign it to php variable
My problem
When I try to retrieve the value of message with the following code, nothing happens:
PHP code below form
<?php
if(isset($_POST['contact'])){
$message = $_POST['msg'];
echo $message;
}
?>
Im very new to Ajax so I guess I am doing something wrong here, unfortunately I dont know where I am going wrong so I am hoping someone can put me on the right path here.
Thanks in advance
Hanoncs suggestion will work, but keeping things only browser side (by displaying the message only from form to div), will always give the user the impression that message is send (processed) server-side, while it is not always the case, one would make php return it before displaying it with javascript. So here is another approach I suggest:
First, Make a Separation of concerns: Sending a POST HTTP Request to the same current page contardicts somehow the purpose of AJAX. The HTTP Response will contain all the page ( the HTML rendred by PHP, the embeded HTML used for templating, and maybe the script if it is not joined in a script tag). Instead, I suggest you create a small separate php file that is responsible for rendereing only the needed markup. And so, instead of using $.post(document.location.url.., one would use $.post('pathToSmallPHPFile'..
Second, let jQuery AJAX functions accept callbacks or use promises. I suggest you carefully read the following link.
The issue is that you are using ajax, which does not cause a page refresh, and then trying to echo out the posted variable, since there is no page refresh, php will not process the page again to echo the posted variable.
My solution is to use javascript to display the text entered and then database it using php.
Here is an example,
$(document).ready(function () {
$(".button").click(function () {
$('p').text($('#msg').val());
});
});
http://jsfiddle.net/r4nanmof/ you dont need ajax if all you want to do is display it on the page. If you plan on saving in the database then ajax is required.
Jquery Code for posting the message value to the php file is given below:
$('#contact_btn').click(function(event){
event.preventDefault();
var url = "url/of/the/php/page/where/to/process/data";
var data = $("#msg_box").val();
var wrapper = $('#wrapper');
$.ajax({
type: "POST",
url: url,
data: data,
success: function(response){
wrapper.html("The reponse from the page is " + response);
},
error: function(xhr,status,msg){
//Handle error here
}
});
});
<code>
<div id="wrapper">
<form name="message-form" action="" id="contact-form" method"post">
Message<br /> <input type="text" name="msg" id="msg_box" value="" /><br />
<input type="submit" id="contact_btn" value="Contact Us" name="contact" class="buttono" />
</form>
<div class="form-feedback" style="display:none">
Thank You We will Get Back to you
</div>
<div class="form-feedback" style="display:none">
Ooops....Something Went Wrong
</div>
</div>
</code>
Message
Thank You We will Get Back to you
Ooops....Something Went Wrong
Its not necessary in your case but change method"post"> to method="post">
And change your Form
<form name="message-form" action="" id="contact-form" method="""post">
Message<br /> <input type="text" name="msg" value="" /><br />
<input type="submit" value="Contact Us" name="contact" class="buttono" />
</form>
<div class="form-feedback" style="display:none"> </div>
And use the following jQuery code to post your data
$(function () {
$("#contact-form").submit(function (e) {
e.preventDefault();
$form = $(this);
$.post(
document.location.url,
$(this).serialize(),
function (data) {
$(".form-feedback").html("Your msge " + data + " is recieved and we will get back soon");
$(".form-feedback").show();
})
});
});

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

Need Help Returning Data From HTML Form on New HTML Page using JavaScript

I'm having a bit of trouble with something I'm sure most of you will laugh at.
I have a form built into one HTML page (contact.html), and I need to have a second HTML page (submit.html) display the information entered into the form using JavaScript. Here is my form code from page 1:
<form name="contact" method="post" action="submit.html">
<p>First Name: *</p><input type="text" name="first">
<p>Last Name: *</p><input type="text" name="last">
<p>Cell Phone Number:</p><input type="text" name="number">
<p>E-mail Address: *</p><input type="text" name="address">
<p>Comment: *</p>
<p><textarea name="comments" cols="25" rows="5">
</textarea></p>
<p><input type="submit" value="Submit"></p>
</form>
Can someone please point me in the right direction? I'm literally brand new to JavaScript, so I don't understand much of any of it yet.
Thank you in advance, and please take it easy on me!
You can't get post parameters using javascript - post parameters are going through the headers in a hidden way and you have to set your second page to be some server side page (php,asp.net etc...)
In php for example you can get post parameters using this:
$first_value = $_POST['first'];
If you still want to use only javascript you can change your method of the form to "get" (method="get") and then the parameters will be in the URL - and then in the other page you can use a regexp to take the get params using this function:
function getQSParam(key,target){
var value = '';
if(!target){
target = location.href;
}
var pattern = key + '=([^&]+)';
var o_reg = new RegExp(pattern,'i');
var matches = o_reg.exec(target);
if(matches && matches[1]){
value = matches[1];
}
return value;
}
So if the url will be like that: submit.html?first=karl&last=marx&...
you can take those parameters using the function like that:
var first_value = getQSParam('first');
var last_value = getQSParam('last');
and so on...

Create a Form element using javascript and submit it without redirecting/refreshing

I am using a Form in a LightBox which contains some input element.
<form name="imageUploadForm" action="uploadImage.do" method="post" enctype="multipart/form-data">
<input type="text" id="id" name="id" style="display: none;" value="">
<div id="fileUploaderDiv">
<input type='file' name="file0" id ="file0" />
</div>
<button onclick="javascript:ImageUploader.attachImage();">Upload</button>
</form>
can anybody tell me how to copy this form in new one and submit it without redirecting user or knowing him about form submission using javascript or jquery?
http://api.jquery.com/serialize/
$('#yourbutton_notintheexample_you_provided').click(function(){
var myForm = $('form[name=imageUploadForm]')
var data = myForm.serialize();
$.ajax({
url: myForm.attr('action'),
type: myForm.attr('method'),
data: data,
success: function(){
window.alert("write your form handling code here")
}
});
});
or something along the lines.
In prototype, there was a single convenience method, called Form.request, read about it here.
In order to send data to a server (through submitting a form or otherwise) one can use AJAX. The user does not need to be informed (but I'd recommend letting the user know somehow).
JavaScript tutorial
jQuery docs

Categories

Resources