How do I change FormData before it submits? - javascript

I'm working on a project where I need to change FormData before it submits. I can't change the element value, I have to change the actual FormData that goes into a the POST.
I've tried changing form.onsubmit to update the value (works for some fields but others dont work due to validation checks)
<form name="aspnetForm" method="post" action="Posturl.aspx" onsubmit="javascript:return WebForm_OnSubmit();" id="aspnetForm" autocomplete="off">
<input type="text" name="field1" id="field1" value="">
<input type="text" name="field2" id="field2" value="">
</form>
I know I can create a new FormData object and can set the values of the object with formData.set('field1', 'newValue') but Im unsure on how to POST this new FormData object and not the old object.

Try to use formdata event listener.
document.querySelector("form").addEventListener('formdata', (e) => {
const formData = e.originalEvent.formData;
formData.append('alphabet', "abcde");
formData.append('a1b2', "123123");
});
source:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/formdata_event
I use e.originalEvent.formData instead of e.formData (following the doc above) because e.formData is undefined And of course, don't use e.preventDefault on submit because it will cancel the default form request (Doc type request).

You can get the data by putting a event listener on the "[type='submit']" button. In the following example I am using jquery to locate the form and ajax to send a request. Hope it Helps.
$("#submit-info").click(function ()
{
var data = new FormData($('form')[0]);
data.append("route",1); (//adding a new value)
data.set('field','newValue'); //use the name attribute of html tag to target the respective key-value pair
$.ajax({
send the data(optional)
});
});
<form method="post" enctype="multipart/form-data" >
<input type="text" name="field" id="field1" value="">
<button type="submit" class="btn btn-primary" id="submit-doc">Submit</button>
</form>

You can simply put the data in the input along with onsubmit
<form name="aspnetForm" method="post" action="Posturl.aspx" onsubmit="formData.set('field1', 'newValue');javascript:return WebForm_OnSubmit();" id="aspnetForm" autocomplete="off">
<input type="text" name="field1" id="field1" value="">
<input type="text" name="field2" id="field2" value="">
</form>

var formData =new FormData();
formData.set('field1', 'sample');
formData.set('field2', 'try');
formData.set('field3', 'again');
//delete the key
formData.delete('field1');
//append new value of the key
formData.set('field1', 'test');
//check all formdata values
for(var pair of formData.entries())
{
console.log('FormData Pair ('+ pair[0]+ ': '+ pair[1]+')');
}
You can try this solution by deleting the key and setting new value
var formData =new FormData();
formData.set('field1', 'sample');
//delete the key
formData.delete('field1');
//append new value of the key
formData.set('field1', 'test');
//check the formdata key if value was updated object
for(let val of formData.values())
{
console.log(val);
}

Related

can not sent appended FormData to php-file from simple html-form

I have the following form html:
<form method="POST" id="checkoutform" novalidate="novalidate" enctype="multipart/form-data">
<input type="hidden" name="action" value="order">
...
<input type="submit" onclick="return clickSubmitbuttonOnce(this);">
My clickSubmitbuttonOnce(button) is:
var t = document.getElementById("checkoutform");
var formData = new FormData(t);
formData.append("payment", "Payment");
for (var p of formData) {
console.log("%s : %s",p[0],p[1]);
}
t.submit();
If I pass this to file the print_r($_POST,true); do not gives the appended payment. Only the action-field is given. The console-statement says it is given.
Whats wrong. Does need FormData() mandatory an Ajax request?
How can I achieve to pass the payment-field?

How do i get submitted form (inputs like name="array[key]") type data as array/object in js to use in submit callback

I have form in which i am submitting multiple inputs containing name attributes as array like name="array[key]"
<form onsubmit="callback($(this));">
<input type="text" name="stock[quantity]">
<input type="text" name="stock[old]">
<input type="text" name="form[mrp]">
<input type="text" name="form[price]">
</form>
I have tried new formData($("form")[0]) and jQuery $("form").serializeArray() both returning name="array[key]" as string.
I want this data as multidimensional object like we got this in php when submit this form like.
<script>
function callback($form){
/*
here i want form data in js object like
{
stock : {quantity : ... , old : ....},
form : {mrp : ... , price : ....}
}
or something like this
*/
}
</script>
I am using JS, jQuery, and Vue.js in this project, actually i want to put this form data to indexedDB after successful save on server. i have different tables/objectStore for stock and form
Try this..
function callback($form) {
let result = {};
let formData = $form.serializeArray();
formData.forEach(obj => {
let inputValue = obj.name.split('[');
if (!result[inputValue[0]]) {
result[inputValue[0]] = {};
}
let innerText = inputValue[1].replace(']','');
result[inputValue[0]][innerText] = obj.value;
});
console.log(result);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form onsubmit="callback($(this)); return false;">
<input type="text" name="stock[quantity]">
<input type="text" name="stock[old]">
<input type="text" name="form[mrp]">
<input type="text" name="form[price]">
<input type="submit" value="submit">
</form>

How to concatenate url with a variable everytime a login is made

The Wordpress site I'm working on:
http://www.careersroadmap.com/
After submission of a registration form, I have to redirect to this URL:
http://careertest.edumilestones.com/access-login-api.php?
However, during the redirect, I have to pass this variable to the URL:
category=2123&channel_id=371&cd=89&age=371&access_code=accesscodehere
So the final destination URL will be:
http://careertest.edumilestones.com/access-login-api.php?category=2123&channel_id=371&cd=89&age=371&access_code=accesscodehere
The access_code variable will change for each user that logs in.
I tried an AJAX call using the code below:
<script>
var startButton = document.getElementById("startButton");
startButton.addEventListener("click", getApiFunction());
function getApiFunction(){
var myRequest = new XMLHttpRequest();
myRequest.open('GET', 'http://careertest.edumilestones.com/access-login-api.php?category=2123&channel_id=371&cd=89&age=371&access_code=accesscodehere');
myRequest.onload= function(){
var myData = JSON.parse(this.response);
};
myRequest.send();
};
</script>
After trying the above code, I got the CORS policy error.
How do I accomplish this with Javascript or PHP??
I suppose you could add hidden inputs to the registration form.
Something along those lines:
<form action="http://careertest.edumilestones.com/access-login-api.php" method="GET">
<input type="hidden" name="category" value="2123">
<input type="hidden" name="channel_id" value="371">
<input type="hidden" name="cd" value="89">
<input type="hidden" name="age" value="371">
<input type="hidden" name="access_code" value="democodesjam12474">
</form>
A hidden field lets web developers include data that cannot be seen or modified by users when a form is submitted.
Read more about it here: https://www.w3schools.com/tags/att_input_type_hidden.asp

Send multiple input using FormData

I have this form:
<form action="#" id="form-add">
<input type="text" name="test[]" value="hello">
<input type="text" name="test[]" value="bye">
<button type="submit"><Submit/button>
</form>
And I want, when the user submits, this information to be sent via AJAX using FormData like this:
$('form-add').submit(function (event)
{
//Prevents from submitting form
event.preventDefault();
var formData = new FormData();
var form_fields = $('#form-add').serializeArray();
$.each(form_fields, function (key, input)
{
formData.append(input.name, input.value);
});
});
The problem is when I try to check the entries inside the variable formData, it only shows the value of the first input:
console.log(formData.get('teste[]'));
//Returns
hello
How can I send this kind of inputs using FormData?
It will send all values. But if you want to check on a client you'll need to use getAll method.
const form = new FormData
form.append('a', 1)
form.append('a', 2)
console.log(form.getAll('a'))

Set Input array value using jquery

I am trying to implement html input array.
<input type="text" name="firstName[]" id="firstName[]">
And i need to set value of another form which looks something like
<form id="tempForm">
<input type="text" name="userName" id="userName">
<input type="text" name="userId" id="userId">
</form>
into the input array using jquery on form submit.
For that i tried following on form submit,
var currentIndex=$("input[name^=firstName]").length;
$("#firstName").eq(currentIndex).val($("#userName").val());
But it doesn't works,obviously.
Question:
How to set value of input array using jquery?
Use the jquery append function for add inputs with different attribute value :
Check it :
$(document).ready(function(){
var a = ["username","userid"];
var b = ["username","userid"];
for( var i = ; i <3 ; i++){
$('#tempForm').append('<input type="text" name="'+a[i]+'" id="'+b[i]+'" />);
}
});
Then continue your other work:
replace this code with your js code :
var currentIndex=$("input[name^=firstName]").length;
$("#firstName").eq(currentIndex).val($("#"+userName).val());

Categories