converting files to JSON object in addition to other fields - javascript

I have the following form in my PHP file defined. I am planning to convert the form fields to JSON object so that I could pass it along to
a java webservice using Ajax maybe.
Here's how I was planning to serialize it :
function submitUsingjQuery(){
var formdata = $('#myForm').serializeArray()
}
Since I have three files upload options, is it possible to convert uploaded files to a JSON object as well along with other form fields?
If not, is there any other alternative to achieve this ?
<!-- Start of HTML Form -->
<form id = "myForm">
<div class="row" style="margin-bottom: 15px" name="infoRegAttachedDocuments" >
<div class="col-md-4">
<label for="docSubmission">First Document</label>
<input type="file" id="firstdoc">
</div>
<div class="col-md-4">
<label for="docApproval">Second Document</label>
<input type="file" id="seconddoc">
</div>
<div class="col-md-4">
<label for="additionalDocs">Third Document (if any)?</label>
<input type="file" id="thirdocs">
</div>
</div>
<div class="row" style="margin-bottom: 15px" name="infoDiv" >
<div class="col-md-6">
<label for="projectTitle">Title </label>
<input type="text" class="form-control" id="projectTitle" value="<?php echo $previousProjTitle;?>" >
</div>
<div class="col-md-6">
<label for="projectDesc">Description </label>
<input type="text" class="form-control" id="projectDesc" value="<?php echo $previousProjDesc;?>">
</div>
</div>
</form>
<!-- END of HTML Form -->
<div class="row"style="margin-top: 15px;" >
<button class="btn btn-primary" onclick="submitUsingjQuery()">Submit</button>
</div>

It is possible to convert those files to base64 encoded strings which can be sent to the server via ajax. Than you can end up with a JSON object like so:
{
"firstdoc": {
"name": "<some file name>",
"type": "image/jpg",
"data": "base62 encoded string"
}
}
But from the JS client and server side point of view it is much easier to use the new Form Data object and the fetch api, because it will take care of all the mime types an stuff. It can be used like so:
//create the data object directly from the form
var fd = new FormData(document.getElementById(''myform));
//send to the server without any conversion,
//everything is happening automatically
fetch('<url>', { body: fd, /*…some more options…*/ });
This way you don't have to bother yourself in finding a proper way to transmit files, since that way uses the »standard POST way« and if your server follows those standards, everything should work. Especially for files that is really helpful since this way the appropriate Content-Type header is set for each of the files to transmit.
It might be noteworthy here that this approach will create a request that is similar to the one which the browser would create if the would be submitted, the »plain html way«, without ajax. So in case JS is disabled or the browser too old, the form can still be processed on the serverside without any change on the code.

Related

how to post json data and form data into single request in laravel 9

I have a form and inside the form I will possible input multiple image that i converted to put into json
my form html create.blade.php
<form method="post" action="{{ route('m_announcement.store') }}" enctype="multipart/form-data">
#csrf
/////// many input just not included
//////// my image input
<div class="row mb-4">
<label class="col-sm-2 col-label-form">Upload Images</label>
<div class="col-sm-10">
<input type="file" name="files[]" id="files" multiple
accept="image/jpeg, image/png, image/gif," onchange="timeFunction()"><br />
</div>
</div>
///////// my imagae preview
<output id="Filelist"></output>
<div class="text-center">
<input type="submit" class="btn btn-primary" value="Add" />
</div>
</form>
This function in script output images to var AttachmentArray in json format that i want to post also with the form
function printvalues() {
console.log(AttachmentArray); all image converted in base64 output in json format with imahe details
is there is a way to join the json to the form and when i press submit the json and the data will output on request
laravel 9 announcementcontroller.php
public function store(Request $request)
{
//dd($request);
$jsonimages = $request->jsonimages;
// decode the json a create loop to upload to database image
// some code to upload the form to announcement database
//image upload
}
im not just into in frontend yet, most of this time im developing in backend first, this is my first web app project, im tried searching ajax or something but i dont understand that yet.
you can get name of field input with
dd($request->file->('files'));
see here for more information Retrieving files upload in laravel 9

how to change multer express post headers?

I have a node/express app and I want to add an image upload to an order form.
I can get the html form to POST using the action link, but I also want my javascript file for this page to be able to take all the rest of the form data and send it to a different post route to create a database entry for the whole order.
Here is my HTML that works for sending the post and image, but reloads the page because of event default behaviour.
<form id="editOrderForm" method="POST" action="/uploadphoto" enctype='multipart/form-data' >
<div class="form-row">
<div class="form-group col-md-3">
<label for="orderWarranty">Warranty Type</label>
<input type="text" class="form-control" id="orderWarranty" placeholder="Warranty Type">
</div>
<div class="form-group col-md-3">
<label for="orderAppliance">Appliance</label>
<input type="text" class="form-control" id="orderAppliance" placeholder="Appliance">
</div>
<div class="form-group col-md-3">
<label for="orderBrand">Brand</label>
<input type="text" class="form-control" id="orderBrand" placeholder="Brand">
</div>
<div class="form-group col-md-3">
<label for="orderModel">Model</label>
<input type="text" id="orderModel" class="form-control" placeholder="">
</div>
</div>
<div class="modal-body mx-6" id="editOrderDiv">
<div class="col-md-3">
<label for="image-upload">Upload Image</label>
<input type="file" accept="image/*" id="imageupload" name="imageupload">
</div>
</div>
<div class="modal-footer d-flex justify-content-center">
<input type="submit" class="btn btn-primary" id="ordersubmit"></input>
</div>
</div>
</form>
What I need is for the below code to ALSO run after the form submits, to make another post.
If I try to post to my upload route from my js file it sends the post with a content-type of application/x-www-form-urlencoded instead of multipart/form-data no matter what I do, so multer doesnt accept it.
Is there a way to set the content-type before I send the request to the backend?
$("#editOrderForm").on("submit", function handleFormSubmit(event) {
event.preventDefault();
function submitOrder(Order) {
$.post("/api/orders/" + currentOrder.id, Order, function () {
getOrders(orderCategorySelect.val());
});
};
I don't really use jQuery, but I think you want to create a headers object in the call to $.post.
Check out the jquery docs, which also refers to the ajax settings.
From skimming the docs, it sounds like you need to create an Ajax request with the correct header in the settings, and then use that request to do the actual POST.
Something like:
let request = $.post({
"header" : "multipart/form-data"
})
request("/api/orders", [rest of code here])

redirecting a mobirise email form

I'm creating a new website for my company using mobirise. The mobirise templates come with predesigned email forms that were created using formoid. When a user uses the email form to send an email the information is sent to formoid and then formoid sends the information to me at my email address. All of the coding in the email form is behind the scenes, so I can't actually see what it's doing.
On one of my forms I need to have the page redirect to another page where users will be able to upload a file to my server using another script. I have contacted mobirise to ask them if they could tell me how to redirect after the user clicks the submit button, but they said I had to contact formoid. So far I haven't gotten a response back from formoid so I thought I would try to look for a solution on my own.
I have tried adding javascript code to the coding on the page, but as I said, most of the coding of the form is somewhere behind the scenes and I can't figure out exactly which coding is performing the form's submit action.
What I was hoping for is a suggestion about how I could add some additional JavaScript coding that would watch for the submit button in the form being clicked and then redirect the page. I'm not positive this is even possible, but I figured that if anyone would be helpful it would be the people who post solutions here. I'm rather new to JavaScript, so I'm not sure where to start and I don't want to experiment for hours and hours and get frustrated because nothing is working.
So, if anyone can give me an idea here I would greatly appreciate it. Below is the coding for the form in case it helps:
<div data-form-alert="true">
<div hidden="" data-form-alert-success="true" class="alert alert-form alert-success text-xs-center">Thanks for uploading your audio file!</div>
</div>
<form action="https://mobirise.com/" method="post" data-form-title="FTP Upload">
<input type="hidden" value="NTcF3QgiRzQHgm5xv+UnYlBBGPR27Q6NZwj5EPuecwUNxuL8vndMlaaoM2PpzlkXlNaFBrtr2mU+CfZxfef01mKMpaQkezUMhyWXZgieem0/pt/V/nU0iUetLNqsEpj7" data-form-email="true">
<div class="row row-sm-offset">
<div class="col-xs-12 col-md-4">
<div class="form-group">
<label class="form-control-label" for="form1-3o-name">Name<span class="form-asterisk">*</span></label>
<input type="text" class="form-control" name="name" required="" data-form-field="Name" id="form1-3o-name">
</div>
</div>
<div class="col-xs-12 col-md-4">
<div class="form-group">
<label class="form-control-label" for="form1-3o-email">Email<span class="form-asterisk">*</span></label>
<input type="email" class="form-control" name="email" required="" data-form-field="Email" id="form1-3o-email">
</div>
</div>
<div class="col-xs-12 col-md-4">
<div class="form-group">
<label class="form-control-label" for="form1-3o-phone">Phone</label>
<input type="tel" class="form-control" name="phone" data-form-field="Phone" id="form1-3o-phone">
</div>
</div>
</div>
<div class="form-group">
<label class="form-control-label" for="form1-3o-message">One or more files are being uploaded to the WORDsmart server. </label>
<textarea class="form-control" name="message" rows="7" data-form-field="Message" id="form1-3o-message"></textarea>
</div>
<div><button type="submit" class="btn btn-info">CONTACT US</button></div>
</form>
in this case, I would recommend you to use another form. As far as I know form wouldn't work if you would bring any changes to form of Mobirise. Just use another form creator and implement it manually to Mobirise's project after publication to the local folder (the project of Mobirise).
You can read tutorial about publishing here: https://mobirise.com/help/local-host-369.html
Just change the action field in the first line of the form, to the page were you would like to send the data.
The next hidden input line with the public key may be deleted also.

Dynamically adding Spring MVC JSP form:input using JS giving binding errors

I have a code block where i am dynamically adding
Below is the code that i am using -
<form:form role="form" method="post" id="addForm" action="/data/SomeAction" modelAttribute="someModel">
<div id="rowCabin1">
<div id="rowCabinData1">
<div class="row" id="cabinRow1">
<div class="col-xs-12 col-sm-12 col-md-6 col-lg-6">
<div class="form-group">
<form:input path="test" placeholder="Name" class="form-control" style="width:100%" />
</div>
</div>
</div>
</div>
</div>
</form:form>
Below is the javascript.
$().ready(function() {
var i=2;
$("#addRowCabin").click(function(){
$('#rowCabin1').append('<div id="rowCabinData'+i+'"><div class="row" id="cabinRow1"><div class="col-xs-12 col-sm-12 col-md-6 col-lg-6"><div class="form-group"><form:input path="test" placeholder="Name" class="form-control" style="width:100%" /></div></div></div></div>');
i++;
});
$("#delRowCabin").click(function(){
if(i>2){
$("#rowCabinData"+(i-1)).remove();
i--;
}
});
});
Now when trying to load the page -
ERROR: org.springframework.web.servlet.tags.form.InputTag - Neither BindingResult nor plain target object for bean name 'test' available as request attribute
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'test' available as request attribute
at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:144)
My gut feel was that it is because of the form:input not being part of the form:form tag itself. but since i am adding in the form tag, that should not be the case.
Please suggest.
AJ
<form:input> is jsp tag which is evaluated during request processing on server. You cannot add it with javascript. If your javascript was part of the JSP then this is why it failed on load-time.
Instead look at generated HTML how existing input id and name look like and append raw HTML input tag.
Or better use c:forEach around field collection in JSP and add new dynamic field by AJAX request.
Nice article about binding a collection is here: http://viralpatel.net/blogs/spring-mvc-multi-row-submit-java-list/

Securing PHP file. Allow variables to be posted only from HTML form

I am using simple HTML/AJAX/PHP script.
<form id="new_user" action="" method="post">
<div class="col-md-3 form-group">
<label for="username">Username</label>
<input type="text" class="form-control" name="username" id="username" required>
</div>
<div class="col-md-3 form-group">
<label for="city">City</label>
<input type="text" class="form-control" name="city" id="city" required>
</div>
<input type="button" name="button1" value="Done" class="btn btn-success" onClick="aa();"></button>
</form>
<div id="d1"></div>
When the button is clicked:
<script type="text/javascript">
function aa()
{
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("POST","ins.php?username="+document.getElementById("username").value+"&city="+document.getElementById("city").value,false);
xmlhttp.send(null);
document.getElementById("d1").innerHTML=xmlhttp.responseText;;
}
</script>
My ins.php file:
<?php
$username_safe = htmlspecialchars($_GET['username']);
$city_safe = htmlspecialchars($_GET['city']);
echo $username_safe . " " . $city_safe;
?>
How to secure the ins.php file (or even the entire form) so that the client wouldn't be able to post variables from URL field, like: http://www.example.com/ins.php?username=aaa&city=bbb
Directly referencing your question:
How to secure the ins.php file (or even the entire form) so that the client wouldn't be able to post variables from URL field, like: http://www.example.com/ins.php?username=aaa&city=bbb
This is already being done as passing parameters in the URL is a GET request, you've set your form up to be a POST submitted form in the line:
<form id="new_user" action="" method="post">
So just don't look at the $_GET super global array. Look at $_POST instead. Better yet use the filter_input() function correctly e.g.: $username_safe = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
Generate an id which is only valid for a certain amount of time (say 15 minutes). Build your form with php, and include this ID inside a <input type="hidden" value="<?=$id?>">
Send this ID back to the server, and check in PHP if this ID is allowed to submit this form.
It appears as though you are sending your vars by POST vice GET, so this really shouldn't be an issue. Barring using either of these methods, you could also send the vars as session data but this becomes cumbersome to set/unset the session vars.

Categories

Resources