submit a form on 'enter' key press [duplicate] - php

This question already has answers here:
jquery (or pure js) simulate enter key pressed for testing
(2 answers)
Submitting a form by pressing enter without a submit button
(20 answers)
Closed 7 years ago.
I want to submit the form value in 'enter' key.I have a button search now to submit the value value.but I want to do it without search button on enter key press.
html
<input class="stxt" type="text" name="searchtxt"><a style="padding-right:2ex;"></a>
<button name="search" class="search">Search</button></p>
php
if(isset($_REQUEST['search']))
{
$search=$_REQUEST['searchtxt'];
some code here
}

Try the below code it will work.. I have coded without button only.
<?php
if(isset($_POST['search']))
{
echo $search = $_POST['search'];
}
?>
<html>
<head>
<script>
document.onkeydown=function(evt){
var keyCode = evt ? (evt.which ? evt.which : evt.keyCode) : event.keyCode;
if(keyCode == 13)
{
//your function call here
document.test.submit();
}
}
</script>
</head>
<body>
<form name="test" action="#" method="POST">
<input type="text" name="search" />
</form>
</body>
</html>

If I understand you correctly you want to trigger php code on every key press in which case good solution will be using AJAX.
$( "#target" ).keypress(function(e) {
$.ajax({
url: "logic.php",
type: post,
data: $('form').serialize(),
success: function( data ) {
//Process data received from server.
}
});
});
On each key press all form data will be serialized and send over to server where you can perform your logic.

The button should be submitting on Enter, if it's not, there's something in the HTML that you have not provided. You have tagged the question with JQuery but have not provided any code, so I can only assume that you are submitting the form through only PHP.
Take a look at the button documentation. There are two paragraphs there that are relevant to your situation.
form HTML5
The form element that the button is associated with (its form owner). The value of the attribute must be the id attribute of a
element in the same document. If this attribute is not
specified, the element must be a descendant of a form
element. This attribute enables you to place elements
anywhere within a document, not just as descendants of their
elements.
This means that for the button to submit the form, it must be inside the form tags. If it is not, you need to specify the form id like this.
<button form="form_id">
The second relevant piece of information.
type
The type of the button. Possible values are:
submit: The button submits the form data to the server. This is the default if the attribute is not specified, or if the attribute is
dynamically changed to an empty or invalid value.
reset: The button resets all the controls to their initial values.
button: The button has no default behavior. It can have client-side scripts associated with the element's events, which are triggered when
the events occur.
Since type defaults to submit, it means that the form will submit with the Enter key.

Related

Recaptcha invisible never sends form name in post [duplicate]

Ok, this is less of a question than it is just for my information (because I can think of about 4 different work arounds that will make it work. But I have a form (nothing too special) but the submit button has a specific value associated with it.
<input type='submit' name='submitDocUpdate' value='Save'/>
And when the form gets submitted I check for that name.
if(isset($_POST['submitDocUpdate'])){ //do stuff
However, there is one time when I'm trying to submit the form via Javascript, rather than the submit button.
document.getElementById("myForm").submit();
Which is working fine, except 1 problem. When I look at the $_POST values that are submitted via the javascript method, it is not including the submitDocUpdate. I get all the other values of the form, but not the submit button value.
Like I said, I can think of a few ways to work around it (using a hidden variable, check isset on another form variable, etc) but I'm just wondering if this is the correct behavior of submit() because it seems less-intuitive to me. Thanks in advance.
Yes, that is the correct behavior of HTMLFormElement.submit()
The reason your submit button value isn't sent is because HTML forms are designed so that they send the value of the submit button that was clicked (or otherwise activated). This allows for multiple submit buttons per form, such as a scenario where you'd want both "Preview" and a "Save" action.
Since you are programmatically submitting the form, there is no explicit user action on an individual submit button so nothing is sent.
Using a version of jQuery 1.0 or greater:
$('input[type="submit"]').click();
I actually was working through the same problem when I stumbled upon this post. click() without any arguments fires a click event on whatever elements you select: http://api.jquery.com/click/
Why not use the following instead?
<input type="hidden" name="submitDocUpdate" value="Save" />
Understanding the behavior is good, but here's an answer with some code that solved my problem in jquery and php, that others could adapt. In reality this is stripped out of a more complex system that shows a bootstrap modal confirm when clicking the delete button.
TL;DR Have an input dressed up like a button. Upon click change it to a hidden input.
html
<input
id="delete"
name="delete"
type="button"
class="btn btn-danger"
data-confirm="Are you sure you want to delete?"
value="Delete"></input>
jquery
$('#delete').click(function(ev) {
button.attr('type', 'hidden');
$('#form1').submit();
return false;
});
php
if(isset($_POST["delete"])){
$result = $foo->Delete();
}
The submit button value is submitted when the user clicks the button. Calling form.submit() is not clicking the button. You may have multiple submit buttons, and the form.submit() function has no way of knowing which one you want to send to the server.
Here is another solution, with swal confirmation. I use data-* attribute to control form should be send after button click:
<button type="submit" id="someActionBtn" name="formAction" data-confirmed="false" value="formActionValue">Some label</button>
$("#someActionBtn").on('click', function(e){
if($("#someActionBtn").data("confirmed") == false){
e.preventDefault();
swal({
title: "Some title",
html: "Wanna do this?",
type: "info",
showCancelButton: true
}).then(function (isConfirm) {
if (isConfirm.value) {
$("#someActionBtn").data("confirmed", true);
$("#someActionBtn").click();
}
});
}
});
i know this question is old but i think i have something to add... i went through the same problem and i think i found a simple, light and fast solution that i want to share with you
<form onsubmit='realSubmit(this);return false;'>
<input name='newName'/>
<button value='newFile'/>
<button value='newDir'/>
</form>
<script>
function getResponse(msg){
alert(msg);
}
function realSubmit(myForm){
var data = new FormData(myForm);
data.append('fsCmd', document.activeElement.value);
var xhr = new XMLHttpRequest();
xhr.onload=function(){getResponse(this.responseText);};
xhr.open('POST', 'create.php');
// maybe send() detects urlencoded strings and setRequestHeader() could be omitted
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send(new URLSearchParams(data));
// will send some post like "newName=myFile&fsCmd=newFile"
}
</script>
summarizing...
the functions in onsubmit form event are triggered before the actual form submission, so if your function submits the form early, then next you must return false to avoid the form be submitted again when back
in a form, you can have many <input> or <button> of type="submit" with different name/value pairs (even same name)... which is used to submit the form (i.e. clicked) is which will be included in submission
as forms submitted throught AJAX are actually sent after a function and not after clicking a submit button directly, they are not included in the form because i think if you have many buttons the form doesn't know which to include, and including a not pressed button doesn't make sense... so for ajax you have to include clicked submit button another way
with post method, send() can take a body as urlencoded string, key/value array, FormData or other "BodyInit" instance object, you can copy the actual form data with new FormData(myForm)
FormData objects are manipulable, i used this to include the "submit" button used to send the form (i.e. the last focused element)
send() encodes FormData objects as "multipart/form-data" (chunked), there was nothing i could do to convert to urlencode format... the only way i found without write a function to iterate formdata and fill a string, is to convert again to URLSearchParams with new URLSearchParams(myFormData), they are also "BodyInit" objects but return encoded as "application/x-www-form-urlencoded"
references:
https://developer.mozilla.org/en-US/docs/Web/API/Document/activeElement
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send
https://developer.mozilla.org/en-US/docs/Web/API/FormData
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/URLSearchParams
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/requestSubmit#usage_notes (proves that form.submit() does not emulate a submit button click)
Although the acepted answer is technicaly right. There is a way to carry the value you'd like to assign. In fact when the from is submited to the server the value of the submit button is associated to the name you gave the submit button. That's how Marcin trick is working and there is multiple way you can achive that depending what you use. Ex. in jQuery you could pass
data: {
submitDocUpdate = "MyValue"
}
in MVC I would use:
#using (Html.BeginForm("ExternalLogin", "Account", new { submitDocUpdate = "MyValue" }))
This is actually how I complied with steam requirement of using thier own image as login link using oAuth:
#using (Html.BeginForm("ExternalLogin", "Account", new { provider = "Steam" }, FormMethod.Post, new { id = "steamLogin" }))
{
<a id="loginLink" class="steam-login-button" href="javascript:document.getElementById('steamLogin').submit()"><img alt="Sign in through Steam" src="https://steamcommunity-a.akamaihd.net/public/images/signinthroughsteam/sits_01.png"/></a>
}
Here is an idea that works fine in all browsers without any external library.
HTML Code
<form id="form1" method="post" >
...........Form elements...............
<input type='button' value='Save' onclick="manualSubmission('form1', 'name_of_button', 'value_of_button')" />
</form>
Java Script
Put this code just before closing of body tag
<script type="text/javascript">
function manualSubmission(f1, n1, v1){
var form_f = document.getElementById(f1);
var fld_n = document.createElement("input");
fld_n.setAttribute("type", "hidden");
fld_n.setAttribute("name", n1);
fld_n.setAttribute("value", v1);
form_f.appendChild(fld_n);
form_f.submit();
}
</script>
PHP Code
<?php if(isset($_POST['name_of_button'])){
// Do what you want to do.
}
?>
Note: Please do not name the button "submit" as it may cause browser incompatibility.

Collect form data for ajax submission

I have a database which has over 50 items in it which need to be checked and possibly edited. I have a web page which pulls the data from the database using php and displays it as values in a webform. Then I have a series of submit buttons at the bottom of the page, depending on what the user wants to do. Each button uses an onclick method to call a javascript function.
In the case where some changes need to be made, the user will make edits directly in the webform. For example, in a textarea, the value of the textarea will display the current content of the database item. The user can then edit the content. Clicking a "Save Changes" button calls an ajax function to send the data back to the server using a POST request.
The problem I am having, probably simple to someone who knows how, is how to collect all the updated data from the different form components to send to the server in the variable "FormData" below (presumably an array). Is there a way to do this all at once, or do I have to step through every one of the form elements and add them to the array one by one? "msg" refers to a <div id="msg"></div> where a message from the server page will be displayed.
My ajax function so far is:
function callsave() {
var xmlHttp, FormData;
xmlHttp = new XMLHttpRequest;
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
document.getElementById("msg").innerHTML = xmlHttp.responseText;
}
}
xmlHttp.open("POST", "savechanges.php", true);
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttp.send(FormData);
}
The submit button at the end of the form is:
<input type="button" value="Save Changes" id="save" onClick="callsave();">
Many thanks for pointing me in the right direction. BTW, this is my first ajax coding.
If you're using jQuery, it can be easy by FormData=$('#formId').serialize(),
serialize() will return all form data in query string style, like "name=AAA&action=BBB"
I'm not sure what your html is like but you can assign a unique id to each form button (this can be done in php by assigning the primary key of your the row in the db) and submit button so that you can get the form you need to submit from the id of the submit button.
For example, if your form html is like this :
<form id="data-<?php //put the primary key of the row here ?>">
<!-- rest of your form attributes here -->
<input type="Submit" id="submit" class="submit" onClick="callSave(<?php //same primary key as your form?>)" />
</form>
As for ajax, I would suggest that you use jQuery's $.ajax function as its much easier to code than in native js.
you would do something like in your callsave function
function callSave(formId)
{
$.ajax({
type : 'POST',
url : //your post url,
data : $("#data" + formId).serialize(),
success : function(data){
$("#msg").text(data);
}
});
}
Setting up jQuery is a breeze. Follow this link
"...how to collect all the updated data from the different form components..."
Without knowing what's inside your full form and your handler (savechanges.php),
you could pull each POST value from your form by using this snippet in savechanges.php:
foreach ($_POST as $key=>$value) {
$post_values=$key.": " . $value . "\n";
}

Submit JQuery array alongside PHP form data to PHP script

I'm dabbling in JQuery, and have run up against an issue I'm not quite able yet to figure out. Here is the context:
I have a HTML form, utilising MySQL & PHP, used to edit a CMS post. This post would have a list of attachments (eg. images for a gallery, or downloadable files). Using JQuery, the user can click on these list item elements and edit the details of each attachment in a revealed div (eg. delete image, add capton, etc).
Currently when the user opts to delete an attachment, I simply fade its opacity and provide a new option to the user to 'undo' the delete. Upon submission of the complete parent form (the CMS post), I want to gather all the attachments still marked for deletion, and submit their GUID's to the PHP script that is doing all the rest of the post updating for me.
Option A:
Is it possible to submit a JQuery array to a PHP script alongside the data being sent naturally to the action script by the form inputs?
Option B:
Is it possible to fill / empty a (hidden) form input array dynamically with JQuery, which could then be submitted naturally to the action script with everything else?
I am currently at the stage where I am filling a Javascript array with the necessary GUIDs, but now don't know what to do with it.
//populate deleted attachments array
$(document).ready(function() {
$('#post-editor').submit(function() {
var arrDeleted = [];
$('.deleted-att').each(function(){
arrDeleted.push({guid: $(this).attr("data-guid")});
});
//do something with array
});
});
JSON.stringify the arrDeleted and put them in a hidden field in the form, that will be submitted.
$('#post-editor').submit(function() {
var arrDeleted = [];
$('.deleted-att').each(function(){
arrDeleted.push({guid: $(this).attr("data-guid")});
});
$('#post-hidden').val(JSON.stringify(arrDeleted));
});
Somewhere in your html:
<form id="post-editor">
<input type="hidden" id="post-hidden" name="post-hidden" />
<!-- ... other fields ... -->
</form>
Then json_decode($_POST['post-hidden']) on the server to get the array.
create a hidden field in your form..put the arrDeleted value in your input through jquery
and post the form..use json_decode() to get the posted value...
<input type="hidden" id="hidden"/>
JQUERY
$(document).ready(function() {
$('#post-editor').submit(function() {
var arrDeleted = [];
$('.deleted-att').each(function(){
arrDeleted.push({guid: $(this).attr("data-guid")});
});
$('#hidden').val(JSON.stringify(arrDeleted));
});
});
The easiest to do what you want would be to add a hidden input field to your HTML form
Then in jQuery do something like this
$('form').submit(function() {
$('#hidden_id_field').val( arrDeleted.join(',') );
});
arrDeleted in this case being your array you've already setup. It would sent a comma separated list then in your PHP you split up the values and act as you want.
Usually I just do AJAX and send JSON to my app. But the above approach will work if you really want to go about it like that. And it has the advantage of not actually deleting anything on the server until you submit the form.
You may be looking to do this with a traditional form submit and refresh, but if you're willing to submit the request asynchronously, you can use jQuery to submit the form and serialize the array of deleted items:
var form = $('#post-editor');
form.submit(function() {
var arrDeleted = [];
$('.deleted-att').each(function(){
arrDeleted.push({ // The format $.serializeArray produces.
name: "deleted",
value: $(this).attr("data-guid")
});
});
var formData = form.serializeArray();
// Add values to existing form data
formData = formData.concat(arrDeleted);
$.ajax({
url: form.attr('action'),
data: formData
// Other ajax options
});
});
On the PHP side, referring to $_REQUEST['deleted'] will return an array of GUIDs.

PHP - Display message directly after selecting a Radio Button

I am using a PHP script, but say I had two radio buttons, right?
How could I actually execute code, such as (main intention | display a messagebox) upon selection of one or the other?
Say I had a radio button named RadioButton1, Once checked/selected, a message box would appear saying RadioButton1 Selected?
Is this possible through PHP alone? Or do I need to integrate an html page which posts to the PHP page?
Use Javascript for client side interaction like that. The code below listens for the onchange event and shows an alert().
jsFiddle Demo
<input type="radio" name="myradio" value="RadioButton1" />
<input type="radio" name="myradio" value="RadioButton2" />
<input type="radio" name="myradio" value="RadioButton3" />
<script>
​window.onload = function()
{
var radios = document.getElementsByName("myradio");
for(var i=0; i<radios.length; i++)
{
radios[i].onchange = function()
{
if(this.checked)
{
alert(this.value + " selected");
}
}
}
}​
</script>
The first 3 lines are the radio buttons HTML. After that we have the <script> tag which denotes Javascript code. The Javascript is adding some code to the onload event, which simply means: execute this code when the page is loaded. Next we get all of the radio button elements into an array called radios - for that we use getElementsByName() passing the radio button group name which is myradio. Next we loop through each radio button in the array and assign an onchange handler, which means: execute this code when each radio button is changed. Within that, we check if the radio button is checked and if it is, we show the alert, showing the radio button's value which will be RadioButton1, RadioButton2, RadioButton3.
Not possible with just php! Try using Jquery as the easiest was to do this
$(document.body).on('click', '#radio-btn', function(){
$.get( 'file1.php' , function (data) {
//whatever you want to do after fetching the data from a php file
});
});
Selecting a form element is done in the client's browser, while PHP is a server-side language. It is absolutely unaware of what the user clicks until some data is actually sent back to the server, e.g., via a POST request upon submitting a form.
So no, PHP isn't capable of achieving what you are after.
There's an easy way though. JavaScript is executed on the client side, so you can easily attach an event listener to your radio buttons and display a message box if needed.
Using php alone its not possible, but you can do it using Jquery ajax. To do this make a ajax request on click of radio button, and populate the message box with the data comming in response.
Let me explain with an example:
<div id='msg_box'>Message will be displayed here</div>
on click of radio button call a function of javascript say ajaxCallForMessage()
<script type="text/javascript">
function ajaxCallForMessage(){
$.ajax({
url: "Url of the page which contain message/?btn_name=xy",
mthod: "GET"
}).done(function ( data ) {
$('#msg_box').append(data);
});
}
</script>
make sure you included jquery.
If I understood your question properly, I would suggest to do it simply via Javascript.
Once the user selects the RadioButton1, the "click" event is triggered in the page. I guess you know that you can capture it adding the onClick attribute like:
<input type="radio" name="Radio1" value="RadioOption1" onclick="showMessage()"> Option 1
Then all you need to do is to create a Javascript funcion showMessage that adds some html to the page (maybe a paragraph) with the message you want to display. You can do this in Javascript easily, using for example the jQuery append or html functions.
function showMessage() {
// Example displaying an alert
alert("Message to be displayed here")
}
I would only introduce PHP here if there is really a need to obtain information from the server. In this case what you should be doing is probably a GET / POST from the page to the server (e.g. using AJAX via jQuery get or post method). You will call a PHP script that returns some information that then will be displayed in the page through Javascript.
But if all you need is to display a simple message like "Option 1 selected" you should do it in Javascript without server interaction.
I hope this helps.
Regards,
Romén

jQuery Multiple Forms Submit

I have 4 forms on a page. I know that forms cannot be nested.
<form id="form1"></form>
<form id="form2"></form>
<form id="form3"></form>
<form id="form4"></form>
presented in that order.
Form 1 and Form 4 post to same php page for processing.
Form 1 have 1 input field
Form 4 have multiple fields, checkboxes and selects.
What is the best approach for both form 1 or form 4 sending the combined fields of both forms?
I've tried jQuery, works great for text input and checkbox, but can't get it to work with Select.
Tried combining form 1 and form 4 and using css to repositioning form 1, but can't get the layout right.
Is there something simpler to do this?
It's not possible. You can either use serialize() or serializeArray() method for getting forms' data and post them to the server using Ajax:
Encode a set of form elements as a string for submission.
$('#send').click(function() {
var firstFormData = $('form:eq(0)').serializeArray();
var fourthFormData = $('form:eq(3)').serializeArray();
$.ajax({
url : '...',
type : 'post',
data : firstFormData.concat(fourthFormData)
}).done(function() {
// ...
});
});
Okay, I could not get .serialize() to work with checkbox array from form4 e.g.
<input type="checkbox" id="model[]">
I tried to grab checked values but could not get them to serialize together with other input :
var vals = []
$('input:checkbox[name="model[]"]').each(function() {
if (this.checked) {
vals.push(this.value);
}
});
So I went back and did the simpler thing :
Removed form1, move the text input and the submit button within a <div id="searchbox" style="position:abosulte;top:-100px;left:0px;">My original form1</div> inside form4.
Put a placeholder <div id="placeholder" style="position:relative;"></div> above form2 and 3 where form1 used to be.
Place a javascript above :
$(document).ready(function(){
$("#searchbox")
.appendTo("#placeholder");
});
to move the text input and submit button to position them absolute and relative to the placeholder div.
This way I reduced them to 1 form (which is what its intention anyways), does not rely on javascript to manipulate any data, and does not require me to do the tandem serialization on both forms.

Categories