I'm trying to get a check box to trigger the submit button in a form. Basically, this is a touch screen game that takes users emails using a touch keyboard. The Enter button on the touch keyboard is what switches into the game. When I add document.getElementById("").submit in the javascript just resets everything. What I've done to try and work around this is to put a button next to it that is like an "opt-in" type of deal. When you click the button it copies the email address into the form. But I still need the submit button on the form to click without resetting the site or not updating the data.txt where the form info goes.
<body>
<script>
function myFunction() {
var x = document.getElementById("name").innerHTML;
document.getElementById("demo").innerHTML = x;
}
</script>
<span id="name">
<!-- Displaying name input from touch keyboard here -->
</span>
<form method="post" class="emailForm" id="demo" name="myForm">
<input type="text" name="subscriptions" id="formName"><br>
<input type="submit" name="mySubmit" id="submitBtn">
</form>
<div class="roundedB">
<input onclick="myFunction()" type="checkbox" value="None" id="roundedB" name="Submit" />
<label for="roundedB"></label>
</div>
</body>
<?php
if(isset($_POST['subscriptions']))
{
$data=$_POST['subscriptions'];
$fp = fopen('data.txt', 'a');
fwrite($fp, $data);
fclose($fp);
}
?>
What I want to achieve is to click the check button, the form fills and auto-submits to data.txt. Website does not reload.
Drat - started this before the noticing an accepted answer but will post this anyway as it might help.
<?php
error_reporting( E_ALL );
ini_set( 'display_errors', 1 );
if( $_SERVER['REQUEST_METHOD']=='POST' ){
ob_clean();
/* This is where you would process the POST request somehow... */
$_POST['response']=date( DATE_ATOM );
$_POST['ip']=$_SERVER['REMOTE_ADDR'];
/* prepare data for saving */
$json=json_encode( $_POST );
/* write to file */
$file=__DIR__ . '/subscriptions-data.txt';
file_put_contents( $file, $json . PHP_EOL, FILE_APPEND );
/* send back a response of some sort to the ajax callback function */
exit( $json );
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>submit form button trigger when secondary button clicked</title>
<script>
document.addEventListener( 'DOMContentLoaded', function(){
const xhr_callback=function(r){
console.info( r );
};
const ajax=function(url,payload,callback){
let xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if( this.status==200 && this.readyState==4 )callback( this.response );
}
xhr.open( 'POST', url, true );
xhr.send( payload );
};
const clickhandler=function(e){
if( this.checked ){
let payload=new FormData( document.forms.myForm );
ajax.call( this, location.href, payload, xhr_callback );
}
};
document.querySelector('input[type="checkbox"][name="submit"]').addEventListener( 'click', clickhandler );
});
</script>
</head>
<body>
<span id='name'>
<!-- Displaying name input from touch keyboard here -->
</span>
<form method='post' class='emailForm' name='myForm'>
<input type='text' name='subscriptions' value='geronimo#hotmail.com' />
<br />
<input type='submit' />
</form>
<div class='roundedB'>
<input type='checkbox' value='None' name='submit' />
<label for='roundedB'></label>
</div>
</body>
</html>
You can try with something like this
As you can see I used Jquery for that. You can make a trigger on change.
Then to send ajax request to server.
$('#myCheck').on('change',function() {
// ajax request
alert('Do your action');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Check me <input type="checkbox" id="myCheck">
Simple ajax
$('#myCheck').on('change', function() {
var data = JSON.stringify({
email: $('input#email').val()
});
$.ajax({
type: "POST",
url: "email.php",
data: data,
success: function(){
alert('success');
},
error: function(){
alert('error');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form1">
Email: <input type="text" id="email" value="someone#email.com">
</form>
<form id="form2">
Check me <input type="checkbox" id="myCheck">
</form>
This one will give you error in alert, because there is not email.php file.
Here is code you need for that
index.php
$('#roundedB').on('change', function() {
var email = $('input#subscriptions').val();
$.ajax({
type: "POST",
data: {
'subscriptions': email
},
url: 'send.php',
success: function (data) {
alert(data);
},
error: function (data) {
alert(data);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<span id="name">
<!-- Displaying name input from touch keyboard here -->
</span>
<form method="post" class="emailForm" id="demo" name="myForm">
<label for="subscriptions">Email address</label>
<input type="text" name="subscriptions" id="subscriptions"><br>
</form>
<div class="roundedB">
<input type="checkbox" id="roundedB" name="Submit" />
<label for="roundedB"></label>
</div>
</body>
send.php
<?php
if(isset($_POST['subscriptions']))
{
$data=$_POST['subscriptions']."\n";
$fp = fopen('data.txt', 'a');
if(fwrite($fp, $data)){
print 'successful';
}else{
print 'error';
}
fclose($fp);
}
Related
Hello I want to get the value of this input and fetch it using ajax no database at all. thank you. how can i do it with ajax?
<form method="POST">
<input type="text" name="input" id="card-code" value='<?php echo $code ?>' class="form-control">
<input type="text" id="card-pin" value='<?php echo $code2 ?>' class="form-control" maxlength="3">
</form>
there is my inputs and here is the button.
<form action="top-up.php" method="POST">
</div>
</div>
<div class="col-md-6" style="margin-top: -160px">
<div class="caption">
<div class="jumbotron">
<textarea class="form-control text-center" id="scanned-QR" name="lblQrTxt" onchange = "change()"></textarea><br><br><br>
<input class="btn btn-primary btn-lg" type="submit" name="btnSubcode" value="PROCESS"></input>
</div>
</div>
</div>
</div>
</form>
so the final output sould not refresh the page and the textarea value will be send to the textbox
The jQuery Form Plugin allows you to easily and unobtrusively upgrade HTML forms to use AJAX. The main methods, ajaxForm and ajaxSubmit, gather information from the form element to determine how to manage the submit process.
http://malsup.com/jquery/form/#getting-started
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#myForm').ajaxForm(function() {
alert("Thank you for your comment!");
});
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<form id="myForm" action="comment.php" method="post">
Name: <input type="text" name="name" />
Comment: <textarea name="comment"></textarea>
<input type="submit" value="Submit Comment" />
</form>
// prepare Options Object
var options = {
target: '#divToUpdate',
url: 'comment.php',
success: function() {
alert('Thanks for your comment!');
}
};
// pass options to ajaxForm
$('#myForm').ajaxForm(options);
Firstly, rewrite your html code as below:
<form id="form" action="top-up.php" method="POST">
</div>
</div>
<div class="col-md-6" style="margin-top: -160px">
<div class="caption">
<div class="jumbotron">
<textarea class="form-control text-center" id="scanned-QR" name="lblQrTxt"></textarea><br><br><br>
<input class="btn btn-primary btn-lg js-form-submit" type="submit"></input>
</div>
</div>
</div>
</div>
</form>
Then, you can write JS something like this:
$(document).on('click','.js-form-submit', function (e) {
e.preventDefault();
var formData = $('#form').serialize();
var url = $('#form').attr('action');
$.ajax({
type: "POST",
cache: false,
url: url // Your php url here
data : formData,
dataType: "json",
success: function(response) {
//var obj = jQuery.parseJSON(response); if the dataType is not specified as json uncomment this
// do what ever you want with the server response
},
error: function() {
alert('error handling here');
}
});
});
This question already has answers here:
Submit a form using jQuery [closed]
(22 answers)
Closed 5 years ago.
Here is my code:
<form action='insert.php' method='post' id='myform' >
<input type='hidden' name='tmdb_id'/>
<button id='insert'>Insert</button>
<p id='result'></p>
<script src='insert.js'></script>
</form>
<form action='insert.php' method='post' id='myform' >
<input type='hidden' name='tmdb_id'/>
<button id='insert'>Insert</button>
<p id='result'></p>
<script src='insert.js'></script>
</form>
<form action='insert.php' method='post' id='myform' >
<input type='hidden' name='tmdb_id'/>
<button id='insert'>Insert</button>
<p id='result'></p>
<script src='insert.js'></script>
</form>
Here is: insert.js
$('#myform').submit(function(){
return false;
});
$('#insert').click(function(){
$.post(
$('#myform').attr('action'),
$('#myform :input').serializeArray(),
function(result){
$('#result').html(result);
}
);
});
The Problem:
Only the code inside first <form></form> tag works. If i click on submit button of other<form></form> tags, then I get re-directed to insert.php file.
What is the problem? If it is related to same id thing, then I would not like to add different id's. for each new form
You don't need multiple instances of insert.js
Use common classes for all the forms and elements instead of duplication of ID's.
We can also use the submit event to post the data
HTML
<form action='insert.php' method='post' class='myform'>
<input type='hidden' name='tmdb_id' />
<button class='insert'>Insert</button>
<p class='result'></p>
</form>
<form action='insert.php' method='post' class='myform'>
<input type='hidden' name='tmdb_id' />
<button class='insert'>Insert</button>
<p class='result'></p>
</form>
<!-- load once per page -->
<script src='insert.js'></script>
JS
$('.myform').submit(function(){
// `this` is the instance of myForm class the event occurred on
var $form = $(this),
url = $form.attr('action'),
data = $form.serializeArray(); // or use serialize() which is more common
$.post( url, data, function(result){
// look inside this form instance for element to populate
$form.find('.result').html(result);
});
return false;
});
ID's Must Be Unique, specifically because it will cause problems in JavaScript and CSS when you try to interact with those elements.
Assuming you load insert.js once into the page:
<form action='insert.php' method='post' class='myform' >
<input type='hidden' name='tmdb_id'/>
<button class='insert'>Insert</button>
<p class='result'></p>
</form>
<form action='insert.php' method='post' class='myform' >
<input type='hidden' name='tmdb_id'/>
<button class='insert'>Insert</button>
<p class='result'></p>
</form>
<form action='insert.php' method='post' class='myform' >
<input type='hidden' name='tmdb_id'/>
<button class='insert'>Insert</button>
<p class='result'></p>
</form>
Once you have that done you can use a single jQuery function to handle all of the forms:
$(function() {
$('.insert').click(function(e){
e.preventDefault();
$.post(
$(this).closest('.myform').attr('action'),
$(this).closest('.myform :input').serializeArray(),
function(result){
$(this).closest('.myform').find('.result').html(result);
}
);
});
});
You do have to do some DOM traversal to get the form elements related to the insert button.
$(this).closest('.myform') finds the parent of the insert button
$(this)closest(.myform').find('.result') finds the child element with the class of 'result' to add the results to.
Try something like below using jQuery Ajax:
$(".submit-button-class").click(function() {
var formData = $(this).closest('form').serialize();
$.ajax({
type: "POST",
url: "YOUR URL",
data: formData,
dataType: 'json',
beforeSend: function() {
//show loading image while processing
},
success: function(resp) {
// do something here
},
error: function(e) {
alert('error: ' + JSON.stringify(e));
}
});
});
Note: you should use class selector instead of id selector for submit button
I have a modal form using bootstrap. The form contains some text inputs and a image input.
I submit the form with ajax, and all data is received at the PHP file correctly. Alas, the image isn't being uploaded.
What is my code problem?
<script>
$(document).ready(function () {
$("input#submit").click(function(){
$.ajax({
type: "POST",
url: "insert.php",
data: $('form.contact').serialize(),
success: function(msg){
$("#th").html(msg)
$("#form-content").modal('hide');
$("#pro").html(content);
},
error: function(){
alert("failure");
}
});
});
});
</script>
The form:
<form class="contact" name="contact" enctype="multipart/form-data">
<label for="inputNombre" class="sr-only">Título</label>
<input id="inputNombre" name="inputNombre" class="form-control" placeholder="Título" required="TRUE" autofocus="" type="text">
<br>
....
<div class="upload_pic1 inline">
<input id="imagen" name="imagen" type="file">
</div>
<div class="modal-footer">
Cerrar
<input id="submit" class="btn btn-success" type="submit" value="Crear">
</div>
</div>
</form>
EDIT:
insert.php
<?php
session_start();
if (!isset($_SESSION["name"]) && $_SESSION["name"] == "") {
// user already logged in the site
header("location: Login.html");
}
require_once('funt.php');
conectar('localhost', 'root', '', 'db');
if (isset($_POST['inputNombre'])) {
$nombre = strip_tags($_POST['inputNombre']);
....
//Here the var imagen
if(is_uploaded_file($_FILES['imagen']['tmp_name'])){
$rutaEnServidor='imagenes';
$rutaTemporal=$_FILES['imagen']['tmp_name'];
$nombreImagen=$_FILES['imagen']['name'];
$rutaDestino=$rutaEnServidor.'/'.$nombreImagen;
move_uploaded_file($rutaTemporal,$rutaDestino);
} else { //Always enter here, so is not uploaded
$rutaEnServidor='imagenes';
$rutaTemporal='/noPicture.png';
$rutaDestino=$rutaEnServidor.'/noPicture.png';
move_uploaded_file($rutaTemporal,$rutaDestino);
}
...
How can I change this and upload the picture with all data in form?
You can use FormData interface. Then you have to tell jQuery not to set content type, nor process data.
Check compatibility table for the FormData constructor first. It might suffice.
Otherwise read through this discussion, How can I upload files asynchronously?.
I've been reluctant to open a question, but after fighting this for 6+ hours I'm now cross-eyed.
I've got some experience with PHP and HTML but Ajax and jQuery is new to me (I first heard about it yesterday).
I want the page to display the submitted values inside the div class="result" without refreshing. Anyway, the workflow:
j.php loads > user fills out two text fields (phone and gz) > click Submit button > jpost.php is called and echos variables > PHP variables need to display is div class=result on j.php
j.php =
<html>
<head>
<script src="//code.jquery.com/jquery-latest.js"></script> <!-- load jquery via CDN -->
<script>
$(document).ready(function() {//start document ready
$('#submit-button').click(function (){
$.ajax({
type: 'POST',
url: 'jpost.php',
data: $("#cdr").serialize(),
success: function(d){
$(".result").html(d);
}
});
});
});//end document ready
</script>
</head>
<body>
<div id="cdr">
<div>
<input type="text" id="phone" name="phone" value="" placeholder="phone" size="40" />
</div>
<div>
<input type="text" id="gz" name="gz" value="" placeholder="gz" size="40" />
</div>
<div>
<button id="submit-button">Submit</button>
</div>
</div>
<div class="result"></div>
</body>
</html>
jpost.php
<?php
$phone = $_POST['phone'];
$gz = $_POST['gz'];
echo $phone;
echo $gz;
print_r($_POST);
echo "grrrr"
?>
So all I want is $gz and $phone to echo out in my result div on j.php, but all that shows up is:
Array ( ) grrrr
This makes me believe that my variables are being lost somewhere :P or I'm echoing them incorrectly.
Thanks so much for any help!
Short
The problem was :
1.You need a form in order to serialise the data ( and not a div ) 2. You need to prevent the default behaviour of the event
Long
In order to serialise the data, you need to have a form. i created the form with id #cdr-form
Also, you need to make sure to prevent the default behaviour of the button ( event ) with e.preventDefault() . Read more about it here
<html>
<head>
<script src="//code.jquery.com/jquery-latest.js"></script> <!-- load jquery via CDN -->
<script>
$(document).ready(function() {//start document ready
$('#submit-button').click(function (e){
e.preventDefault();
$.ajax({
type: 'POST',
url: 'http://localhost/~metaly/tests/j.php',
data: $("#cdr-form").serialize(),
success: function(d){
$(".result").html(d);
}
});
});
});//end document ready
</script>
</head>
<body>
<div id="cdr">
<form id="cdr-form">
<div>
<input type="text" id="phone" name="phone" value="" placeholder="phone" size="40" />
</div>
<div>
<input type="text" id="gz" name="gz" value="" placeholder="gz" size="40" />
</div>
<div>
<button id="submit-button">Submit</button>
</div>
</form>
</div>
<div class="result"></div>
</body>
</html>
I'm trying to build a subscribe form.
The problem is that the page gets redirected, and the data doesn't get entered into db,
page gets redirected to
http://localhost/xampp/MY/SUB_FOLDERS/includes/parse.php?subscriber=sid%40patel&subscribe=subscribe
HTML CODE
<div id="subsc">
<form class="navbar-form navbar-right" action="includes/parse.php" mathod="post">
<div class="form-group">
<input type="email" placeholder="Email" class="form-control" name="subs" id="subs" required="required">
</div>
<input type="submit" class="btn btn-success" name="subscribe" id="subscribe" value="subscribe">
</form>
</div>
Ajax code:
<script type="text/javascript">
$(document).ready(function(){
$("#subscribe").click(function(){
username=$("#subs").val();
$.ajax({
type: "POST",
url: "includes/parse.php",
//data:dataString,
success: function(html){
if(html=='true')
{
$("#subsc").fadeOut("normal");
$("#subsc").html("Thank you for subscriping!");
}
else
{
$("#subsc").html("Error in subscribing");
}
},
});
return false;
});
});
</script>
PHP script for inserting data to database:
<?php include("connect.php");
if (#$_POST['subs']) {
$subscriber = mysql_real_escape_string(strip_tags($_POST['subs']));
$sendmessage = mysql_query("INSERT INTO subscriber VALUES('','$subscriber',now())");
echo 'true';
}
?>
PS: Name of rows in subscriber id, email, datetime
I guess there is one simpler approach here using your existing code itself...Instead of these lines:
$("#subscribe").click(function(){
username=$("#subs").val();
Use these lines:
$("#subscribe").click(function(e){
e.preventDefault();
. e.stopPropagation();
username=$("#subs").val();
This should stop the form post back even for submit button.
Hope this helps.
Add an id on your form:
<form id="myform" class="navbar-form navbar-right" action="includes/parse.php" method="post">
Change your Javascript to:
<script type="text/javascript">
$(document).ready(function(){
$("#myform").submit(function(event){
username=$("#subs").val();
$.ajax({
type: "POST",
url: "includes/parse.php",
//data:dataString,
success: function(html){
if(html=='true')
{
$("#subsc").fadeOut("normal");
$("#subsc").html("Thank you for subscriping!");
}
else
{
$("#subsc").html("Error in subscribing");
}
},
});
event.preventDefault();
});
});
</script>
This will prevent the default action of the form to submit the data and the apparent redirect. Also by handling the form's submit event you also handle the situation where the form may be submitted by other means.
First bind your subscribe button to a click event and Remove attribute action="includes/parse.php"
<input type="button" class="btn btn-success" name="subscribe" id="subscribe" value="subscribe">
jQuery('#subscribe').click(function(){
jQuery.ajax({
url:'YOUR URL',
type:'POST',
data:'subsribe=true&email='+jQuery('#subs').val(),
success:function(data){
if(data == 'true')
{
//enter code here
window.location.reload(true);
}else{
//enter code here
alert(data);
}
}
});
});
SERVER SIDE
/* AJAX check */
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
if(isset($_POST)){
$subscriber = mysql_real_escape_string(strip_tags($_POST['subscriber']));
$query = "INSERT INTO subscribers('email','timestamp') VALUES('$subscriber',NOW())";
$sendmessage = mysql_query($query) or die(mysql_error());
echo 'true';
}
}
The simplest thing to do would be changing the type of your #subscribe element to button instead of submit.
<div id="subsc">
<form class="navbar-form navbar-right" id="SubsForm">
<div class="form-group">
<input type="email" placeholder="Email" class="form-control" name="subscriber" id="subs" required="required">
</div>
<input type="button" class="btn btn-success" id="subscribe" value="subscribe">
</form>
</div>
And JavaScript -
<script type="text/javascript">
$(document).ready(function(){
$("#subscribe").click(function(){
$.ajax({
type: "POST",
url: "includes/parse.php",
data:$('#SubsForm').serialize(),
success: function(html){
if (html=='true') {
$("#subsc").fadeOut("normal");
$("#subsc").html("Thank you for subscriping!");
} else {
$("#subsc").html("Error in subscribing");
}
},
});
});
});
</script>
More about $().serialize can be found here - http://api.jquery.com/serialize/
The .serialize() method creates a text string in standard URL-encoded
notation. It can act on a jQuery object that has selected individual
form controls....