I have a ajax php comment system which works fine but it submits data on pressing comment button. I want to give some fancy touch and remove comment button, means comment will be submitted on enter key.
<form method='post' name='form' action=''>
<input type='text' name='comment' id='comment' placeholder='Write a comment....' />
<input type='button' name='submit' id='submit' value='Comment'/>
</form>
<script type="text/javascript" >
$(function() {
$("#submit").click(function() {
var test = $("#comment").val();
var comment = test;
var id = '<?php echo $id ?>';
if (test == '') {
alert("Please Enter Some Text");
} else {
$.ajax({
type: "POST",
url: "comment.php",
data: {comment : comment,id : id},
cache: false,
success: function(html) {
$(".coments").prepend(html);
$("#comment").val('');
}
});
}
return false;
});
});
</script>
Code above is with comment button and works fine. Now I am trying to submit comment on enter key:
<script type="text/javascript" >
$(function() {
$('#comment').keyup(function(e) {
if(e.keyCode == 13) {
var test = $("#comment").val();
var comment = test;
var id = '<?php echo $id ?>';
if (test == '') {
alert("Please Enter Some Text");
} else {
$.ajax({
type: "POST",
url: "comment.php",
data: {comment : comment,id : id},
cache: false,
success: function(html) {
$(".coments").prepend(html);
$("#comment").val('');
}
});
}
return false;
}
});
});
</script>
This code does not work on pressing enter key page is refreshed no comment is submitted.
Adjust input="button" to <input type='submit' name='submit' id='submit' value='Comment'/>.
But if you don't want the submit button to appear you can still hide it with css<input type='button' name='submit' id='submit' value='Comment' style="display:none;" />
And then you do your magic to submit the form using jQuery
$(function() {
$('#comment').keyup(function(e) {
if (e.keyCode == 13) {
var test = $("#comment").val();
var comment = test;
var id = '<?php echo $id ?>';
if (test == '') {
alert("Please Enter Some Text");
} else {
$.ajax({
type: "POST",
url: "comment.php",
data: {comment : comment,id : id},
cache: false,
success: function(html) {
$(".coments").prepend(html);
$("#comment").val('');
}
});
}
}
});
Since you don't want to reload the page, I suggest you change the form element to a div element. This way, you handle the requests yourself.
<div>
<input type='text' name='comment' id='comment' placeholder='Write a comment....' />
<input type='button' name='submit' id='submit' value='Comment' />
</div>
Here's a quick fiddle: https://jsfiddle.net/w2fepLak/
If you have a button type submit, then it'll automatically submit when pressing the enter key - no JS, no magic needed!
<input type='submit' name='submit' id='submit' value='Comment'/>
Submitting on enter is actually default behavior here. What you want to do is hook in to the submit event, rather than trying to catch everything that will later cause a submit event. So:
Listen for just submit on the form element, not click or keydown.
In the submit handler, call event.preventDefault() to prevent the form from submitting and reloading the page.
In code:
$("form").on("submit", function(e) {
e.preventDefault();
var test = $("#comment").val();
var comment = test;
var id = '<?php echo $id ?>';
if (test == '') {
alert("Please Enter Some Text");
} else {
$.ajax({
type: "POST",
url: "comment.php",
data: {comment : comment,id : id},
cache: false,
success: function(html) {
$(".coments").prepend(html);
$("#comment").val('');
}
});
}
});
The browser will automatically submit when there is only one input[type=text] in the form and press a enter in the input.
To fix this, you can simply add another useless input[type=text] under the form like this:
<form method='post' name='form' action=''>
<input type='text' name='comment' id='comment' placeholder='Write a comment....' />
<input type="text" style="display: none;" name="nothing" value="nothing" />
<input type='button' name='submit' id='submit' value='Comment'/>
</form>
If you are okay without <form> tag. Remove it and you are good to go.
Related
Tell me please, there is a form for sending data to the database. Without a script it works fine, but nothing happens with the script. In the console — Form Data has all the data, and the 200th code arrives, but is not added to the database.
PHP:
<?php
$data = $_POST;
if (isset($data['add'])) {
$posts = R::dispense('posts');
$posts->head = $data['head'];
$posts->desc = $data['desc'];
R::store($posts);
}
?>
HTML:
<form method="POST" id="FormID">
<input type="text" name="head" required />
<input type="text" name="desc" required />
<button type="submit" name="add">Добавить</button>
JS:
<script>
$("#FormID").submit(function(e)
{
var form = $(this);
var url = form.attr('action');
e.preventDefault();
$.ajax({
type: "POST",
url: url,
data: $("#FormID").serialize(),
success: function(data)
{
c = "hello";
$('#FormStatus').text(c);
}
});
});
</script>
You said:
if (isset($data['add'])) {
So the code only does anything if add in the data.
<button type="submit" name="add">Добавить</button>
add is a submit button. It will be included in the data when you submit the form.
data: $("#FormID").serialize(),
You aren't submitting the form. jQuery serialize does not include submit buttons because they aren't successful controls when you aren't submitting the form.
Use some other mechanism to determine if there is data to process (such as the presence of head and desc.
You have forget the action for your form
Why don't simply use $data['name'] instead of R::dispense?
If you what to do a POST request why don't you use $.post()?
What you need is these:
PHP Code:
<?php
$data = $_POST;
if (isset($data['add'])) {
if(isset($data['head']) AND !empty($data['head']) AND isset($data['desc']) AND !empty($data['desc'])) {
$head = htmlspecialchars($data['head']);
$desc = htmlspecialchars($data['desc']);
echo "Hello from server";
}
else {
echo "Please fill the form";
}
}
?>
HTML:
<form method="POST" id="FormID" action="path_to_php_file.php">
<input type="text" name="head" required />
<input type="text" name="desc" required />
<button type="submit" name="add">Добавить</button>
</form>
JS:
<script>
$("#FormID").submit(function(e)
{
e.preventDefault();
var form = $(this),
url = form.attr('action');
var data = {};
// To have post paramaters like
// { 'head' : 'Head value', 'desc' : 'Desc value' }
$.each(form.serializeArray(), function(i, field) {
data[field.name] = field.value;
});
$.post(url, data, function(Responses) {
// Will write "Hello from server" in your console
console.log(Responses);
});
});
</script>
<form id='formregister' autocomplete='off'>
<input type='text' name='user' maxlength='50' placeholder='* Username'>
<input type='text' name='pass' maxlength='50' placeholder='* Password'>
<input type='text' name='name' maxlength='50' placeholder='Ime'>
<button id='btnregister'>Register</button>
</form>
javascript
$('#btnregister').click(function(){
$.ajax({
url: 'regpro.php',
type: 'post',
data: $('#formregister').serialize(),
success: function(data) {
if (data == 'exists') {
alert ('user already exists'); // after closing form is empty!
}
else if (data =='empty'){
alert ('something is missing'); // after closing form is empty!
}
else{
if (window.confirm('Registration is successfull. Do you wont to login?')){
window.location.href = 'login.php'; // doesn't work
}
else {
window.location.href = 'index.php'; // doesn't work
}
}
}
});
});
So why form inputs become empty after closing alert, and why redirections don't work after confirm dialog is closed ?
You should add event.preventDefault(); to your code:
$('#btnregister').click(function(event){
event.preventDefault();
...
});
This method will disable the default submit action of the form when you click on the button.
The problem I've been trying to solve for hours and hours now is following: I cannot stop the redirecting of #myform action after the data has been submitted succesfully to database. I've tried multiple methods but none seem to work. I'm in dire need of help!
The code:
Html(mainview.php):
<div id="submitAccordion">
<form id="myForm" action="userFiles.php" method="post">
Name: <input type="text" name="accordionName" /><br />
<input id="sub" type="submit" name="go" />
</form>
<span id="result"> </span>
</div>
Javascript(mainview_script.js):
$("#sub").click(function () {
var data = $("#myForm :input").serializeArray();
$.post( $("#myForm").attr("action"),
data, function(info) {
$("#result").html(info); } )
});
$("#myForm").submit(function () {
return false;
});
php(userFiles.php):
session_start();
require_once 'database.php';
if ( isset($_SESSION['user_id']) ) {
$sql = "INSERT INTO useraccordion (id, h3) VALUES (:id, :accordion)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':id', $_SESSION['user_id']);
$stmt->bindParam(':accordion', $_POST['accordionName']);
if ( $stmt->execute() ) {
echo "Succesfully inserted";
} else {
echo "Sorry, there was an error";
}
}
I have tried ajax method, prevent.default etc, but none work!
Either change your input type to button
<input id="sub" type="button" name="go" value="Submit"/>
Or try this:
$("form").submit(function(e){
e.preventDefault();
});
First, move your $("#myForm").submit(... out of the click event so it is it's own thing. Then, pass in e into that function. So it would look like this...
$("#myForm").submit(function(e) {
e.preventDefault();
return false;
});
$("#sub").click(function() {
var data = $("#myForm :input").serializeArray();
$.post( $("#myForm").attr("action"),data, function(info) {
$("#result").html(info);
});
});
That will fix your immediate problem. My thought is... Do not even use a form for this. There is no reason to. You are posting the data via Ajax, so there is no reason to have a form that would submit. I would do something like this...
HTML...
<div id="form">
<div class="form-item">
<label for="name">Name:</label>
<input name="name" id="name" type="text" />
</div>
<button id="sub">Submit Form</button>
</div>
Javascript...
$("#sub").click(function() {
var postData = {};
//this is here to be dynamic incase you want to add more items....
$("#form").find('input').each(function() {
postData[$(this).attr('name')] = $(this).val();
});
$.ajax({
url: "YOUR URL HERE",
type: "POST",
data: postData,
success: function(msg) {
$("#result").html(msg);
}
});
});
It is sufficient to prevent deafult action on sub:
$("#sub").click(function (e) {
e.preventDefault();
var data = $("#myForm :input").serializeArray();
$.post( $("#myForm").attr("action"),
data, function(info) {
$("#result").html(info); } )
});
$("#myForm").submit(function (event) { event.preventDefault(); });
That should stop the submission
If you are submitting your form data via ajax or jquery then you should change your input type form 'submit' to 'button' type
<input id="sub" type="button" name="go" value="go"/>
I am fetching php json encoded data using ajax and then setting values to form input then sending it to other page . But json fetched values does not post to other page while normal input values are posting . Here's the code i am using . Your help will be highly appriciated .
`
if(isset($_POST['send_mail'])){
header('Content-Type: application/json');
$out = array('a'=>"Volvo", 'b'=>"BMW", 'c'=>"Toyota");
echo json_encode($out);
//print_r($out);
exit();
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
function send_mail_test(){
var txt = $("#test_txt").val();
if( txt !=""){
$.ajax({
url : "chckvar.php",
type : "POST",
//async : false,
dataType: "JSON",
data : {
send_mail : 1,
txt_val : txt
},
success : function(data){
document.getElementById('code_r').setAttribute('value', data.a);
}
});
//return false;
}
else alert("please enter some text");
//return false;
}
</script>
<form method="post" action="sub.php" name="myform" onSubmit="return send_mail_test()">
<input type="text" name="name" id="test_txt">
<input type="text" name="code_r" id="code_r">
<input type="submit" name="_mail" value="send" >
</form>`
sub.php
<?php
print_r($_POST);
?>
UPDATE
I am using onclick on button in another form and trying to change action page from there and then submitting form to that action is that possible ??
<script>
function action(){
var str = location.href;
var x = "feedback.php?page="+str;
$("#quick_query").attr("action", x);
$('#quick_query').submit();
}
</script>
<form id="myform" method="post" action="">
<input type="button" onclick="action()">
</form>
It is changing the action but doesn't submit the form ? how can i achieve it that will be of great help.
ANSWER UPADTED:
The problem with your code is that the submit event occurs even before ajax is called. The following changes have been done in your code
HTML
<form method="post" action="sub.php" name="myform" id="myform">
<input type="text" name="name" id="test_txt">
<input type="text" name="code_r" id="code_r">
<input type="button" name="_mail" value="send" onclick="return send_mail_test()" >
</form>
<br><hr><br>
<form method="post" action="xyz.php" name="anotherform" id="anotherform">
<input type="button" name="change" value="Change action of above form" onclick="changeformaction();" >
</form>
The onsubmit on the form is removed & the submit button is changed to normal button. The send_mail_test() function is called on the Send button now.
JAVASCRIPT
<script>
function send_mail_test() {
var txt = $("#test_txt").val();
if (txt != "") {
$.ajax({
url : "chckvar.php",
type : "POST",
//async : false,
dataType : "JSON",
data : {
send_mail : 1,
txt_val : txt
},
success : function(data) {
$('#code_r').val(data.a);
$('#myform').submit();
}
});
}else{
alert("please enter some text");
return false;
}
}
function changeformaction(){
$("#myform").prop('action','newaction.php');
$('#myform').submit();
}
</script>
Here a small change is made in ajax success callback , after the response is received and the value is set in the input , the form is made to submit then.
No change is needed in your ajax file.
Try this:
<script>
$(function () {
$('form[name="myform"]').on('submit', function (e) {
e.preventDefault();
var txt = $(this).find("#test_txt").val();
if (txt.length > 0) {
$.ajax({
url: "chckvar.php",
type: "POST",
//async : false,
dataType: "JSON",
data: {
send_mail: 1,
txt_val: txt
},
success: function (data) {
$('#code_r').attr('value', data.a); //$('#code_r').val(data.a);
$(this).submit()
}
});
} else alert("please enter some text");
});
});
</script>
<form method="post" action="sub.php" name="myform">
<input type="text" name="name" id="test_txt">
<input type="text" name="code_r" id="code_r">
<input type="submit" name="_mail" value="send" >
</form>
I am using the following script for validate my contact form.
//submission scripts
$('.contactForm').submit( function(){
//statements to validate the form
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
var email = document.getElementById('e-mail');
if (!filter.test(email.value)) {
$('.email-missing').show();
} else {$('.email-missing').hide();}
if (document.cform.name.value == "") {
$('.name-missing').show();
} else {$('.name-missing').hide();}
if (document.cform.phone.value == "") {
$('.phone-missing').show();
}
else if(isNaN(document.cform.phone.value)){
$('.phone-missing').show();
}
else {$('.phone-missing').hide();}
if (document.cform.message.value == "") {
$('.message-missing').show();
} else {$('.message-missing').hide();}
if ((document.cform.name.value == "") || (!filter.test(email.value)) || (document.cform.message.value == "") || isNaN(document.cform.phone.value)){
return false;
}
if ((document.cform.name.value != "") && (filter.test(email.value)) && (document.cform.message.value != "")) {
//hide the form
//$('.contactForm').hide();
//show the loading bar
$('.loader').append($('.bar'));
$('.bar').css({display:'block'});
/*document.cform.name.value = '';
document.cform.e-mail.value = '';
document.cform.phone.value = '';
document.cform.message.value = '';*/
//send the ajax request
$.post('mail.php',{name:$('#name').val(),
email:$('#e-mail').val(),
phone:$('#phone').val(),
message:$('#message').val()},
//return the data
function(data){
//hide the graphic
$('.bar').css({display:'none'});
$('.loader').append(data);
});
//waits 2000, then closes the form and fades out
//setTimeout('$("#backgroundPopup").fadeOut("slow"); $("#contactForm").slideUp("slow")', 2000);
//stay on the page
return false;
}
});
This is my form
<form action="mail.php" class="contactForm" id="cform" name="cform" method="post">
<input id="name" type="text" value="" name="name" />
<br />
<span class="name-missing">Please enter your name</span>
<input id="e-mail" type="text" value="" name="email" />
<br />
<span class="email-missing">Please enter a valid e-mail</span>
<input id="phone" type="text" value="" name="phone" />
<br />
<span class="phone-missing">Please enter a valid phone number</span>
<textarea id="message" rows="" cols="" name="message"></textarea>
<br />
<span class="message-missing">Please enter message</span>
<input class="submit" type="submit" name="submit" value="Submit Form" />
</form>
I need to clear the form field values after submitting successfully. How can i do this?
$("#cform")[0].reset();
or in plain javascript:
document.getElementById("cform").reset();
You can do this inside your $.post calls success callback like this
$.post('mail.php',{name:$('#name').val(),
email:$('#e-mail').val(),
phone:$('#phone').val(),
message:$('#message').val()},
//return the data
function(data){
//hide the graphic
$('.bar').css({display:'none'});
$('.loader').append(data);
//clear fields
$('input[type="text"],textarea').val('');
});
use this:
$('form.contactForm input[type="text"],texatrea, select').val('');
or if you have a reference to the form with this:
$('input[type="text"],texatrea, select', this).val('');
:input === <input> + <select>s + <textarea>s
$('.contactForm').submit(function(){
var that = this;
//...more form stuff...
$.post('mail.php',{...params...},function(data){
//...more success stuff...
that.reset();
});
});
Simply
$('#cform')[0].reset();
it works: call this function after ajax success and send your form id as it's paramete. something like this:
This function clear all input fields value including button, submit, reset, hidden fields
function resetForm(formid) {
$('#' + formid + ' :input').each(function(){
$(this).val('').attr('checked',false).attr('selected',false);
});
}
* This function clears all input fields value except button, submit, reset, hidden fields
* */
function resetForm(formid) {
$(':input','#'+formid) .not(':button, :submit, :reset, :hidden') .val('')
.removeAttr('checked') .removeAttr('selected');
}
example:
<script>
(function($){
function processForm( e ){
$.ajax({
url: 'insert.php',
dataType: 'text',
type: 'post',
contentType: 'application/x-www-form-urlencoded',
data: $(this).serialize(),
success: function( data, textStatus, jQxhr ){
$('#alertt').fadeIn(2000);
$('#alertt').html( data );
$('#alertt').fadeOut(3000);
resetForm('userInf');
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
e.preventDefault();
}
$('#userInf').submit( processForm );
})(jQuery);
function resetForm(formid) {
$(':input','#'+formid) .not(':button, :submit, :reset, :hidden') .val('')
.removeAttr('checked') .removeAttr('selected');
}
</script>
$.post('mail.php',{name:$('#name').val(),
email:$('#e-mail').val(),
phone:$('#phone').val(),
message:$('#message').val()},
//return the data
function(data){
if(data==<when do you want to clear the form>){
$('#<form Id>').find(':input').each(function() {
switch(this.type) {
case 'password':
case 'select-multiple':
case 'select-one':
case 'text':
case 'textarea':
$(this).val('');
break;
case 'checkbox':
case 'radio':
this.checked = false;
}
});
}
});
http://www.electrictoolbox.com/jquery-clear-form/
Set id in form when you submitting form
<form action="" id="cform">
<input type="submit" name="">
</form>
set in jquery
document.getElementById("cform").reset();
$('#formid).reset();
or
document.getElementById('formid').reset();
Vanilla!
I know this post is quite old.
Since OP is using jquery ajax this code will be needed.
But for the ones looking for vanilla.
...
// Send the value
xhttp.send(params);
// Clear the input after submission
document.getElementById('cform').reset();
}
just use form tag alone, like this :
$.ajax({
type: "POST",
url: "/demo",
data: dataString,
success: function () {
$("form")[0].reset();
$("#test").html("<div id='message'></div>");
$("#message")
.html("<h2>Contact Form Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
.fadeIn(1500, function () {
$("#message").append(
"<img id='checkmark' src='images/check.png' />"
);
});
}
});
e.preventDefault();
});
Using ajax reset() method you can clear the form after submit
example from your script above:
const form = document.getElementById(cform).reset();
If you are using a form tag in your form. Then
$("#cform")[0].reset();
This code will work perfectly but in case you are not using any form tag then you can try to set an empty value to each input field Like this.
$('input[type="text"],textarea').val('');