jQuery: How to submit an array in a form - javascript

I have the following form. Each time the users clicks add_accommodation I want to add to an array that I will return to the end point (http://server/end/point).
<form action="http://localhost:3000/a/b/c" method="post">
<div>
<input type="hidden" id="Accommodation" name="accommodation"><div>
</div>
</form>
<div id="accommodation_component">
<div>
<label for="AccommodationType">Type:</label>
<input type="number" step="1" id="accommodationType" name="accommodation_type" value="0">
</div>
<div>
<button type="button" id="add_accommodation">Add Accommodation</button>
</div>
</div>
<script>
$( document ).ready(function() {
$('#add_accommodation').click(function() {
make_accommodation(this);
});
});
function make_accommodation(input) {
var value = {
type : $("#AccommodationType").val(),
};
var accommodation = $('#Accommodation').attr('id', 'accommodation');
accommodation.push(value);
console.log(accommodation);
}
</script>
At my end point I want the result to be and array (accommodation = [{1},{2},{3},{4}]). How can I do this?

Give the form an id, and just append a new hidden(?) input that has a name that has [] at the end of it, it will send the values as an array to the server.
HTML
<form id="myform" ...>
Javascript
function make_accommodation(){
var newInput = $("<input>",{
type:"hidden",
name:"accommodation[]",
value: {
type: $("#AccommodationType").val()
}
});
$("#myform").append(newInput);
}
Also you list the output as [1,2,3,4] but your code shows you setting the value as an object with a property type and setting it to the value of the accommodation input, i am going to assume that was a mistake. If I am mistaken just modify the value property in the code above.
Also in your code you change the id of the input, not sure why you were doing that as it serves no purpose and would have made your code error out so i removed it.
EDIT
Since you are wanting to send an array of objects, you will have to JSON.stringify the array on the client end and decode it on the server end. In this one you do not need multiple inputs, but a single one to contain the stringified data.
var accommodationData = [];
function make_accommodation(){
accommodationData.push({
type: $("#AccommodationType").val()
});
$("#accommodation").val( JSON.stringify(accommodationData) );
}
Then on the server you have to decode, not sure what server language you are using so i am showing example in PHP
$data = json_decode( $_POST['accommodation'] );
If you are using jQuery's ajax method you could simplify this by sending the array data
jQuery.ajax({
url:"yourURLhere",
type:"post"
data:{
accomodation:accommodationData
},
success:function(response){
//whatever here
}
});

Add antorher hidden field in form
<input type="hidden" name="accommodation[]"> // click1
<input type="hidden" name="accommodation[]"> // click2
...
<input type="hidden" name="accommodation[]"> // clickn
Then when you submit form on server you will have array of accommodation.
JS part :
function make_accommodation() {
$(document.createElement('input'))
.attr('type', 'hidden')
.attr('name', 'accommodation[]')
.val($("#AccommodationType").val())
.appendTo('form');
}
on server(PHP) :
print_r($_POST['accommodation']);

Since you're using jQuery you can create a function which creates another hidden field, after clicking on the button
<div id='acommodation-wrapper'></div>
<button type="button" id="add_accommodation" onclick="addAnother()">Add Accommodation</button>
<script type="text/javascript">
function addAnother(){
var accWrapper = $('#accommodation-wrapper');
var count = accWrapper.children().length;
var div = "<input type=\"hidden\" class=\"accommodation-"+count+"\" name=\"accommodation["+count+"]\"></div>";
accWrapper.append(div);
}
</script>

Related

Calculate input of html text fields with php

At the moment, I try to create a survey in a webpage. At the end of the survey, users are able to fill two text fields with values. With these values, my plan is to calculate an output, displayed for them at the same page. So:
Input: a
Input: b
Result: ab+b-ab (do not concentrate this please, its just an example)
My plan is that the user is able to fill the two input fields and by a buttonclick, a php function is calculating the result field (by my own algorithm depending on input - this is already working) and fills this field. Do i have to link to another webpage for this purpose?
And how is it possible to grab the two input values and give it to my php function?
And as last thing, how is it possible to start a php function either embedded in html or in an own file?
I tried your solution and some others as well (fetching inputA and inputB from the DOM with document.getElementById does not work. Below is my code
<form>
InputA:<br>
<input type="text" id="inputA"/></br>
InputB:<br>
<input type="text" id="inputB"/></br>
Output:<br>
<input type="text" id="output"/>
</form>
<input name="go" type="button" value="Calculate" id="calculate" >
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.min.js" ></script>
<script type="text/javascript">
$("#calculate").click(function(){
$.get( "submit.php", { value1: $("#inputA").val(), value2: $("#inputB").val() } )
.done(function( data ) {
$("#output").val(data);
});
});
</script>
submit.php:
<?php
$value1 = $_POST['value1'];
$value2 = $_POST['value2'];
$output = $value1 + $value2;
echo($output);
}
?>
When I check with firebug the error, i get a: no element found exception in both (html and php) files. Seems like the problem is, that with: value1: $("#inputA").val(); no value is givent to the server or it can not be handled there.
If i grab the value from the DOM, I can "bring" the value inside the .click function but there is still a "no element found exception" by calling the submit.php.
I have no idea what i am doing wrong, any suggestions? Do i need to install/bind anything in for using JQuery?
After some additional changes, it finally worked (one thing was the header line in the submit.php file):
<form>
WorkerID:<br>
<input type="text" id="workerId"/></br>
CampaignId:<br>
<input type="text" id="campaignId"/></br>
Payment Code:<br>
<input type="text" id="payCode"/>
</form>
<input name="go" type="button" value="Calculate" id="calculate" >
<script type="text/javascript">
$("#calculate").click(function(){
$.get( 'submit.php', { wId: $('#workerId').val(), cId: $('#campaignId').val()} )
.done(function( data ) {
$('#payCode').val(data.payCode);
});
});
and submit.php:
<?php
header('Content-Type: text/json');
$workerId = $_GET['wId'];
$campaignId = $_GET['cId'];
$payCode = $campaignId . $workerId;
$result = array("status" => "success",
"payCode" => $payCode);
echo json_encode($result);
?>
To simplify, i am using jQuery, doing this in vanilla JS is a real pain in the a** in my opinion.
You can use .get(), which is the GET shorthand for .ajax().
With that code, you bind a handler on your submit button and make a AJAX request to your PHP and fill the result your PHP gives into your result field asynchronously.
$("#calculate").click(function(){
$.get( "path/to/your_php.php", { value1: $("#inputA").val(), value2: $("#inputB").val() } )
.done(function( data ) {
$("#output").val(data);
});
});
Also change your submit to something like this:
<input name="go" type="button" value="Calculate" id="calculate" >
Like that, your button won't submit a form and therefore synchronously load your PHP.
Since you seem new to JavaScript and you had this comment
my button, but here i got redirected to submit, no idea how i can go back to page before with filled textfield
in your question, i'll tell you, JavaScript works while the DOM (Document Object Model) is loaded, means you can access your elements when already loaded and alter them.
Getting the value of a input is as easy as that in jQuery:
$("#inputA").val();
With the AJAX you get what your php will return in data.
// the { value1: $("#inputA").val(), value2: $("#inputB").val() } object
// is what you send to your PHP and process it
$.get( "path/to/your_php.php", { value1: $("#inputA").val(), value2: $("#inputB").val() } )
.done(function( data ) {
// data is what your php function returned
});
Using JS you can now change your elements as just said, effectively meaning to change the value of your output here:
$("#output").val(data);
"Working" Example: JSFiddle (There is no PHP to access to, so it will not do anything actively)

AJAX Form, passing return message

I have my AJAX form it works great.
Every time I submit the form It returns the result inside the <div id="message"></div>, but it gets complicated when I have multiple forms. So I was wondering if their is a way to indicate inside the form what <div> to return the message to.
Here is my AJAX.js
$("form#ajaxForm").on("submit", function() {
var form = $(this),
url = form.attr("action"),
type = form.attr("method");
data = {};
form.find("[name]").each(function(index, value){
var input = $(this),
name = input.attr("name"),
value = input.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response) {
$("#message").html(response); //I would like to interactively switch the return div, from #message to like #message2
$("body, html").animate({
scrollTop: $( $("#message") ).offset().top - 5000
}, 600);
}
});
return false;
});
In the form I would like to indicate where the return div is, like
<form action="../forms/add_event_form.php" method="post" id="ajaxForm">
//Can I add an input somewhere here? To indicate where I want the return to go too? Like <input type="hidden" value="message2" name="return">
<input type="text" class="formI" name="date" id="dateI" placeholder="Date">
<input type="submit" name="submit" class="btn btn-primary" value="Add">
</form>
Thank you for reading this. Have a good day! And Thank you in advance for your responses.
Yes, it will not work automatically, but you can add some information to the form and then use it to decide where to put returned HTML. Doing that with additional inputs may not be the best way though, as it can be achieved with far less impact on the DOM: with an attribute on the form itself.
Here's an example of how you may do that.
$(".ajaxForm").on("submit", function(e) {
e.preventDefault();
var form = $(this);
// using jQuery's `data()` to get an ID of response element from the 'data-response' attribute
var responseElementId = form.data("response");
var response = $(responseElementId);
response.html(produceResponse(form));
// function that produces some html response
// you'll use AJAX request to the server for that
// so don't mind its complexity or bugs
function produceResponse(form) {
var data = form.find("input").map(function(i, el) {
return "'" + el.name + "': " + el.value;
});
return "<p>You've submitted:\n<pre>" + Array.prototype.join.call(data, ",\n") + "</pre></p>";
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Form #1</h2>
<form action="#" class="ajaxForm" data-response="#response1">
<input name="first-name" type="text">
<button>Submit</button>
</form>
<div id="response1"></div>
<h2>Form #2</h2>
<form action="#" class="ajaxForm" data-response="#response2">
<input name="last-name" type="text">
<button>Submit</button>
</form>
<div id="response2"></div>
Here I use a data attribute because it was designed for cases like this: to store arbitrary data related to the element, but which doesn't have any defined meaning for the browser. Accessing data stored in such way is really convenient with its HTML5 API, but because of pretty low support from IE (it has it only starting from the version 11), one may use jQuery's method data() to do the same.

Change one value uploaded from a form using jQuery

I have a form.
<form id="myForm">
<input type="text" name="e1" id="e1" value="1" />
<input type="text" name="e2" id="e2" value="2" />
<input type="text" name="e3" id="e3" value="3" />
<input type="text" name="e4" id="e4" value="4" />
<input type="text" name="e5" id="e5" value="5" />
</form>
I use the jQuery validation plugin http://jqueryvalidation.org/ to validate and submit the form.
var validator=$("#myForm").validate({
rules: {},
submitHandler: function(form) {
var data1=$(form).find(':input');
var data2=data1.serializeArray();
//Use ajax to post data2 or submit form...
}
});
Instead of submitting the exact values in the form, I would like to change one of them. For instead, the server should receive a value of "333" instead of "3" for $_POST['e3'].
I don't wish to change the value of the #e3 input on the page. I would rather not use a hidden input to do so, nor manually create my object to upload. How do I change either the data1 object or data2 object to reflect the new value for #e3?
EDIT. Live example at http://jsfiddle.net/rueL9y0p/1/ data1 and data2 values are:
Object { 0=input#e1, 1=input#e2, 2=input#e3, more...}
[Object { name="e1", value="1"}, Object { name="e2", value="2"}, Object { name="e3", value="3"}, Object { name="e4", value="4"}, Object { name="e5", value="5"}]
Simply change the value of the element just before it's submitted, and the serialized array will reflect the new value. Then after your ajax (or after you serialize the data for your ajax), you can easily change the value back to the original.
Insert your conditional logic as needed...
submitHandler: function(form) {
var original = $('#e3').val(); // original value
$('#e3').val('your new value'); // insert new value
// ajax() here // submit via ajax
$('#e3').val(original); // change the value back after the ajax is complete
}
Maybe you'll want to change the value back from within the ajax() complete callback function.
DEMO: http://jsfiddle.net/rueL9y0p/4/
Just as another solution, you could clone the form and make changes to the cloned element.
e.g.
var formClone = form.clone(),
name = formClone.find('#name');
name.val('NEW VALUE');
You would then serialize the cloned form and send that data off to the server.
JSFiddle
haim770 previously posted this as an answer, but he later deleting it. Seems good to me. Any reason why he might have deleted it?
var data1 = $('#myForm').find(':input');
var data2 = data1.serializeArray();
console.log(data1);
console.log(data2);
data2.forEach(function(i) { if (i.name === 'e3') i.value = '333' });
console.log(data2);
http://jsfiddle.net/rueL9y0p/3/

How can I filter data returned from jQuery?

jQuery code:
$(document).ready(function() {
$('#s-results').load('get_report1.php').show();
$('#search-btn').click(function(){ showValues(); });
$(function() {
$('form').bind('submit', function() { showValues(); return false; });
});
function showValues() {
$.post('get_report1.php', { name: form.name.value },
function(result) {
$('#s-results').html(result).show();
}
);
}
});
HTML:
<form name = "form">
<div>Enter name</div>
<input type="text" name="name" id="fn" />
<input type="submit" value="Search" id="search-btn" />
<div>
<input type="text" id="se2" name="search22">
</div>
</form>
<div id = "s-results" style="height:50px;">
</div>
Up to this the script is running perfectly. Now I just want to filter the returned HTML from the above function again.
For implementing this I have tried this line of code:
$(result).filter('#se2');
under the function with the result parameter, but it is not working.
So how can the returned HTML code be filtered?
You probably need find() instead of filter as you need to get the descendant whereas filter "Reduce the set of matched elements to those that match the selector or pass the function's test"
Live Demo
$(result).find('#se2');
If the #se is added in DOM then you can directly use the id selector
se = $('#se2');
I made another demo (as I am still waiting for your demo that is not working) to further elaborate how a string containing the html you have could be passed to jQuery function $() to search elements within it using find.
Live Demo
html = '<form name = "form"> \
<div>Enter name</div> \
<input type="text" name="name" id="fn" /> \
<input type="submit" value="Search" id="search-btn" /> \
<div> \
<input type="text" id="se2" name="search22" value="se2"/> \
</div> \
</form>\
<div id = "s-results" style="height:50px;"> \
</div> ';
alert($(html).find('#se2').val());
Note You can further check the code working in the example above by using find wont work by using filter over this jsfiddle example
The issue
You are successfully adding the result to #s-results:
$('#s-results').html(result).show();
And then tried to select #se2 from the added results like this, with no success:
$(result).filter('#se2');
It didn't work because you didn't get it from the dom added in the second step.
Actually, it is creating a new unattached dom with the same result variable.
The solution
To select #se2 from the added result content correctly, try the following:
$('#s-results').filter('#se2');
Or, as suggested by #zerkms, you could select it directly through:
$('#se2');
These possibilities will work, because now it is referencing something attached to dom, which will search into the same elements you added in the first step.
You can try to use ajax for this as below:
$(document).ready(function () {
$('#s-results').load('get_report1.php').show();
$('#search-btn').click(function () {
$.ajax({
type: "POST",
url: "get_report1.php",
data: {
name: $("#fn").val()
},
beforeSend: function () {
//do stuff like show loading image until you get response
},
success: function (result) {
$('#s-results').html(result).show();
},
error: function (e) {
alert("Error in ajax call " + e);
}
});
});
});
Note: When you click on search-btn each time it will call the get_report1.php file and retrieve the data base on the text-box value that you have passed. I assume that in ge_report1.php file you are using the tex-box value like: $_POST['name'] and you are fetching the data using MySQL search query.
You can use JQuery find instead of filter.
$(result).find('#se2');
Then add to your variable like this
var your_element = $('#se2');

How to pass multiple checkboxes using jQuery ajax post

How to pass multiple checkboxes using jQuery ajax post
this is the ajax function
function submit_form(){
$.post("ajax.php", {
selectedcheckboxes:user_ids,
confirm:"true"
},
function(data){
$("#lightbox").html(data);
});
}
and this is my form
<form>
<input type='checkbox' name='user_ids[]' value='1'id='checkbox_1' />
<input type='checkbox' name='user_ids[]' value='2'id='checkbox_2' />
<input type='checkbox' name='user_ids[]' value='3'id='checkbox_3' />
<input name="confirm" type="button" value="confirm" onclick="submit_form();" />
</form>
From the jquery docs for POST (3rd example):
$.post("test.php", { 'choices[]': ["Jon", "Susan"] });
So I would just iterate over the checked boxes and build the array. Something like
var data = { 'user_ids[]' : []};
$(":checked").each(function() {
data['user_ids[]'].push($(this).val());
});
$.post("ajax.php", data);
Just came across this trying to find a solution for the same problem. Implementing Paul's solution I've made a few tweaks to make this function properly.
var data = { 'venue[]' : []};
$("input:checked").each(function() {
data['venue[]'].push($(this).val());
});
In short the addition of input:checked as opposed to :checked limits the fields input into the array to just the checkboxes on the form. Paul is indeed correct with this needing to be enclosed as $(this)
Could use the following and then explode the post result explode(",", $_POST['data']); to give an array of results.
var data = new Array();
$("input[name='checkBoxesName']:checked").each(function(i) {
data.push($(this).val());
});
Here's a more flexible way.
let's say this is your form.
<form>
<input type='checkbox' name='user_ids[]' value='1'id='checkbox_1' />
<input type='checkbox' name='user_ids[]' value='2'id='checkbox_2' />
<input type='checkbox' name='user_ids[]' value='3'id='checkbox_3' />
<input name="confirm" type="button" value="confirm" onclick="submit_form();" />
</form>
And this is your jquery ajax below...
// Don't get confused at this portion right here
// cuz "var data" will get all the values that the form
// has submitted in the $_POST. It doesn't matter if you
// try to pass a text or password or select form element.
// Remember that the "form" is not a name attribute
// of the form, but the "form element" itself that submitted
// the current post method
var data = $("form").serialize();
$.ajax({
url: "link/of/your/ajax.php", // link of your "whatever" php
type: "POST",
async: true,
cache: false,
data: data, // all data will be passed here
success: function(data){
alert(data) // The data that is echoed from the ajax.php
}
});
And in your ajax.php, you try echoing or print_r your post to see what's happening inside it. This should look like this. Only checkboxes that you checked will be returned. If you didn't checked any, it will return an error.
<?php
print_r($_POST); // this will be echoed back to you upon success.
echo "This one too, will be echoed back to you";
Hope that is clear enough.
This would be better and easy
var arr = $('input[name="user_ids[]"]').map(function(){
return $(this).val();
}).get();
console.log(arr);
The following from Paul Tarjan worked for me,
var data = { 'user_ids[]' : []};
$(":checked").each(function() {
data['user_ids[]'].push($(this).val());
});
$.post("ajax.php", data);
but I had multiple forms on my page and it pulled checked boxes from all forms, so I made the following modification so it only pulled from one form,
var data = { 'user_ids[]' : []};
$('#name_of_your_form input[name="user_ids[]"]:checked').each(function() {
data['user_ids[]'].push($(this).val());
});
$.post("ajax.php", data);
Just change name_of_your_form to the name of your form.
I'll also mention that if a user doesn't check any boxes then no array isset in PHP. I needed to know if a user unchecked all the boxes, so I added the following to the form,
<input style="display:none;" type="checkbox" name="user_ids[]" value="none" checked="checked"></input>
This way if no boxes are checked, it will still set the array with a value of "none".
function hbsval(arg) {
// $.each($("input[name='Hobbies']:checked"), function (cobj) {
var hbs = new Array();
$('input[name="Hobbies"]:checked').each(function () {
debugger
hbs.push($(this).val())
});
alert("No. of selected hbs: " + hbs.length + "\n" + "And, they are: " + hbs[0] + hbs[1]);
}

Categories

Resources