Google Script: get values from input forms - javascript

I implemented an authentication process using google scripts but with hard-coded data for username and password values from payload option and I can't find a way to get these values from the html page when user presses the Login button...
Is there a way to get this values from input fields to payload option?
Here is my code:
HTML:
<body>
<form>
<fieldset class='login'>
<div class="required">
<label for="email">Email:</label>
<input type="text" name="email" id="email" class="input-text" />
</div>
<div class="required">
<label for="pass">Password:</label>
<input type="password" name="pass" id="pass" class="input-password" />
</div>
</fieldset>
<input type="submit" id="submit-btn" value="Login" name='Submit' class='btn'/>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$('#submit-btn').click(function() {
google.script.run.login();
});
</script>
</body>
Google Script:
function onOpen() {
SpreadsheetApp.getUi()
.createMenu('Menu')
.addItem('Show sidebar', 'showSidebar')
.addToUi();
}
function showSidebar() {
var html = HtmlService.createHtmlOutputFromFile('login')
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setTitle('SDR Tag Governance')
.setWidth(300);
SpreadsheetApp.getUi()
.showSidebar(html);
}
function login(){
var endpoint = 'login';
var url = 'https://example.com/api/'+endpoint;
var payload = {
'username' : 'email', //Add here the value from #email input
'password' : 'pass' //Add here the value from #pass input
}
var headers = {
'Connection':'keep-alive',
'Content-Type':'application/json;charset=utf-8',
'Accept':'application/json, text/plain, */*',
}
var options = {
'method' : 'post',
'headers' : headers,
'payload': JSON.stringify(payload),
};
var urlResponse = UrlFetchApp.fetch(url, options);
Logger.log(urlResponse);
}
I tried to add this code to the HTML page:
<script>
$('#submit-btn').click(function() {
google.script.run
.withSuccessHandler(function(response) {
return urlResponse;
})
.login({
email: $('#email').val(),
pass: $('#pass').val()
});
});
</script>
With GS function:
function login(email,pass){
var endpoint = 'login';
var url = 'https://example.com/api/'+endpoint;
var payload = {
'username' : email,
'password' : pass
}
var headers = {
'Connection':'keep-alive',
'Content-Type':'application/json;charset=utf-8',
'Accept':'application/json, text/plain, */*',
'Cookie':'...',
}
var options = {
'method' : 'post',
'headers' : headers,
'payload': JSON.stringify(payload),
};
var urlResponse = UrlFetchApp.fetch(url, options);
Logger.log(urlResponse);
}
But it doesn't work...

In your original HTML file you are not passing anything to the login() function in you .gs file. You can use jquery to grab those values.
<script>
$('#submit-btn').click(function() {
google.script.run
.withSuccessHandler(function(response) {
// this is where you handle the response from your Code.gs
})
.withFailureHandler(function(error) {
console.log(error);
})
.login({
email: $('#email').val(),
pass: $('#pass').val()
});
});
</script>
EDIT: login function in gs file
function login(data){
// i dont think you need this endpoint variable
var endpoint = 'login';
var url = 'https://example.com/api/'+endpoint;
// since you are passing in an object in the html, you can
// access the properties of data
var payload = {
'username': data.email,
'password': data.pass
}
// this is the same as your original
var headers = {
'Connection':'keep-alive',
'Content-Type':'application/json;charset=utf-8',
'Accept':'application/json, text/plain, */*',
'Cookie':'...',
}
// are you sure you need to JSON.stringify the payload?
// try just passing the payload object as is
var options = {
'method' : 'post',
'headers' : headers,
'payload': JSON.stringify(payload),
};
var urlResponse = UrlFetchApp.fetch(url, options);
// Logger.log shows you what comes back
// when that is fine change it to return urlResponse;
// this will then get sent to the withSuccessHandler that is
// in your HTML file.
Logger.log(urlResponse);
}

Related

Laravel 6 Error - Undefined property: App\Http\Controllers\GetContentController::$request

I am trying to send form data including files (if any) without form tag via Ajax request. However, I am getting the following error message
Undefined property: App\Http\Controllers\GetContentController::$request
Here are my codes
Controller
public function GetContentController($params){
$CandidateFullName = $this->request->CandidateFullName;
$CandidateLocation=$this->request->CandidateLocation;
//inserted into database after validation and a json object is sent back
Web.php
Route::match(['get', 'post'], '{controller}/{action?}/{params1?}/{params2?}', function ($controller, $action = 'index', $params1 = '',$params2 = '') {
$params = explode('/', $params1);
$params[1] = $params2;
$app = app();
$controller = $app->make("\App\Http\Controllers\\" . ucwords($controller) . 'Controller');
return $controller->callAction($action, $params);
})->middleware('supadminauth');
Blade
<input type="text" id="CandidateFullName" name="CandidateFullName" class="form-control">
<input type="text" id="CandidateLocation" name="CandidateLocation" class="form-control">
<button id="final_submit">Submit</button>
<script>
$('#final_submit').click(function(e){
e.preventDefault();
var data = {};
data['CandidateFullName']= $('#CandidateFullName').val();
data['CandidateLocation']=$('#CandidateLocation').val();
submitSaveAndNext(data)
});
function submitSaveAndNext(data){
//console.log(data);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': '{{csrf_token()}}'
}
});
$.ajax({
type : "POST",
url : '{{url("GetContent/submitContent")}}', //GetContentController ,but without Controller in the end
dataType : "json",
contentType : "application/json",
data : JSON.stringify(data),
success : function(response){
//console.log("response ",response);
if(response.message=="success"){
swal({
title:"Success",
type: "success",
});
}else{
swal({
title:"Sorry! Unable to save data",
type:"warning"
})
}
},
error:function(xhr, status, error){
swal({
title:"Sorry! Unable to save data",
type:"warning"
})
}
}) //ajax ends
I don't think controller instance in laravel possess the property having request instance, you'll have to type-hint to obtain the object of the request
public function GetContentController($params) {
// $this->request is the issue
$CandidateFullName = $this->request-> CandidateFullName;
$CandidateLocation = $this->request->CandidateLocation;
}
So you can try either of the below-given solutions
// make sure include the Request class into your controller namespace
public function GetContentController($params, Request $request) {
$CandidateFullName = $request->input('CandidateFullName');
$CandidateLocation = $request->input('CandidateLocation');
}
Or use the helper function for request
public function GetContentController($params) {
$CandidateFullName = request('CandidateFullName');
$CandidateLocation = request('CandidateLocation');
}
These links will help you get more details :
https://laravel.com/docs/8.x/requests#accessing-the-request
https://laravel.com/docs/5.2/helpers#method-request

Rendering the response of a jquery POST request in NodeJs

Functionality:
The functionality of this code is to update user details on the user Profile-page.
Code:
Profile.ejs
<script>
(function() {
function toJSONString( form ) {
var obj = {};
var elements = form.querySelectorAll( "input, select, textarea" );
for( var i = 0; i < elements.length; ++i ) {
var element = elements[i];
var name = element.name;
var value = element.value;
if( name ) {
obj[ name ] = value;
}
}
return JSON.stringify( obj );
}
document.addEventListener( "DOMContentLoaded", function() {
var form = document.getElementById( "test" );
form.addEventListener( "submit", function( e ) {
e.preventDefault();
var json = toJSONString( this );
//alert(json);
$.ajax({
type: "POST",
url: "/profile",
data: json,
success: function(){},
dataType: "json",
contentType : "application/json"
});
}, false);
});
})();
</script>
<div id="res">
<h4>
<%= status %>
</h4>
</div>
<form id="test" action="/profile" method="post">
<input type="text" name="name" id="name" value=""/>
<input type="text" name="about" id="about" value=""/>
<input type="text" name="hobbies" id="hobbies" value=""/>
<input type="submit" value="send" class="btn btn-primary btn-block"/>
</form>
Index.js
router.get('/profile', loggedin, function(req, res, next) {
res.render('profile', {status:''});
});
router.post('/profile', loggedin, function(req, res, next) {
res.render('profile', {status:'Changes Updated'});
});
Expected-Outcome:
Once the post request with all the details are sent, the <div id="res"> should contain the text Changes Updated.
Actual-Outcome:
Once the post request is sent, 200 OK response is observed and the response packet has the text Changes Updated. However, the browser does not reflect it. The new response received is not rendered.
Kindly assist in resolving this issue, as I'm fairly new to this( And the entire code is put together from a lot of places ). Also, any extra information, or good reads on the subject would be much appreciated
You will need to use the jQuery html attribute to insert the desired results into the div. ejs is used for creating templates before your page has loaded, and not for inserting ajax data after the page has loaded.
Try this:
$(document).ready(function() { //the jQuery equivalent
var form = $('#test');
form.on('submit', function(e) {
e.preventDefault();
var json = toJSONString(this);
$.ajax({
type: "POST",
url: "/profile",
data: json,
success: function(data) {
console.log(data);
$('#res').html(data); //insert "data" into the inner html of the div
},
dataType: "json",
contentType : "application/json"
});
}, false);
});
});

angularjs $http(config) ith data from form not working

I have an issue with $http in angularjs :
app.controller('ctrlProfil', function($scope, $http){
$scope.loginProfil = "<?= $_SESSION['login']?>";
$scope.mdpProfil = "<?= $_SESSION['mdp']?>";
$scope.emailProfil = "<?= $_SESSION['email']?>";
var config = {
method: 'POST',
url: 'modifProfil.php',
data: $('#formProfil').serialize()
}
$scope.submit = function(){
$http(config).
then(function(response){
console.log(response);
console.log($('#formProfil').serialize());
})
}
});
my form =>
<form id="formProfil" ng-submit="submit()">
<p><span>Bonjour </span><input type="text" name="loginProfil" value="{{loginProfil}}"/></p>
<p>Mon mot de passe: <input type="text" name="mdpProfil" value="{{mdpProfil}}"/></p>
<p> Email: <input type="email" name="emailProfil" value="{{emailProfil}}"/></p>
<input class="btn btn-primary" type="submit" value="Enregistrer"/>
</form>
my php code =>
try
{
$db = new PDO('mysql:host=localhost;dbname=monprojet;charset=UTF8', 'root', 'root');
}
catch(Exception $e)
{
die('Erreur : '.$e->getMessage());
}
$login = $_POST['loginProfil'];
$mdp = $_POST['mdpProfil'];
$email = $_POST['emailProfil'];
$rep = $db->query('SELECT id FROM utilisateur WHERE login='.$_SESSION['login']);
$reponse = $db->prepare('UPDATE utilisateur SET login= :login, mdp= :mdp, email= :email WHERE id='.$rep);
$reponse->execute(array(
':login' => $login,
':mdp' => $mdp,
':email' => $email
));
$json = json_encode($reponse->fetchAll());
$reponse->closeCursor();
echo $json;
i can't manage to send the data via the $http(config), i have an error telling me :
Notice: Undefined index: loginProfil in
/Applications/MAMP/htdocs/izad/git/modifProfil.php on line 15
Notice: Undefined index: mdpProfil in
/Applications/MAMP/htdocs/izad/git/modifProfil.php on line 17
Notice: Undefined index: emailProfil in
/Applications/MAMP/htdocs/izad/git/modifProfil.php on line 19
but my index are defined, need some help to understand this one
Thanks
You have to add headers application/x-www-form-urlencoded to receive the data in GET/POST request in php.
By default, the $http service will transform the outgoing request by
serializing the data as JSON
Change your $http request to this:
var config = {
method: 'POST',
url: 'modifProfil.php',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $('#formProfil').serialize()
}
$scope.submit = function(){
$http(config).
then(function(response){
console.log(response);
console.log($('#formProfil').serialize());
})
You can also add headers for all $http request like this:
myapp.factory('httpRequestInterceptor', function () {
return {
request: function (config) {
config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
return config;
}
};
});
myapp.config(function ($httpProvider) {
$httpProvider.interceptors.push('httpRequestInterceptor');
});

NodeJS: how to perform Ajax Post with FormData

I am testing a local HTML Form sending data to an aspx application as backend. Since I have some problem with CORS (even on localhost) I am trying to emulate the Ajax request performed by jQuery with NodeJS. I don't know if this is the right way to do. In the HTML form, after the jQuery validation, this is what I do:
submitHandler: function(form) {
$.ajax({
url: form.action,
type: form.method,
data: $(form).serialize(),
success: function(response) {
console.log(response);
}
});
//console.log($(form).serialize())
}
and it works, until CORS ends the request. I mean that I can retrieve the data from the backend application.
Instead, if I do:
function loadDoc() {
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhttp = new XMLHttpRequest();
/*var FormData = require('form-data');
var myform = new FormData();
myform.append('firstname', 'foo');*/
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
};
xhttp.open("POST", "http://127.0.0.1:1308/ImperoOrdini/ImperoOrdini.aspx?CMD=NUOVOORDINE", true);
//which is the same string I get from .serialize() in jQuery
xhttp.send("firstname=foo&email=some#domain.it");
}
loadDoc();
I cannot get anything from the server application. If I want to get the parameter firstname from the POST data, I get null. So, where am I wrong?
UPDATE
This is the only workaround I have found useful in NodeJS:
var http = require('http');
var querystring = require('querystring');
var post_data = querystring.stringify({'firstname':'Lory'});
var post_options = {
host: 'localhost',
port: '1308',
path: '/ImperoOrdini/ImperoOrdini.aspx?CMD=NUOVOORDINE',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(post_data)
}
};
// Set up the request
var post_req = http.request(post_options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('Response: ' + chunk);
});
});
// post the data
post_req.write(post_data);
post_req.end();
I had also tried with:
var request = require('ajax-request');
request.post({
url: 'http://127.0.0.1:1308/ImperoOrdini/ImperoOrdini.aspx?CMD=NUOVOORDINE',
data: {'firstname':'Lory'},
headers: {}
}, function(err, res, body) {
console.log(res);
}
);
but it did not work too. I feel such an ignorant and I would like to know the differences between those 3 libraries.
I have some doubts concerning the fact I must use querystring.stringify() in the working solution, because POST data are not in the URL and should not be uder the limits of query string, if I remember well.
I would like to suggest request module. while doing ajax call post, we can post the data by form or JSON format. It's based on receiver end point how they are receiving.
I hope you are trying to post form data.
var request = require('request');
request.post({
url:'http://service.com/upload',
form: {'firstname':'Lory'}
}, function(err,httpResponse,body){
/* ... */
})
If you are trying to do normal JSON post.
var request = require('request')
request({
method: 'POST',
uri: 'http://www.google.com',
body:{'firstname':'Lory'}
}, function(err,httpResponse,body){
/* ... */
})
request module provide lots of options. Play with that then you will get the better idea.
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
</head>
<body>
<form id="myForm" name="myForm">
<div>
<label for="comment">Comment:</label>
<textarea id="comment" name="comment"></textarea>
</div>
<div>
<label for="rating">Comment:</label>
<textarea id="rating" name="comment"></textarea>
</div>
<input type="submit" value="Submit!">
</form>
<script>
$(document).ready(function () {
$('form').submit(function (event) {
event.preventDefault();
//collect the form data using Id Selector what ever data you need to send to server
let comment=$('#comment').val();
let rating= $('#rating').val()
$.ajax({
url: 'replace your url',
data: JSON.stringify({"comment": comment, "rating": rating }),
processData: false,
type: 'POST',
contentType: 'application/json',
success: function (data) {
alert(data);
}
});
});
})
</script>
</html>

XMLHTTPREQUEST send file and parameters [duplicate]

I'm using jQuery and Ajax for my forms to submit data and files but I'm not sure how to send both data and files in one form?
I currently do almost the same with both methods but the way in which the data is gathered into an array is different, the data uses .serialize(); but the files use = new FormData($(this)[0]);
Is it possible to combine both methods to be able to upload files and data in one form through Ajax?
Data jQuery, Ajax and html
$("form#data").submit(function(){
var formData = $(this).serialize();
$.ajax({
url: window.location.pathname,
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
<form id="data" method="post">
<input type="text" name="first" value="Bob" />
<input type="text" name="middle" value="James" />
<input type="text" name="last" value="Smith" />
<button>Submit</button>
</form>
Files jQuery, Ajax and html
$("form#files").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: window.location.pathname,
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
<form id="files" method="post" enctype="multipart/form-data">
<input name="image" type="file" />
<button>Submit</button>
</form>
How can I combine the above so that I can send data and files in one form via Ajax?
My aim is to be able to send all of this form in one post with Ajax, is it possible?
<form id="datafiles" method="post" enctype="multipart/form-data">
<input type="text" name="first" value="Bob" />
<input type="text" name="middle" value="James" />
<input type="text" name="last" value="Smith" />
<input name="image" type="file" />
<button>Submit</button>
</form>
The problem I had was using the wrong jQuery identifier.
You can upload data and files with one form using ajax.
PHP + HTML
<?php
print_r($_POST);
print_r($_FILES);
?>
<form id="data" method="post" enctype="multipart/form-data">
<input type="text" name="first" value="Bob" />
<input type="text" name="middle" value="James" />
<input type="text" name="last" value="Smith" />
<input name="image" type="file" />
<button>Submit</button>
</form>
jQuery + Ajax
$("form#data").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: window.location.pathname,
type: 'POST',
data: formData,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
});
Short Version
$("form#data").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.post($(this).attr("action"), formData, function(data) {
alert(data);
});
});
another option is to use an iframe and set the form's target to it.
you may try this (it uses jQuery):
function ajax_form($form, on_complete)
{
var iframe;
if (!$form.attr('target'))
{
//create a unique iframe for the form
iframe = $("<iframe></iframe>").attr('name', 'ajax_form_' + Math.floor(Math.random() * 999999)).hide().appendTo($('body'));
$form.attr('target', iframe.attr('name'));
}
if (on_complete)
{
iframe = iframe || $('iframe[name="' + $form.attr('target') + '"]');
iframe.load(function ()
{
//get the server response
var response = iframe.contents().find('body').text();
on_complete(response);
});
}
}
it works well with all browsers, you don't need to serialize or prepare the data.
one down side is that you can't monitor the progress.
also, at least for chrome, the request will not appear in the "xhr" tab of the developer tools but under "doc"
I was having this same issue in ASP.Net MVC with HttpPostedFilebase and instead of using form on Submit I needed to use button on click where I needed to do some stuff and then if all OK the submit form so here is how I got it working
$(".submitbtn").on("click", function(e) {
var form = $("#Form");
// you can't pass Jquery form it has to be javascript form object
var formData = new FormData(form[0]);
//if you only need to upload files then
//Grab the File upload control and append each file manually to FormData
//var files = form.find("#fileupload")[0].files;
//$.each(files, function() {
// var file = $(this);
// formData.append(file[0].name, file[0]);
//});
if ($(form).valid()) {
$.ajax({
type: "POST",
url: $(form).prop("action"),
//dataType: 'json', //not sure but works for me without this
data: formData,
contentType: false, //this is requireded please see answers above
processData: false, //this is requireded please see answers above
//cache: false, //not sure but works for me without this
error : ErrorHandler,
success : successHandler
});
}
});
this will than correctly populate your MVC model, please make sure in your Model, The Property for HttpPostedFileBase[] has the same name as the Name of the input control in html i.e.
<input id="fileupload" type="file" name="UploadedFiles" multiple>
public class MyViewModel
{
public HttpPostedFileBase[] UploadedFiles { get; set; }
}
Or shorter:
$("form#data").submit(function() {
var formData = new FormData(this);
$.post($(this).attr("action"), formData, function() {
// success
});
return false;
});
EDIT: with the new version of JQuery (3.6), you could also try using contentType function argument instead of enctype. Try contentType: multipart/form-data.
For me, it didn't work without enctype: 'multipart/form-data' field in the Ajax request. I hope it helps someone who is stuck in a similar problem.
Even though the enctype was already set in the form attribute, for some reason, the Ajax request didn't automatically identify the enctype without explicit declaration (jQuery 3.3.1).
// Tested, this works for me (jQuery 3.3.1)
fileUploadForm.submit(function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: $(this).attr('action'),
enctype: 'multipart/form-data',
data: new FormData(this),
processData: false,
contentType: false,
success: function (data) {
console.log('Thank God it worked!');
}
}
);
});
// enctype field was set in the form but Ajax request didn't set it by default.
<form action="process/file-upload" enctype="multipart/form-data" method="post" >
<input type="file" name="input-file" accept="text/plain" required>
...
</form>
As others mentioned above, please also pay special attention to the contentType and processData fields.
A Simple but more effective way:
new FormData() is itself like a container (or a bag). You can put everything attr or file in itself.
The only thing you'll need to append the attribute, file, fileName eg:
let formData = new FormData()
formData.append('input', input.files[0], input.files[0].name)
and just pass it in AJAX request. Eg:
let formData = new FormData()
var d = $('#fileid')[0].files[0]
formData.append('fileid', d);
formData.append('inputname', value);
$.ajax({
url: '/yourroute',
method: 'POST',
contentType: false,
processData: false,
data: formData,
success: function(res){
console.log('successfully')
},
error: function(){
console.log('error')
}
})
You can append n number of files or data with FormData.
and if you're making AJAX Request from Script.js file to Route file in Node.js beware of using
req.body to access data (ie text)
req.files to access file (ie image, video etc)
The code below works for me
$(function () {
debugger;
document.getElementById("FormId").addEventListener("submit", function (e) {
debugger;
if (ValidDateFrom()) { // Check Validation
var form = e.target;
if (form.getAttribute("enctype") === "multipart/form-data") {
debugger;
if (form.dataset.ajax) {
e.preventDefault();
e.stopImmediatePropagation();
var xhr = new XMLHttpRequest();
xhr.open(form.method, form.action);
xhr.onreadystatechange = function (result) {
debugger;
if (xhr.readyState == 4 && xhr.status == 200) {
debugger;
var responseData = JSON.parse(xhr.responseText);
SuccessMethod(responseData); // Redirect to your Success method
}
};
xhr.send(new FormData(form));
}
}
}
}, true);
});
In your Action Post Method, pass parameter as HttpPostedFileBase UploadFile and make sure your file input has same as mentioned in your parameter of the Action Method.
It should work with AJAX Begin form as well.
Remember over here that your AJAX BEGIN Form will not work over here since you make your post call defined in the code mentioned above and you can reference your method in the code as per the Requirement
I know I am answering late but this is what worked for me
Just to remind, in 2022 you don't need to use jquery. Try js standard Fetch API
var formData = new FormData(this);
fetch(url, {
method: 'POST',
body: formData
})
.then(response => {
if(response.ok) {
//success
alert(response);
} else {
throw Error('Server error');
}
})
.catch(error => {
console.log('fail', error);
});
This is a solution that I implemented
var formData = new FormData();
var files = $('input[type=file]');
for (var i = 0; i < files.length; i++) {
if (files[i].value == "" || files[i].value == null) {
return false;
}
else {
formData.append(files[i].name, files[i].files[0]);
}
}
var formSerializeArray = $("#Form").serializeArray();
for (var i = 0; i < formSerializeArray.length; i++) {
formData.append(formSerializeArray[i].name, formSerializeArray[i].value)
}
$.ajax({
type: 'POST',
data: formData,
contentType: false,
processData: false,
cache: false,
url: '/Controller/Action',
success: function (response) {
if (response.Success == true) {
return true;
}
else {
return false;
}
},
error: function () {
return false;
},
failure: function () {
return false;
}
});
---Solution for DOT NET CORE MVC Implementation---
While looking at this question I though I should right .NET CORE implementation for this because the question is not specific to any backend language.
So guys here is the standalone implementation example.
Objective :- To submit form fields including files and how we can get data in a single model at backend
HTML Code / View Code - Views/Home/Index.cshtml
#{
ViewData["Title"] = "Home Page";
}
<input type="file" id="FileUpload1" multiple />
<div>
<label>Enter First Name :</label>
<input type="text" id="nameText" maxlength="50" />
</div>
<input type="button" id="btnUpload" value="Submit Form with Files" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function () {
$('#btnUpload').click(function () {
// Checking whether FormData is available in browser
if (window.FormData !== undefined) {
var fileUpload = $("#FileUpload1").get(0);
var files = fileUpload.files;
// Create FormData object
var fileData = new FormData();
// Looping over all files and add it to FormData object
for (var i = 0; i < files.length; i++) {
fileData.append("files", files[i]);
}
// Adding one more key to FormData object
fileData.append('FirstName', $("#nameText").val());
$.ajax({
url: '/Home/UploadFiles',
type: "POST",
contentType: false, // Not to set any content header
processData: false, // Not to process data
data: fileData,
success: function (result) {
alert(result);
},
error: function (err) {
alert(err.statusText);
}
});
} else {
alert("FormData is not supported.");
}
});
});
</script>
Backend Code / Controller action method Controllers/HomeController.cs
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly IWebHostEnvironment _environment;
public HomeController(ILogger<HomeController> logger, IWebHostEnvironment environment)
{
_logger = logger;
_environment = environment;
}
public IActionResult Index()
{
return View();
}
public IActionResult Privacy()
{
return View();
}
[HttpPost]
public async Task<IActionResult> UploadFiles(MyForm myForm)
{
var files = myForm.Files;
// First Name
string name = myForm.FirstName;
// check All files
foreach (IFormFile source in files)
{
string filename = ContentDispositionHeaderValue.Parse(source.ContentDisposition).FileName.Trim('"');
filename = this.EnsureCorrectFilename(filename);
string fileWithPath = this.GetPathAndFilename(filename);
// Create directory if not exist
Directory.CreateDirectory(Path.GetDirectoryName(fileWithPath));
using (FileStream output = System.IO.File.Create(fileWithPath))
await source.CopyToAsync(output);
}
return Ok("Success");
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
public class MyForm
{
public string FirstName { get; set; }
public IList<IFormFile> Files { get; set; }
}
private string EnsureCorrectFilename(string filename)
{
if (filename.Contains("\\"))
filename = filename.Substring(filename.LastIndexOf("\\") + 1);
return filename;
}
private string GetPathAndFilename(string filename)
{
return Path.Combine(_environment.ContentRootPath, "uploadedFiles", filename);
}
}
Full Source Code Repo: https://github.com/rj-learning/DotNetCoreFileUpload
In my case I had to make a POST request, which had information sent through the header, and also a file sent using a FormData object.
I made it work using a combination of some of the answers here, so basically what ended up working was having this five lines in my Ajax request:
contentType: "application/octet-stream",
enctype: 'multipart/form-data',
contentType: false,
processData: false,
data: formData,
Where formData was a variable created like this:
var file = document.getElementById('uploadedFile').files[0];
var form = $('form')[0];
var formData = new FormData(form);
formData.append("File", file);
you can just append them on your formdata, add your files and datas in it.you can read this..
https://developer.mozilla.org/en-US/docs/Web/API/FormData/append
for better understanding. you can separately retrieve them $_FILES for your files and $_POST for your data.
<form id="form" method="post" action="otherpage.php" enctype="multipart/form-data">
<input type="text" name="first" value="Bob" />
<input type="text" name="middle" value="James" />
<input type="text" name="last" value="Smith" />
<input name="image" type="file" />
<button type='button' id='submit_btn'>Submit</button>
</form>
<script>
$(document).on("click", "#submit_btn", function (e) {
//Prevent Instant Click
e.preventDefault();
// Create an FormData object
var formData = $("#form").submit(function (e) {
return;
});
//formData[0] contain form data only
// You can directly make object via using form id but it require all ajax operation inside $("form").submit(<!-- Ajax Here -->)
var formData = new FormData(formData[0]);
$.ajax({
url: $('#form').attr('action'),
type: 'POST',
data: formData,
success: function (response) {
console.log(response);
},
contentType: false,
processData: false,
cache: false
});
return false;
});
</script>
///// otherpage.php
<?php
print_r($_FILES);
?>

Categories

Resources