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>
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 a page where almost every click is handled by delegate().
http://itsneworleans.com/shows/midnight-menu-plus-1/blogs/after-midnight?preview=1
I set up jQuery validate like so
$(document).ready(function(){
$(".commentform form").validate({
rules: {
antispam: { equalToParam: "INO" }
}
});
jQuery.validator.addMethod("equalToParam", function(value, element, param) {
return value == param;
},
"Anti-spam field does not match requested value.");
});
if I check in console with
$.validator.methods['equalToParam']
I get back
function (value, element, param) { return value == param; }
so that looks good.
The validation works on the form submission BUT the equalToParam method has no effect. Only the "required" events occur for it.
The field HTML is
<input name="antispam" type="text" class="required" id="antispam" size="5" />
Where am I going wrong?
EDIT Here is whole form code (generated from PHP script and added to page via AJAX):
<? if ($post = (int) $_POST['pID']) { ?>
<div class="commentform">
<form>
<div class="commenttext">Comment:<br>
<textarea name="comment" class="required"></textarea>
</div>
<div class="commenttext">Your name:<br>
<input type="text" name="name" class="required">
</div>
<div class="commenttext">Your email (will not be publically visible):<br>
<input type="text" name="email" class="required email">
</div>
<div class="commenttext">Type the letters INO here to help us beat spam!<br>
<input name="antispam" type="text" class="required" id="antispam" size="5" />
</div>
<div class="commenttext">
<input type="button" name="submitcomment" class="submitcomment" value="Submit Comment">
<input type="hidden" name="post" value="<?=$post?>">
<? if ($parentComment = (int) $_POST['cID']) { ?>
<input type="hidden" name="parent" value="<?=$parentComment?>">
<? } ?>
</div>
</form>
</div>
<? } ?>
EDIT AGAIN And here's the click delegation code...
$("body").delegate(".submitcomment", "click", function(e) {
e.preventDefault();
var theform = $(this).closest("form");
console.log('Posting comment');
if ($(".commentform form").valid()) {
$.ajax({
type: "POST",
url: "/addComment.php",
data: theform.serialize()
}).done(function(html) {
if (html == 'OK') {
$(theform).html("<div class='commentposted'>Your comment has been received. Thank you. A moderator will review it for public viewing.</div>");
} else {
alert(html);
}
});
}
});
EDIT Here is the code which populates the form into the space where the Reply to Post link was:
$("body").delegate(".getcommentform", "click", function(e) {
e.preventDefault();
var pIDval = $(this).attr("data-pid");
var cIDval = $(this).attr("data-cid");
var thebox = $(this).closest("div.commentformcontainer");
console.log('Getting comment form');
$.ajax({
type: "POST",
url: "/commentForm.php",
data: { pID : pIDval, cID : cIDval }
}).done(function(html) {
thebox.html(html);
});
});
When you need to apply the .validate() method to more than one form, you must wrap it within a jQuery .each().
$(".commentform form").each(function() {
$(this).validate({
rules: {
antispam: {
equalToParam: "INO"
}
}
});
});
EDIT:
You need to initialize the plugin AFTER the form is inserted into the page. Assuming this code properly inserts the form... put your .validate() call as the last item inside...
$("body").delegate(".getcommentform", "click", function(e) {
e.preventDefault();
var pIDval = $(this).attr("data-pid");
var cIDval = $(this).attr("data-cid");
var thebox = $(this).closest("div.commentformcontainer");
console.log('Getting comment form');
$.ajax({
type: "POST",
url: "/commentForm.php",
data: { pID : pIDval, cID : cIDval }
}).done(function(html) {
thebox.html(html);
});
$(".commentform form").validate({ // <- initialize plugin AFTER form is inserted
// your rules & options
});
});
EDIT 2:
Include the equalToParam function someplace on your page within a DOM ready event handler.
I am stuck in passing the multiple value through AJAX call in Codeigniter.
My View is :
<script>
$( document ).ready(function() {
var current_id = 0;
$('#btn').click(function(){
nextElement($('#Outer_00'));
})
function nextElement(element){
var newElement = element.clone()
.find("input:text").val("").end();
var id = current_id+1;
current_id = id;
if(id <10)id = "0"+id;
$('input', newElement).attr("id", id );
newElement.appendTo($("#elements"));
if($('#elements').find('div').length=='5')
{
$('#btn').prop('disabled',true);
}
}
$('#exercises').on('click', '.remove', function() {
if($('#elements').find('div').length<'6')
{
$('#btn').prop('disabled',false);
}
if($('#elements').find('div').length=='1')
{
$('.remove').addAttr("disabled",true);
}
$(this).parent().remove();
return false; //prevent form submission
});
});
</script>
/******************************
<script>
var base_url = '<?=base_url()?>';
$(document).ready(function()
{
$('#Edit').click(function()
{
$('#Name').removeAttr("disabled");
});
$('#Add').click(function()
{
$('#Name').attr("disabled","disabled");
$('#Phone').attr("disabled","disabled");
$('#email').attr("disabled","disabled");
$('#CurrentlyLocated').attr("disabled","disabled");
$('#KeySkills').attr("disabled","disabled");
//var queryString = $('#form1').serialize();
$.ajax({
url: '<?php echo site_url('PutArtistProfile_c/formDataSubmit');?>',
type : 'POST', //the way you want to send datas to your URL
data: {Name:$("#Name").val(), Phone: $("#Phone").val(), email: $("#email").val(),
birthday: $("#birthday").val(), bornIn: $("#bornIn").val(),
CurrentlyLocated: $("#CurrentlyLocated").val(), KeySkills: $("#KeySkills").val(),
Audio1: $("#00").val(), Audio2: $("#01").val(), Audio3: $("#02").val(),Audio4: $("#03").val(), Audio5: $("#04").val(),
},
success : function(data)
{ //probably this request will return anything, it'll be put in var "data"
$('body').html(data);
}
});
});
});
</script>
<p>
<div id="elements">
<div id="Outer_00">
Audio: <input type="text" id="00" value="">
<input type="button" class="remove" value="x"></button>
</div>
</div>
<div id="count"></div>
<input type="button" id="btn" value="Add Audio"></button>
</p>
My Controller is :
public function formDataSubmit()
{
$queryAudio1 = $this->input->post('Audio1');
$queryAudio2 = $this->input->post('Audio2');
$queryAudio3 = $this->input->post('Audio3');
$queryAudio4 = $this->input->post('Audio4');
$queryAudio5 = $this->input->post('Audio5');
}
How can I pass Multiple Values of text box? The above code is passing the values to the controller. But on clicking 'x' Button the value of text box is been getting deleted, but the id of the textbox is getting Incremented, Thus I am not able to pass the further values of textbox to controller via AJAX. Please help me over here.
instead of doing :
data: {Name:$("#Name").val(), Phone: $("#Phone").val(), email: $("#email").val(),
birthday: $("#birthday").val(), bornIn: $("#bornIn").val(),
CurrentlyLocated: $("#CurrentlyLocated").val(), KeySkills: $("#KeySkills").val(),
Audio1: $("#00").val(), Audio2: $("#01").val(), Audio3: $("#02").val(),Audio4: $("#03").val(), Audio5: $("#04").val(),
},
You can do as
data:$("#Form_id").serialize(); // all form data will be passed to controller as Post data.
If you have a remove button then getting the value by id may result in a js error, Why don't you make use of html element array:
<div id="elements">
<div id="Outer_00">
Audio: <input type="text" name="audio[]" value="">
<input type="button" class="remove" value="x"></button>
</div>
</div>
IT is very simple:
Consider you want to pass: user name, surname, and country. These are
three input boxes then:
using Jquery do so:
Javascript side
$.post("url",{name:name,surname:surname,country:country},
function(data){
console.log("Query success");
});
In your Model or controller where your Query will be handled
$name=$this->input->post("name");
$surname=$this->input->post("surname");
$country=$this->input->post("country");
in your case just pass parameters that YOU need. I use codignitter and
this method works fine!