Sending input by onclick - javascript

Is this possible to add to onclick the comment that is in the textarea in the same form? and how do i get it in javascript function?
<form id='comments' method='post'>
<textarea rows='8' cols='80' name='comments'></textarea> <br />
<input type='submit' name='send' onclick='sendcomment(".$photoid.",".$mynick.",".$_POST['comments'].")' value='Wyƛlij'>
</form>
<script>
function sendcomment(photoid, mynick,comments){ }
</script>

I'm not really sure what you are trying to do. But I think you are over complicating this. Define your action (a PHP controller to deal with the the request) and the form will be submitted by the browser when the submit button is clicked.
<form id='comments' action='/handler.php' method='post'>
<textarea rows='8' cols='80' name='comments'></textarea> <br />
<input type='submit' name='send' />
</form>
UPDATE:
It sounds to me like what you want to do is submit these by AJAX. I'd highly recommend you use the jQuery library to to this.
Add this to your page <head> tag:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
Then change your form to use a class, rather than id because you can only have one id per name for each page. Since you are using a while loop you need to eliminate this issue.
<form class='comments' action='/handler.php' method='post'>
<textarea rows='8' cols='80' name='comments'></textarea> <br />
<input type='submit' name='send' />
</form>
Now, we need some jQuery to help us out...
$(document).on('submit', '.comments', function(event) {
event.preventDefault();
var serialized = $(this).serialize();
$.ajax({
url: "handler.php",
method: "post",
data: serialized,
})
.done(function(data) {
// take some action when the request completes
});
});
This will prevent the default action of submitting the form when you click the button, then the jQuery will take over and serialize (stringify) the form data and send it to the server as an AJAX request. Once the .done fires you can do more, like show the user a message that the submission was successful... maybe disable the submit button so they can't hammer the server with messages easily, etc... I really hope this helps!

Related

Multiple form submit with one Submit button

I have two forms. I want to submit both forms with 1 button. Is there any method that can help me do it?
Example:
<form method="post" action="">
<input type="text" name="something">
</form>
<form method="post" action="">
<input type="text" name="something">
<input type="submit" value="submit" name="submit">
</form>
I want both forms to be submitted with 1 submit button. Any help would be appreciated.
The problem here is that when you submit a form, the current page is stopped. Any activity on the page is stopped. So, as soon as you click "submit" for a form or use JavaScript to submit the form, the page is history. You cannot continue to submit another page.
A simplistic solution is to keep the current page active by having the form's submission load in a new window or tab. When that happens, the current page remains active. So, you can easily have two forms, each opening in a window. This is done with the target attribute. Use something unique for each one:
<form action='' method='post' target='_blank1'>
The target is the window or tab to use. There shouldn't be one named "_blank1", so it will open in a new window. Now, you can use JavaScript to submit both forms. To do so, you need to give each a unique ID:
<form id='myform1' action='' method='post' target='_blank1'>
That is one form. The other needs another ID. You can make a submit button of type button (not submit) that fires off JavaScript on click:
<submit type='button' onclick="document.getElementById('myform1').submit();document.getElementById('myform2').submit();" value='Click to Submit Both Forms'>
When you click the button, JavaScript submits both forms. The results open in new windows. A bit annoying, but it does what you specifically asked for. I wouldn't do that at all. There are two better solutions.
The easiest is to make one form, not two:
<form action='' method='post'>
<input type='text' name='text1'>
<input type='text' name='text2'>
<input type='submit' value='Submit'>
</form>
You can place a lot of HTML between the form tags, so the input boxes don't need to be close together on the page.
The second, harder, solution is to use Ajax. The example is certainly more complicated than you are prepared to handle. So, I suggest simply using one form instead of two.
Note: After I submitted this, Nicholas D submitted an Ajax solution. If you simply cannot use one form, use his Ajax solution.
You have to do something like that :
button :
<div id="button1">
<button>My click text</button>
</div>
js
<script>
$('#button1').click(function(){
form1 = $('#idIFirstForm');
form2 = $('#idISecondForm');
$.ajax({
type: "POST",
url: form1.attr('action'),
data: form1.serialize(),
success: function( response ) {
console.log( response );
}
});
$.ajax({
type: "POST",
url: form2.attr('action'),
data: form2.serialize(),
success: function( response2 ) {
console.log( response2 );
}
});
});
</script>
You could create a pseudo form in the background. No time to write the code, jsut the theory. After clicking submit just stop propagation of all other events and gather all the informations you need into one other form you append to document (newly created via jquery) then you can submit the third form where all the necesary infos are.
Without getting into why you want to use only 1 button for 2 forms being submitted at the same time, these tools that will get the input data available for use elsewhere:
Option 1...
Instead of using <form> - collect the data with the usual Input syntax.
ex: <input type="text" name="dcity" placeholder="City" />
Instead of using the form as in this example:
<form class="contact" method="post" action="cheque.php" name="pp" id="pp">
<label for="invoice">Your Name</label>
<input type="text" id="invoice" name="invoice" />
<button class="button" type="submit" id="submit">Do It Now</button>
</form>
use:
<label for="invoice">Your Name</label>
<input type="text" id="invoice" name="invoice" />
<button type="button" onclick="CmpProc();" style="border:none;"><img src="yourimage.png"/> Do It Now</button>
Then code the function CmpProc() to handle the processing/submittion.
Inside that function use the Javascript form object with the submit() method as in...
<script type="text/javascript">
function submitform() {
document.xxxyourformname.submit();
}
</script>
Somehow I suspect making the two forms into one for the POST / GET is worth reconsidering.
Option 2...
Instead of POST to use the data to the next page consider using PHP's $_SESSION to store each of your entries for use across your multiple pages. (Remember to use the session_start(); at the start of each page you are storing or retrieving the variables from so the Global aspect is available on the page) Also less work.
Look man. This is not possible with only HTML. weither you gether the inputs in one form or else you use jquery to handle this for you.

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();
})
});
});

How to submit a form with javascript without having the button trigger a new page?

I have a simpel form that I would like to submit with Ajax. It seems that regardless how I approach this, the form keeps insisting to refresh the page.
I would like the form to be submitted with a GET request, submitted with javascript, because I need a js response back from the server.
<div id='form_wrapper'>
<div class='gradient'></div>
<form action='' class='my-form' method='get' name='my-form'>
<div class='header'>
<h1>Submit this form</h1>
<span>Please fill out all fields, and then submit the form.</span>
</div>
<div class='content'>
<input class='input full_name' name='full_name' placeholder='Your full name' type='text'>
<div class='full_name-icon input-icon'></div>
<input class='input address' name='address' placeholder='Your full address' type='text'>
<div class='address-icon input-icon'></div>
</div>
<div class='form-footer'>
<input class='button' name='submit' type='submit' value='SUBMIT'>
<input class='help' name='submit' type='submit' value='HELP?'>
</div>
</form>
</div>
Also, I would like my submit button to not look like it is being pushed down - meaning that I would like to avoid having that blue border around the button once it has been pushed. I usually avoid the blue border by letting my buttons have href='javascript:void(0)', but as this is a form button I don't suppose I can apply my own href.
For one, i don't think you should have 2 submit buttons, but have an other mechanism in place, for the two different submit actions, however, that aside, i'll give you a jQuery answer since it's faster:
$(document).on('submit','.my-form',function(e){
e.preventDefault();
$.ajax({
url: "processing_page.php",
type : 'get',
data: { name : $('.full_name').val(), address: $('.address').val },
dataType: 'json'
}).success(function(data){
// do something here
console.log(data); //this is an object in my example
});
});
You'll also need a php processing page (named processing_page.php in my example) to get back some data. For example (didn't go through all the verification steps on either side, but you'll get the gist of it):
<?php
$myData = ['name' => '', 'address' => ''];
$name = $_POST['name'];
$address = $_POST['address'];
$myData['name'] = $name;
$myData['address'] = $address;
echo json_encode($myData);
?>
Reason for the long answer is so that you can verify your code at the basic level.
Hope i didn't make any typos.
Taken from the jQuery documentation:
$( "#target" ).submit(function( event ) {
alert( "Handler for .submit() called." );
event.preventDefault();
});
event.preventDefault() stops the submit from triggering a new page.
You could do the following if you're using vanilla JavaScript;
function myFunc(){
alert(1);
}
<form id="formID" onsubmit="myFunc(); return false;">
<input type="submit" value="Submit">
</form>
When you click the submit button, it will activate the myFunc() JavaScript function and using return false in this manner will prevent the page from being changed. Then simply call document.getElementById('formID') to load the form details up. Alternatively you can use an active selector or jQuery $("#formID").
Happy Coding!

Change page after submitting the form using javascript

I have a form that after submitting goes to page "http://qwertyasdfgh.rozblog.com/New_Post" ( the action value )
I don't want to change the action but I want to redirect to another page after submitting.
I tried to redirect to "http://qwerty.rozblog.com/page/success" after submitting but it doesn't work .
here is the code I tried :
(html)
<form method="post" action="http://qwertyasdfgh.rozblog.com/New_Post" id="f1">
<input type="text" name="title" style="width:300px"><br />
<input type="text" name="pimg" style="width:300px" maxlength="3072"><br />
<textarea dir="rtl" id="post" name="post" style="width:300px;" aria-hidden="true"></textarea><br />
<input type="submit" name="postsubmit" value=" submit " style="background:#333;" onclick="location()">
</form>
(js)
function location() {
window.location.replace("http://qwerty.rozblog.com/page/success");
}
and here is the fiddle
You can submit the form using jquery and AJAX (or I misunderstood you):
$('#f1').submit(function(e)
{
e.preventDefault();
$.post('http://qwertyasdfgh.rozblog.com/New_Post',
formDataAsJSON, //use eg. jquery form plugin
function(data)
{
window.location = 'somewhere';
}
);
});
You have two choices.
1) Submit that form using AJAX and after recieving response from server redirect browser to your desired page. You can use for example jQuery with Ajax form plugin. The code would look like this:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
// wait for the DOM to be loaded
$(document).ready(function() {
// bind 'f1' form and provide a simple callback function
$('#f1').ajaxForm(function() {
window.location = "/page/success"
});
});
</script>
OR
2) You can leave your form and js as is, and use for example php to redirect user after doing some stuff.
New_post.php
<?php
// some stuff without printing (you cant change headers if you print something)
Header("Location: /page/success");
If possible, you can configure /New_Post to redirect to /page/success using meta refreshing in head:
<meta http-equiv="refresh" content="0; url=http://qwerty.rozblog.com/page/success">

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