I want to upload file using Struts2, but without refreshing page.
How can I use AJAX for this solution.
$.ajax({
url:"strutsaction",
type : 'POST',
async: false,
});
What should I write for data and contentType in ajax request ?
jsp code:
<s:form action="strutsaction" method="post" enctype="multipart/form-data">
<s:file name="imgFileUpload" label="Choose file to upload" accept="image/*"></s:file>
<s:submit value="Upload" align="center"></s:submit>
</s:form>
Hi the below code is working for me. I hope it will help you.
JSP Code:
<div id="uploadImg">
<s:form id="uploadImgForm" action="strutsaction" method="post" enctype="multipart/form-data">
<s:file name="imgFileUpload" label="Choose file to upload" accept="image/*"></s:file>
<s:submit value="Upload" align="center" id="uploadImgSubmitBtn"></s:submit>
</s:form>
<div>
JQuery:
$("#uploadImgSubmitBtn").click(function(e){
// Get form
var form = $('#uploadImgForm')[0];
// Create an FormData object
var data = new FormData(form);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "strutsaction.action",
data : data,
cache: false,
processData: false,
contentType: false,
success: function(data){
$('#uploadImg').html(data);
}
});
});
Related
EasyUi combtree dose't working inside the form tag, It's fine other than form tag
Mark Up
<form>
<div class="form-group">
<label for="searchfolder"><?php echo \Application\Plugin\Common::z_xlt('Move to Category'); ?></label>
<div class="custom-dropdownclass custom-documents">
<inputclass="form-control easyui-combotree " ng-value="currentdocument.category" data- realcatcode="{{currentdocument.category}}" name="parent" id ="searchfolder" data- options="input:searchfolder">
</div>
</div>
<form>
Script
$http({
method: 'post',
url: basePath + '/documents/documents/ajax',
data: data
}).then(function(response) {
$('#searchfolder').combotree('loadData', $scope.getDirectTreeComboData(response.data.directorytree));
$('#newfolder_parent').combotree('loadData',
$scope.getDirectTreeComboData(response.data.directorycombotree));
});
Error Image of console error
I have installed programr. I followed tutorial from this site http://dreamingechoes.github.io/bot/ruby/rails/conversational-bot-ruby-on-rails/
bot.rb
require 'programr'
brains = Dir.glob("lib/bot/*")
BOT = ProgramR::Facade.new
BOT.learn(brains)
application_controller.rb
def ask_bot
reaction = BOT.get_reaction(params[:query])
render json: { response: reaction.present? ? reaction : "I don't have an answer to that" }
end
bot.aiml
<?xml version="1.0" encoding="UTF-8"?>
<aiml version="1.0" xmlns="http://alicebot.org/2001/AIML-1.0.1"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://alicebot.org/2001/AIML-1.0.1 http://aitools.org/aiml/schema/AIML.xsd">
<category>
<pattern>Hello *</pattern>
<template>
Hey, how can I help you?
</template>
</category>
<category>
<pattern>*bye</pattern>
<template>
Always here for you!
</template>
</category>
<category>
<pattern>What payment methods do you accept?</pattern>
<template>
We accept Visa, MasterCard and American Express.
</template>
</category>
</aiml>
view:
<div class="alert alert-info">
×
<strong>Info!</strong> Type something on the text input and hit the <strong>GO</strong> button to get a response.
</div>
<div class="bs-callout bs-callout-info bot-response hide" id="callout-alerts-no-default">
<h4>Bot says:</h4>
<p id="bot-response"> </p>
</div>
<div class="row home-row">
<div class="col-lg-12">
<div class="input-group">
<input id="query" type="text" class="form-control" placeholder="Say something to the bot...">
<span class="input-group-btn">
<button id="ask" class="btn btn-default" type="button">GO</button>
</span>
</div>
</div>
</div>
application.js
$(document).ready(function(){
$('#ask').on('click', function(event) {
$.ajax({
url: '/ask_bot',
type: 'json',
method: 'get',
data: { query: $('#query').val() },
success: function(data) {
$('.bot-response').removeClass('hide');
$('#bot-response').html(data['response']);
$('#query').val('');
}
});
});
});
If i copy a pattern and paste in the form, the GO button does nothing. Please help...thanks!
Most probably what you'll have to use is the DOMContentLoaded in order to check when the DOM has finished loading, this way you can wrap the listener for the #ask button and the AJAX function, without having to modify your "requires" in the application.js file, nor to have to include them as script tags in your views.
You could try with something like:
document.addEventListener('DOMContentLoaded', function () {
...
});
And inside to put your JS code, which would remain as:
document.addEventListener('DOMContentLoaded', function () {
$('#ask').on('click', function(event) {
$.ajax({
url: '/ask_bot',
type: 'json',
method: 'get',
data: { query: $('#query').val() },
success: function(data) {
$('.bot-response').removeClass('hide');
$('#bot-response').html(data['response']);
$('#query').val('');
}
});
});
$('[data-toggle="tooltip"]').tooltip();
});
Also you could add the specific custom.js for the specific controller and action in which is being used, that's the reason of the Uncaught TypeError: Cannot read property 'getContext' of null error, because such elements barChart and barChart2 are in the back_office#index.
I am a newbie and tried to do the laziest way to do a file upload using emberjs, jquery and formdata(IE10+). The code might look stupid, but it worked.
Here is what i got. Can you please take a look and give some suggestions. Am i doing it wrong?
<script type="text/x-handlebars" data-template-name="posts">
<form role="form" enctype="multipart/form-data" method="post" id="fileinfo" {{action 'createPost' on='submit'}}>
{{input type="text" value=newPost id="newPost" placeholder="Post" class="form-control"}}
{{input type="file" id="inputFile" class="form-control" name="file"}}
<button type="submit" class="btn btn-default" >Submit</button>
</form>
</script>
App.PostsController = Ember.ArrayController.extend({
actions: {
createPost: function(){
var fd = new FormData(document.getElementById("fileinfo"));
fd.append("postContent", this.get('newPost'));
this.set('newPost', ''); //reset text field
$('#inputFile').val(''); //reset fileinput field
Ember.$.ajax({
url: "http://localhost:3000/posts",
type: "POST",
data: fd,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
});
}
}
});
I've been tried this for days. Assuming I have a form like following:
<form ng-submit="create()" class="form-horizontal" enctype="multipart/form-data">
<div class="control-group">
<label class="control-label">name : </label>
<div class="controls">
<input type="text" class="input-xlarge" ng-model="message.title" />
</div>
</div>
<div class="control-group">
<label class="control-label">avatar : </label>
<div class="controls">
<input type="file" ng-model="message.avatar" name="message[avatar]" />
</div>
</div>
<div class="well">
<input class="btn btn-large btn-primary" type="submit" value="建立資料" />
</div>
</form>
I am using the carrierwave gem to handle the file upload behind the scene. My controller is like this:
$scope.create = function($scope.message){
var deferred = $q.defer();
$http({
method: 'POST',
url: '/resources/messages',
data: $.param({message: message}),
headers: {'Content-Type': 'multipart/form-data'}
}).
success(function(data, status, headers, config){
deferred.resolve(data);
}).
error(function(data, status, headers, config){
deferred.reject(status);
});
return deferred.promise;
};
However it is not working. What I intend to do is create a form and upload everything like the old way, but the examples I found such as ng-upload, or like this post, or jquery file upload, they don't suit my need. Is there any example or sample code for this purpose? Thank you.
I think "like the old way" would be to not use Ajax, but I'm guessing that's not what you mean. :)
#shaunhusain's fiddle is a good example of how to use the FormData object to handle the file upload. And using this site as a reference, you can use the transformRequest to incorporate the FormData object.
Keeping your basic $http code, modify it to add the transform object:
$scope.create = function(message){
var deferred = $q.defer();
$http({
method: 'POST',
url: '/resources/messages',
data: message // your original form data,
transformRequest: formDataObject // this sends your data to the formDataObject provider that we are defining below.
headers: {'Content-Type': 'multipart/form-data'}
}).
success(function(data, status, headers, config){
deferred.resolve(data);
}).
error(function(data, status, headers, config){
deferred.reject(status);
});
return deferred.promise;
};
Create a factory that will incorporate manipulate the form data into a sendable payload. It will iterate through your form data (including uploaded file) and return a sender-friendly object:
app.factory('formDataObject', function() {
return function(data) {
var fd = new FormData();
angular.forEach(data, function(value, key) {
fd.append(key, value);
});
return fd;
};
});
I haven't tested this, but it should work out of the box.
I'm doing an xhr file upload using dojo.io.iframe.send and it works fine in all browsers except IE 8. IE8 sends a GET request instead of a multipart POST. This is my code:
dojo.io.iframe.send({
form: this.logoForm.domNode,
handleAs: "json",
method: "POST",
url: '/backend/design/uploadLogo',
load: dojo.hitch(this, function(response) {
if (response.error) {
errorFunc(response);
} else {
this.submitStatusLogo.innerHTML = "Your logo has been successfully uploaded.";
this.logoButton.hideIndicator();
dojo.addClass(this.submitStatusLogo, "success");
if (response.logoPath) {
this.productLogo.innerHTML = '<img src="'+response.logoPath+'" alt="" />';
}
}
}),
error: errorFunc
});
And this.logoForm.domNode is:
<form dojoAttachPoint="logoForm" dojoType="dijit.form.Form" enctype="multipart/form-data" class="designLayoutForm">
<div class="uploadedImage" dojoAttachPoint="productLogo"></div>
<h2>Logo
<span dojoType="sc2.common.TinyHelp" title="Logo">
Upload a product logo that will be shown in the top left of the demo page.<br />
If the logo is higher than 80 pixels, it will be resized to a height of 80px. <br />
<br />
<i>Supported file types are: png, jpg, gif, bmp.</i>
</span>
</h2>
<p>
<input type="hidden" dojoAttachPoint="logoForm_product" name="product" value="" />
<input type="hidden" dojoAttachPoint="logoForm_XSessionVerify" name="X-Session-Verify" value="" />
<input type="file" name="file" dojoAttachPoint="logoInput" />
</p>
<p dojoAttachPoint="submitStatusLogo" class="submitStatus"></p>
<p>
<input dojoType="sc2.form.IndicatorButton" dojoAttachPoint="logoButton" label="Upload">
</p>
</form>
What am I doing wrong?
Okay I solved it, adding method="POST" to the form element did the trick. Apparently specifying method: "POST" in the send parameters was not sufficient for IE8. Thanks for your time anyway