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.
Related
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.
I'm trying to figure out a way to load 1 single tab(tabs by jQuery) without reloading all the others.
The issue is that I have a submit button and a dropdown that will create a new form, and when on this new form 'OK' or 'CANCEL' is clicked, it has to get the original form back.
The code to load a part of the page that I found is this:
$("#tab-X").load("manageTab.php #tab-X");
But now I would like to know how to use this in combination with the $_POST variable and the submit-button
Clarification:
I have a .php(manageTab.php) which contains the several tabs and their contents
I have in each of these tabs a dropdown containing database-stored information(code for these dropdowns is stored in other pages)
for each of these dropdowns, there exists a submit button to get aditional information out of the DB based on the selection, and put these informations in a new form for editing
this new form would ideally be able to be submitted without reloading everything except the owning tab.
Greetings
<script>
$(document).ready(function() {
$("#form1").submit(function(){
event.preventDefault();
$.post('data.php',{data : 'dummy text'},function(result){
$("#tab-X").html(result);
});
});
});
</script>
<form id="form1">
<input id="btn" type="submit">
</form>
I am not totally understand your question, but as per my understanding you can't load one tab with form submit. Its normally load whole page.
What you can do is, use ajax form submit and load the html content as per the given sample code.
$.ajax({
url: url, // action url
type:'POST', // method
data: {data:data}, // data you need to post
success: function(data) {
$("#tab_content_area").html(data); // load the response data
}
});
You can pass the html content from the php function (just need to echo the content).
AJAX is what you are looking for.
jQuery Ajax POST example with PHP
Also find more examples about ajax on google.
Example: Let me assume you have a select menu to be loaded in the tab.
You will need to send a request to your .php file using jquery, and your php file should echo your select menu.
In your jQuery,
<script>
$.post(url, { variable1:variable1, variable2:variable2 }, function(data){
$("#tab-X").html(data);
//data is whatever php file returned.
});
});
$("#form_id").submit(function(){
return false;
});
</script>
I mean whatever your options are, you will need to do the following in your .php file,
Echo that html code in your PHP script.
echo "<select name='".$selector."'>
<option value='".$option1."'>Option1</option>
<option value='".$option2."'>Option2</option>
<option value='".$option3."'>Option3</option>
</select>";
This would be returned to jQuery, which you may then append wherever you want.
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.
Working from the ground up on a Joomla Component re-config. I'm trying to incorporate an AJAX search function in my component. So far, I have this:
$(document).ready(function() {
$('form').submit(function() {
var results = $('form').serialize();
var url = 'index.php?option=com_mls&task=ListData&format=raw&' + results;
$('#test').html(url);
});
});
This just need to dump the values of the the form elements into a div. right now, it will display the text string, but not the results var.
You are using $('form').serailize() so if your form input elements don't have any name attributes attached to them - which serialize will turn that into the key.. Then you won't get anything when you serialize the form.
Also since you are inside the form's submit function.. it would probably be better to use $(this).serialize() - that way if you ever have multiple forms on one page - it will know which form is getting submitted and serialize the correct form.
I'm trying to send a lot of data from a form using the $.post method in jQuery. I've used the serialize() function first to make all the form data into one long string which I will then explode serverside.
The weird thing is when I try and send it using $.post it appends the result of the serialize() to the URL as if I was sending it using GET.
Anyone have any ideas why this is happening?
Here's the jquery:
$("#addShowFormSubmit").click(function(){
var perfTimes = $("#addShowForm").serialize();
$.post("includes/add_show.php", {name: $("#showTitle").val(), results: perfTimes }, function(data) {
$("#addShowSuccess").empty().slideDown("slow").append(data);
});
});
here's the php:
$show = $_POST['name'];
$results = $_POST['results'];
$perfs = explode("&", $results);
foreach($perfs as $perf) {
$perf_key_values = explode("=", $perf);
$key = urldecode($perf_key_values[0]);
$values = urldecode($perf_key_values[1]);
}
echo $key, $values;
If you are using a <button> element to activate the serialize and ajax, and if that <button> element is within the form element, the button automatically acts as a form submission, no matter what other .click assignment you give it with jQuery.
type='submit'
<button></button> and <button type='submit'></button> are the same thing. They will submit a form if placed within the <form> element.
type='button'
<button type='button'></button> is different. It is just a normal button and will not submit the form (unless you purposely make it submit the form via JavaScript).
And in the case where a form element has no action attribute specified, this submission simply sends the data back onto the same page. So you will end up seeing a page refresh, along with the serialized data appearing in the URL as if you used GET in your ajax.
Possible solutions
1 - Make the <button> type button. As explained above, this will prevent the button from submitting the form.
Before:
<form id='myForm'>
<!--Some inputs, selects, textareas, etc here-->
<button id='mySubmitButton'>Submit</button>
</form>
After:
<form id='myForm'>
<!--Some inputs, selects, textareas, etc here-->
<button type='button' id='mySubmitButton'>Submit</button>
</form>
2 - Move the <button> element outside the <form> element. This will prevent the button from submitting the form.
Before:
<form id='myForm'>
<!--Some inputs, selects, textareas, etc here-->
<button id='mySubmitButton'>Submit</button>
</form>
After:
<form id='myForm'>
<!--Some inputs, selects, textareas, etc here-->
</form>
<button id='mySubmitButton'>Submit</button>
3 - Add in the preventDefault() into the button click handler to prevent the form from being submitted (it's default action):
$("#addShowFormSubmit").click(function(event){
event.preventDefault();
var perfTimes = $("#addShowForm").serialize();
$.post("includes/add_show.php", {name: $("#showTitle").val(), results: perfTimes }, function(data) {
$("#addShowSuccess").empty().slideDown("slow").append(data);
});
});
Obviously without seeing all your code, I have no idea if this is the case for your issue, but the only reason I have ever seen behavior you are describing is because the submit button was a <button> without a type specified.
try using serializeArray() instead of serialize(). serialize() will produce an url-encoded query string, whereas serializeArray() produces a JSON data structure.
What leads you to believe that the data is appended to the URL?
Anyway, wouldn't it make more sense to pass the form values in the form data itself? It will allow you to skip the "explode" step:
$("#addShowFormSubmit")
.click(function() {
var perfTimes = $("#addShowForm").serialize();
$.post("includes/add_show.php",
$.param({name: $("#showTitle").val()}) + "&" + perfTimes,
function(data) {...});
});
So this is probably a bit obtuse, but I made a function to help me do this very thing since I got tired of making a bunch of fixes every time. serializeArray is kind of annoying because it provides a collection of objects, when all I wanted to have PhP reconstruct was an associative array. The function below will go through the serialized array and will build a new object with the appropriate properties only when a value exists.
Firstly, the function (it takes the ID of the form in question):
function wrapFormValues(form) {
form = "#" + form.attr("id") + " :input";
form = $(form).serializeArray();
var dataArray = new Object();
for( index in form)
{
if(form[index].value) {
dataArray[form[index].name] = form[index].value;
}
}
return dataArray;
}
When constructing my posts I also usually use an object since I usually tag on two or three other values before the form data and I think it looks cleaner than to define it inline, so the final step looks like this:
var payload = new Object();
//stringify requires json2.js from http://www.json.org/js.html
payload.data = JSON.stringify(data);
$.post("page.php", payload,
function(reply) {
//deal with reply.
});
Server-side all you have to do is $payload = json_decode($_POST['data'], true) and you have yourself an associative array where the keys are the names of your form fields.
Full disclaimer though, multiple-selects probably won't work here, you would probably only get whichever value was last on the list. This is also created very specifically to suit one of my projects, so you may want to tweak it to suit you. For instance, I use json for all of my replies from the server.
Try this syntax. I use this to serialize a form and POST via ajax call to WCF service. Also, you can send this back a single JSON object instead of building the object the way you are. Try this:
var serializedForm = serializedForm = $("#addShowForm").serializeArray();
$.post("includes/add_show.php",
{
"myObjectName": ("#showTitle").val(), results: perfTimes
}, function(data)
{
$("#addShowSuccess").empty()
.slideDown("slow")
.append(JSON.stringify(serializedForm));
});
On the php side, you may want to look into parse_str. It will parse that url string into variables, or into an array if you utilize the 2nd optional parameter.
One more possible reason for this issue: If you have a form without any sort of submission action assigned to it, whenever you press the "ENTER" key while filling out the form, the form will be submitted to the current URL, so you will see the serialized data appear in the URL as if you were using a GET ajax transaction. A simple solution to this problem, just prevent ENTER from submitting the form when its pressed:
//Prevent Form Submission when Pressing Enter
$("form").bind("keypress", function(e) {
if (e.keyCode == 13)
return false;
});