In a web form in a PHP program, the form is a regular HTML form.
Now, the form has 3 separate text boxes. Let their IDs/names be box1, box2 and box3 respectively
What I want to happen is, when the form gets posted --
The following text gets posted--> box1 + box2+ box3 contents, separated by commas.
I wish to do this using JQuery- I looked up JQuery "submit" function but could not find any direct way to replace the parameters-- how can I implement the above?
You could do this :
$('#yourForm').submit(function(e){
var form = $(this)
//Do you validation
if(isValid){
var mergedInput = $('<input/>');
var inputToMerge = ['#box1','#box2','#box3'];
var valueToMerge = $.map(inputToMerge, function(selector){
val = $(selector).val()
$(selector).remove()
return val;
})
mergedInput.val(valueToMerge.join(','));
mergedInput.prop('name', 'mergedInput')
mergedInput.appendTo(form);
}else{
return false;
}
})
Basicly, it is merging your input into one accessible via php with ['mergedInput'].
i think you can do this easily using ajax .. Kindly check Change contents of submitted form on submit
if you want to do this without ajax, you may have to use hidden fields .. Kindly check jquery-add-additional-parameters-on-submit-not-ajax
You can use AJAX to solve your problem
Your HTML
<form onsubmit="return sendBoxes()">
<input type="text" id="box1">
<input type="text" id="box1">
<input type="text" id="box1">
<input type="submit">
</form>
And JS
function sendBoxes(){
var values = "'"+$('#box1').val()+"'"+$('#box2').val()+"'"+$('#box3').val()+"'";
jQuery.ajax({
url: "ajax_ajax.php",
data: "boxes="+values,
cache: false,
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error.\n" + textStatus + " " + errorThrown);
}
});
return false;
}
HTML
<input id="box1" type="text" />
<input id="box2" type="text" />
<input id="box3" type="text" />
<input id="submit_button" type="submit" />
JS
function submit(){
$.ajax({
type: "POST",
url: "someurl.php",
data:{'boxes':$('#box1').val()+","+$('#box2').val()+","+$('#box3').val()}
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
$("#submit_button").click(function(e) {
submit();
e.preventDefault();
return false;
});
This would check whether submit button is clicked and sends three box values separated by comma
Related
I am trying to submit a form on keyup, sort of a keylogger effect. Here is my attempt -
php loop form -
<form method="post" id="'.$vid.'" class="note-form">
<textarea id="'.$vid.'" name="quicknote" value="'.$quick_note.'" placeholder="add a quick note" class="quicknote">'.$quick_note.'</textarea>
<input type="hidden" name="tac" value="'.$vid.'"/>
</form>
$vid is the unique id for each form that im passing from the DB.
JS file -
// Capture keyup from textarea to submit form
$('.quicknote').bind('keyup', function() {
var id = this.id;
var formID = "#"+id;
$(formID).delay(200).submit();
});
$(formID).submit(function(e) {
var url = "ready-data/submit-note.php";
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function(data) {
// Do something
}
});
e.preventDefault();
});
I use the same ID for the form and the inputs but the form isnt submitting. I can submit if I use the form class note-form but it submits all forms. I cant make formID a global variable to pass to the ajax function also. What is the correct way to do this?
Your form id and textarea id are same that's why its causing problem . Instead you can use
$(this).closest('form') this will get closest form from textarea then you can submit only that form.
Demo Code :
$('.quicknote').bind('keyup', function() {
var selector = $(this).closest('form') //get closest form
$(selector).delay(200).submit(); //submit that.
});
$("form").submit(function(e) {
console.log("data to send --> " + $(this).serialize())
var url = "ready-data/submit-note.php";
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function(data) {
// Do something
}
});
e.preventDefault();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" class="note-form">
<textarea id="1" name="quicknote" value="somethings..." placeholder="add a quick note" class="quicknote">somethings..</textarea>
<input type="hidden" name="tac" value="1" />
</form>
<form method="post" class="note-form">
<textarea id="2" name="quicknote" value="somethings" placeholder="add a quick note" class="quicknote">somethings...</textarea>
<input type="hidden" name="tac" value="2" />
</form>
In a Tinymce textarea, it forces me to double click submit form. In the first send "var a" is empty, in the second click if you have the data and it is sent correctly. How can it be solved?
<script src="https://cdn.tiny.cloud/1/zgxpx6ymtwpuc7yy5x3wuic7eu7ughi6w7q98msfnxmbcpjp/tinymce/5/tinymce.min.js" referrerpolicy="origin"></script>
<script>
tinymce.init({
selector: '#comment',
});
</script>
<script type="text/javascript">
function FQB() {
var a = document.forms["Formularioqr"]["comment"].value;
if (a == null || a == "") {
alert(a);
return false;
}else{
a = a.replace(/\r?\n/g, '<br />');
$.ajax({
type: "POST",
url: "send-email-manual-envio.php?mesaje=" + a + "&correo=<?php echo $correo;?>" ,
dataType: "json",
success: function() {
document.getElementById("Formularioqr").reset();
document.getElementById("showtextqr1").innerHTML =" Enviado Con exito ";
},
error: function() {
document.getElementById("Formularioqr").reset();
document.getElementById("showtextqr1").innerHTML = " ERROR!!";
}
});
}
}
</script>
<form method="POST" autocomplete="off" id="Formularioqr" name="Formularioqr" onsubmit="return FQB()">
<div class="form-group">
<label for="comment">Mesaje:</label>
<textarea class="form-control" rows="12" id="comment" name="comment"></textarea>
</div>
<p id="showtextqr1"></p>
<input type="submit" value="Enviar">
</form>
I haven't tried it, but i would guess, that '.value' isn't working properly for tinymce textareas.. the tinymce has an dedicated function to get the content. See https://www.tiny.cloud/blog/how-to-get-content-and-set-content-in-tinymce/
I would suggest, trying this way instead this var a = document.forms["Formularioqr"]["comment"].value;
This form has a text input for each day of the week, as well as an "Add Another" button to create more inputs under each day. The submissions go through but only the first value that's entered into the input gets posted to the Spreadsheet's cell.
So for example, if the user has multiple entries entered in for SUNDAY_NOTES, like so:
SUNDAY_NOTES = "Late."
SUNDAY_NOTES = "This thing."
SUNDAY_NOTES = "Something."
... then only "Late" ends up in the spreadsheet's cell with my current code. Ideally, I'd like to have a comma-separated or linebreak-separated string in the cell: ("Late., This thing., Something."). I'm using the following code (which I copied) to post the submissions to a Google Spreadsheet.
<form method="post" id="timesheet" >
<input type="text" name="SUNDAY_NOTES">
<input type="text" name="SUNDAY_NOTES">
// user can click a button to keep adding more SUNDAY_NOTES fields
<input type="text" name="MONDAY_NOTES">
// and so forth
<input type="submit" id="submit" />
</form>
<script>
var $form = $('form#timesheet'),
url = 'https://script.google.com/macros/s/abcd123456789/exec'
$('#submit').on('click', function(e) {
var jqxhr = $.ajax({
url: url,
method: "GET",
dataType: "json",
data: $form.serializeArray()
}).success(
console.log('success')
);
})
</script>
(This question doesn't accurately describe the use-case of my form, I just overly-simplified it for posting purposes)
to have an array of inputs values with same name, add [] after the name like : name="SUNDAY_NOTES[]" ,
so replace <input type="text" name="SUNDAY_NOTES"> with <input type="text" name="SUNDAY_NOTES[]">
then join the array values with a comma with
data : $form.serializeArray().map((e) => { return e.value}).join(',')
$form.serializeArray() will have an array of objects, that's why it's useful to use .map() to retun an array of values to be able to join them.
$(document).ready(function() {
var $form = $('form#timesheet');
$form.submit(function(e) {
e.preventDefault();
var myValues = $form.serializeArray().map((e) => {
return e.value
}).join(',');
console.log(myValues);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" id="timesheet">
<input type="text" name="SUNDAY_NOTES[]">
<input type="text" name="SUNDAY_NOTES[]"> // user can click a button to keep adding more SUNDAY_NOTES fields
<input type="text" name="MONDAY_NOTES[]"> // and so forth
<input type="submit" id="submit" />
</form>
EDIT :
in order to keep the structure as is ( key, value pairs ), create a function group that loops through an array and add the values to the key
function group(arr){
var tempArr = [];
arr.forEach(function(e){
if(!tempArr[e.name]) tempArr[e.name] = e.value
else tempArr[e.name] += ',' + e.value
});
return tempArr;
}
$('#submit').on('click', function(e) {
var jqxhr = $.ajax({
url: url,
method: "GET",
dataType: "json",
data: group($form.serializeArray())
// rest of your code
here's a fiddle : https://jsfiddle.net/cwgL6L0L/29/ ( check the console )
I have an input field through which i am getting the value that user enters, although i am able to display it but instead of displaying it, i wish to store the user entry in a variable and then use it to get data from database. Below is the code that i have so far (#JSFiddle)
<form action="save.php" method="post">
<input type="text" value="" id="test">
<p></p>
<input type="text" value="">
<button type="button">submit</button>
</form>
<script>
$( "input" )
.keyup(function() {
var value = $( this ).val();
$( "p" ).text( value );
})
.keyup();
</script>
E.g: if a user enters 12 in input box and then click enter button, then 12 should get stored in a variable, but the whole form should not get submitted after every value of input field is filled then only the form should get submitted
$idd=12;
and then i wish to run a query as
$sql=" SELECT * from menu where id = '".$idd."' ";
$result = mysqli_query($con, $sql);
if(mysqli_num_rows($result)>0)
{
while($row = mysqli_fetch_assoc($result))
{
/*
*
* code to display data
*
*/
}
}
and the result that i need to display will come from the code running inside while loop
Can anyone please tell how to obtain the result
With this code, you store the result to a variable declared before the keyup event.
<input type="text" value="some text">
<p></p>
<script>
var inputValue;
$( "input" )
.keyup(function() {
inputValue = $(this).val();
})
.keyup();
</script>
Than you could do your AJAX call.
EDIT
Here's the code that only respond to the "enter" keycode
var value;
$('input').on('keyup', function(ev) {
if(ev.keyCode == 13) {
value = $(this).val();
}
});
You can do by two ways
<input type="text" value="some text" id="input_id" name="input_name">
<input type="submit" name="submit">
With jquery/ajax
$('#input_id').on('keyup', function() {
var field_value = $("#input_id").val();
jQuery.ajax({
type: 'post',
url: 'path_to_the_file',
data: { fieldValue: field_value },
success: function(successData) {
//do whatever want on success
}
});
});
Or without jquery/ajax On same page
if(isset($_POST['submit']))
{
$my_value = $_POST['input_name'];
//Execute your query
}
you can use ajax to post value of input box and get the result like this
<form action="save.php" method="post">
<input type="text" value="" id="test">
<p></p>
<input type="text" value="">
<button type="button" id="btnsubmit">submit</button>
</form>
<script>
var value
$("input").keyup(function () {
value = $(this).val();
})
$('#btnSubmit').click(function(){
$.ajax({
type: "POST",
url: "url_of_php_page",
data: {id: value},
success: function (html)
{
$("p").text(html);
}
});
});
</script>
I have the following code in a SharePoint aspx page ( I got an error that said I cannot use form controls... that is why the form tags are not there):
<div id="formBox">
Here is a link : <a href="" id=lnk>nothing here yet</a> <br>
<input type='text' id='userInput' />
<input name="codename" type="radio" value="codeA" /> <label for="x">X</label> <input name="codename" type="radio" value="codeB" /><label for="y">Y</label>
<input type='button' onclick='javascript:changeText2()' value='Change Text'/>
</div>
Here is the function which is supposed to concatenate the information: It works... kind of.. parts of it.
It will add the selected button to the url, and also the input text. However, it is firing before the input is filled out, and then works once you type in the box again.
I tired to add in if statement, to stop the code if the box was not filled out but it didn't work. Here is what I have...
function changeText2(){
var userInput = document.getElementById('userInput').value;
$('#formBox input[type="text"]').on('change', function() {
var linktest = 'site/info.aspx?' + $('input[name="codename"]:checked', '#formBox').val() + '=' + userInput;
alert(linktest);
});
var lnk = document.getElementById('lnk');
lnk.href = "http://www.google.com?q=" + userInput;
lnk.innerHTML = lnk.href;
}
I tried to check the input box like this, but it didn't work:
if( $('#formBox input[type="text"]').val== "") {
alert('no info');
}
It should be val() in jquery, not val. However, it will be value in javascript, not val. Simply just use unique id, try something like this,
For Jquery:
if( $('#userInput').val() === "") {
alert('no info');
}
For javascript:
if(document.getElementById("userInput").value === "") {
alert('no info');
}