Sending form array values trought ajax - javascript

So my php needs 2 values, operation => string and data => array. The following is the form (dynamically generated inputs) :
<form method="post" action="/operations.php">
Title: <input type="text" value="valuehere" name="data[title]">
.
.
.
Description: <textarea name="data[description]"></textarea><br>
<button class="btn janitor_edit" type="submit">Edit Media</button>
<input type="hidden" value="operateMePls" name="operation">
<input type="hidden" value="254" name="data[id]">
</form>
And now I have to create an array from all data[xyz] in the form, but I'm having trouble finding a way to do so. The closest I've come to was doing like so: link
I must store the array as key/values, no other way, so I can ajax_request = { operation: operation_input, data : input_array_data };.
Oh, and the form works as expected when submiting "normaly" trought POST.

If the form works by itself, then let jQuery take care of it converting the data into a form suitable for XHR for you.
data: $('#your_form').serialize();

I've used an object instead of an array. When you json_decode in PHP, pass "true" as your second argument, and the data will come out as an array. I think this is what you wanted. Please comment if you were looking for something different.
$(".janitor_edit").click(function () {
var data = {};
data.operation = $("input[name='operation']").val();
data.data.id = $("input[name='data\\[id\\]']").val();
data.data.title = $("input[name='data\\[title\\]']").val();
data.data.description = $("input[name='data\\[description\\]']").val();
});

Related

Need to fill in form data from json data . Not showing up

Things are not important since I'm also trying this with jsfiddle, thus ruling out that isn't React.JS causing the form to not fill.
I have data from a file. It should be in json format and goal is to hydrate (fill) form fields
Here is a fiddle of it: https://jsfiddle.net/vp5kLxgs/
While it would be nice to use some map function or perhaps the ID of the form, I will settle for about anything that will just loop over the form. I can change the form if needed I plan on having ID and Name
form:
<form id="importantForm" role="form" onSubmit={this.handleSubmit}>
<div className="form-group">
<label htmlFor="family1 Name">
Family1 Name
</label>
<input type="text" className="form-control" name="family1Name" id="family1Name" />
.... // etc....
</form>
javascript:
//document.getElementById("family1Name").value = "jack"
var json = {family1Name: "jack", family1Relationship: "", family1Phone: ""};
var form_data = new FormData();
for ( var key in json ) {
form_data.append(key, json[key]);
console.log('key', key)
console.log('impor..[key]', json[key])
}
Manually setting family1Name with document.getElementById that works...
but the looping over the data does not fill the form fields.
With console.log i can see the key and value , but I don't know how formdata is suppose to know to use my form of id="importantForm" , does it need to ?
FormData() is not intended as a way to bind the data between a data structure and a form. That's what the UI frameworks/libraries (React, Vue, Angular, etc) were created for. FormData is intended to offer a way to build data structures that can be easily submitted to the backend:
It is primarily intended for use in sending form data, but can be used
independently from forms in order to transmit keyed data. The
transmitted data is in the same format that the form's submit() method
would use to send the data if the form's encoding type were set to
multipart/form-data
However, setting your form field values manually is pretty straight forward:
var json = {family1Name: "jack", family1Relationship: "brother", family1Phone: "00045555000"};
var form = $("#importantForm");
for (var key in json) {
var selector = `input[name="${ key }"], textarea[name="${ key }"]`
var input = $(form).find(selector)
input.val(json[key]);
}
Sample JSON
const data = {
family1Name: "Jack",
family1Relationship: "None",
family1Phone: "999"
};
And put this following jsx inside your <form></form> tag, quite simple
{Object.keys(data).map(k => (
<div className="form-group">
<label htmlFor={k}>{k}</label>
<input
type="text"
className="form-control"
name={k}
id={k}
value={data[k]}
/>
</div>
))}
This is the output

Get multiple values from jquery and post it to php

<input type="checkbox" value="<?= $servicii_content[$j]['title'] ?>" name="check_list" id="check" />
i get multiple values from the table above if the checkboxes are checked with jQuery, like this.
var temp = $("input:checkbox[name=check_list]:checked").map(function(){
return $(this).val();
}).get();
alert(temp);
I get the alert with the correct checked values!
I post them later here:
url: "/servicii_email.php",
type: "POST",
data: {
families: temp,
How can I get the elements of "families" eg.:Family1, Family2, Family3, etc. - which are checked to post it to the php file? What is the correct way to do that?
For example, you can just make string with name of variable and it value. That will be something like this Family1=true,Family2=false
On server you just need to split string by , and after that split by =, you will get two dimensional array {{Family1, true}, {Family2, false}}
You can make use of serializeArray() method:
var temp = $("input:checkbox[name=check_list]:checked").serializeArray();
// outputs:
// [{name:"check_list", value:"theValue"},......n]

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)

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/

jQuery: How to submit an array in a form

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>

Categories

Resources