If I upload a PDF or a picture to the form, I get the following error message when changing to another form field:
The upload function is done using the following JavaScript:
;(function($,window) {
$.plugin('OnacyUpload', {
defaults: {
fileUpload: '#register_license_upload',
fileText: '.register-upload-file-text',
registerContent: '.register--content.registration-upload-finished',
registerLogin: '.register--login',
sidebar: 'aside.sidebar-main',
breadcrumb: 'nav.content--breadcrumb'
},
init: function() {
var me = this;
me._on(me.opts.fileUpload, 'change', $.proxy(me.onUploadChange, me));
me._on(me.opts.fileText, 'click', $.proxy(me.fileTextClicked, me));
if ( $(me.opts.registerContent).length ) {
$(me.opts.registerLogin).remove();
$(me.opts.sidebar).remove();
$(me.opts.breadcrumb).remove();
}
},
fileTextClicked: function() {
$(me.opts.fileUpload).trigger('click');
},
onUploadChange: function(event) {
var me = this,
$target = $(event.target),
$fileText = $(me.opts.fileText),
value = $target.val();
if ( typeof value !== 'string' || value === '' ) {
$fileText.html($fileText.attr('data-no-file-text'));
}
else {
var list = value.replace(/\\/g, '/').split('/');
$fileText.html(list[list.length-1]);
}
}
});
window.StateManager.addPlugin('body', 'OnacyUpload');
Here is the HTML Part:
<div class="panel--body is--wide"> <input type="file" id="register_license_upload" name="register_license_upload" accept="image/png, image/jpeg, application/pdf"> <label for="register_license_upload" class="btn is--secondary"> Datei aussuchen </label> <span class="register-upload-file-text" data-no-file-text="Datei wählen"> Datei wählen </span> </div>
Related
I have a defined a file upload field but the issue here is I am able to submit the form even if I have not selected a file. Please help me figure out how to through an error that no file is selected on clicking on the submit button if no file is selected. I am using vuetify version 1.0.
<template>
<v-form :model='agency' ref='AgencyForm'>
<div class="vue-file-wrapper">
<input
type="file"
ref="file"
name="vue-file-input"
required
:rules='uploadDocument'
#change="onFileSelected"
>
</div>
<v-btn #click.prevent='submit'>Save</v-btn>
</v-form>
</template>
<script>
export default {
props: ['agency'],
data: function () {
return {
filename: '',
uploadDocument: [
value => !!value || 'Please upload document'
],
}
}
methods: {
onFileSelected(event) {
var files = event.target.files || event.dataTransfer.files;
if (!files.length) {
return;
}
this.createImage(files[0]);
},
createImage(file) {
var fileReader = new FileReader(),
that = this;
fileReader.onload = function(event) {
that.agency.document = event.target.result;
that.agency.filename = file.name;
that.filename = file.name;
};
fileReader.readAsDataURL(file);
},
submit() {
if (this.$refs.AgencyForm.validate()) {
this.$axios.put('/agency.json', { agency: this.agency })
}
</script>
I can see some issues with your current implementation. Firstly, you are directly mutating a prop agency, which isn't a good practice. Also, you aren't waiting for your axios request to complete on submission.
However, for your current situation of not having an error thrown when no file is selected on clicking on the submit button, I think the issue is a syntax problem.
You currently have
<div class="vue-file-wrapper">
<input
type="file"
ref="file"
name="vue-file-input"
required
:rules='uploadDocument'
#change="onFileSelected"
>
According to the documentation, it should be
<v-file-input
:rules="uploadDocument"
#change="onFileSelected"
>
</v-file-input>
You can then leave the data property as it was
data: function () {
return {
filename: '',
uploadDocument: [
value => !!value || 'Please upload document'
],
}
}
EDIT -- since in Vuetify 1.0.5, there's no support for v-file-input, from this Github issue, you can do this
<template>
<div>
<v-text-field prepend-icon="attach_file" single-line
v-model="filename" :label="label" :required="required"
#click.native="onFocus"
:disabled="disabled" ref="fileTextField"></v-text-field>
<input type="file" :accept="accept" :multiple="false"
ref="file" #change="onFileSelected">
</div>
</template>
Your data property now becomes
data: function () {
return {
filename: '',
uploadDocument: [
value => !!value || 'Please upload document'
],
errors: {
file: ''
}
}
}
You can then style the text field using SCSS/CSS to be below the file input field or something.
One thing is for sure, the rules prop will not work on a input element because it's reserved for vuetify specific elements.
It won't be triggered by this.$refs.AgencyForm.validate() for that very reason. You will have to write custom validation
Maybe something along the lines of
methods: {
validateFile(file) {
if (!file.name) {
errors.file = 'Please select a file';
} else {
errors.file = '';
}
}
atLeastOneErrorExists(errors) {
return Object.values(errors).some(error => error.length > 0)
}
onFileSelected(event) {
var files = event.target.files || event.dataTransfer.files;
if (!files.length) {
return;
}
var file = files[0];
this.filename = file.name;
this.createImage(files[0]);
},
submit() {
this.validateFile(this.filename);
if (this.atLeastOneErrorExists(this.errors)) {
this.$axios.put('/agency.json', { agency: this.agency })
}
}
}
In your template, you can simulate the error message of Vuetify by styling a p tag that looks similar to Vuetify error messages
Something like
<div class="vue-file-wrapper">
...
<input
...
>
<p class="custom-error-class">{{errors.file}}</p> // custom error message
</div>
I make a web form to add some string to database and now my add function is running perfectly but my web does not send params to function when i click submit and console log send undefined to me i dont know what to do please help and thank you
Here my function code and run perfectly
Parse.Cloud.define('addSynonym', function (request, response) {
var SYN = Parse.Object.extend("Synonym");
var CommonwordFromUser = request.params.common_word;
var SynonymwordFromUser = request.params.synonym_word;
console.log(CommonwordFromUser);
console.log(SynonymwordFromUser);
if (CommonwordFromUser == null || SynonymwordFromUser == null) {
response.error("request null values");
} else {
var query = new Parse.Query(SYN)
query.find({
success: function (synResponse) {
var synOBJ = new SYN();
synOBJ.set("common_word", CommonwordFromUser);
synOBJ.set("synonym_word", SynonymwordFromUser);
synOBJ.save(null, {
success: function (success) {
response.success({
"common_word": CommonwordFromUser,
"synonym_word": SynonymwordFromUser
});
},
error: function (error) {
response.error("save failed : " + error.code);
}
});
}
})
}
});
Here my web form my problem
<form id="contact" class="registerForm">
<div class="alert alert-success" id="alertbox">
<strong>Success!</strong> Your Synonym has uploaded.
</div>
<div class="text-center">
<img src="img/icon.png" class="text-center" alt="Responsive image" width="90" height="90">
</div>
<h3 class="text-center font-weight-normal">Welcome to synonym Menu</h3>
<label id="label-tags" for="ask-tags">Common Word :</label>
<fieldset class="form-group">
<input id="common_word" name="common_word" placeholder="Please type some word" type="text" tabindex="1" required>
</fieldset>
<label id="label-tags" for="ask-tags">Synonym Word :</label>
<fieldset class="form-group">
<input id="synonym_word" name="synonym_word" placeholder="Please type some word" type="text" tabindex="2"
required>
</fieldset>
<fieldset class="form-group">
<button name="submit" type="submit" onclick="submitfrom()" id="contact-submit">Submit</button>
</fieldset>
</form>
</div>
<!-- jQuery -->
<script src="js/jquery.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js"></script>
<script src="js/standalone/selectize.min.js"></script>
<script src="js/bootstrapValidator.min.js"></script>
<script>
$('.registerForm').bootstrapValidator({
message: 'This value is not valid',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
common_word: {
validators: {
notEmpty: {
message: 'Require !!'
}
}
},
synonym_word: {
validators: {
notEmpty: {
message: 'Require !!'
}
}
},
}
}).on('success.form.bv', function (e) {
submitfrom();
});
$('#alertbox').hide();
function submitfrom() {
var common_word = $('#common_word').val();
var synonym_word = $('#synonym_word').val();
var obj = [{
"common_word": common_word,
"synonym_word": synonym_word,
}];
var data = '{"objects":' + JSON.stringify(obj) + '}';
callParseServerCloudCode("addSynonym", data, function (response) {
if (response) {
console.log(response);
alert("🤖:Ok !");
location.reload();
}
});
$(this).scrollTop(0);
$('.registerForm').data('bootstrapValidator').resetForm();
$('#alertbox').show();
$('#alertbox').fadeTo(2000, 500).slideUp(500, function () {
$('#alertbox').hide();
});
}
function callParseServerCloudCode(methodName, requestMsg, responseMsg) {
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://xxxxxxxxxxxx.herokuapp.com/parse/functions/' + methodName, true);
xhr.setRequestHeader('Content-type', 'application/json');
xhr.setRequestHeader('X-Parse-Application-Id', 'myAppId');
xhr.setRequestHeader('X-Parse-Master-Key', 'myMasterKey');
xhr.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
responseMsg(myArr.result);
}
};
xhr.send(requestMsg);
}
</script>
</body>
</html>
Option 1:
Just change the lines below and it should work
var obj = {
"common_word": common_word,
"synonym_word": synonym_word,
};
var data = JSON.stringify(obj);
Option 2 (recommended):
Install Parse JS SDK: https://docs.parseplatform.org/js/guide/#getting-started
Call cloud code like this:
Parse.Cloud.run(
"addSynonym",
{
"common_word": common_word,
"synonym_word": synonym_word
}
).then(
function() {
console.log('success');
},
function (error) {
console.error(error);
}
);
I am having trouble actioning a callback function in one of my React classes. Basically I call checkSource on click and then if it meets a specific requirement I want to call handleSubmitClick. I have a feeling this has to do with me calling this.handleSubmitClick, but I don't understand. My understanding is that the this is referring to the component object that I created. If this is the case, shouldn't it just call that function and execute?
The full component is here:
var React = require('react');
module.exports = React.createClass({
getInitialState: function() {
return {
text: ''
}
},
handleTextInput: function(event){
this.setState({text: event.target.value})
},
checkSource: function(){
var clientId = 'xxxx';
var resolve = 'http://api.soundcloud.com/resolve?url=';
$.get(resolve + this.state.text + '&client_id=' + clientId, function(data) {
$.get('http://api.soundcloud.com/users/' + data.user.id + '/?client_id=' + clientId, function(data) {
if(data.followers_count < 3000) {
console.log("handleSubmitClick now");
this.handleSubmitClick();
} else {
return false;
}
});
});
},
handleSubmitClick: function() {
console.log('handleSubmitClick going')
console.log(this.state.text)
var linkStore = this.props.linkStore
linkStore.push(this.state.text)
this.setState({text: ''})
this.props.handleListSubmitClick(linkStore)
console.log(this.props.linkStore)
},
render: function() {
return <div className="row">
<div className="col-md-8 col-md-offset-2">
<div className="text-center">
<h1>Soundcloud3k</h1>
</div>
<div className="input-group">
<input
onChange = {this.handleTextInput}
type="text"
className="form-control"
placeholder="Search fr..."
value={this.state.text} />
<span className="input-group-btn">
<button
onClick={this.checkSource}
className="btn btn-default"
type="button">Submit!</button>
</span>
</div>
</div>
</div>
}
});
This is the render function with the checkSource call
The console logs for the checkSource function works as intended, but I can't get the handleSubmitClick to do anything. I don't get an error or anything in the console. Any ideas?
In $.get callback this does not refer to your component, you should set this for each callback. Also return false in ajax callback does not make sense so you can remove it
checkSource: function(){
var clientId = 'xxxx';
var resolve = 'http://api.soundcloud.com/resolve?url=';
$.get(resolve + this.state.text + '&client_id=' + clientId, function(data) {
$.get('http://api.soundcloud.com/users/' + data.user.id + '/?client_id=' + clientId, function(data) {
if(data.followers_count < 3000) {
this.handleSubmitClick();
}
}.bind(this));
}.bind(this));
},
I'm wondering if this is possible or not. When the user hits the save button, I want knockout to check if the field labeled Status has been changed to Completed - then I want it to enter the current date into the Date Completed field.
Here are my fields -
<ul class="button-group">
<li><button data-bind="click: save" class="success">Save</button></li>
<li><button data-bind="click: saveAndClose" class="success">Save and close</button></li>
<li><button data-bind="click: cancel" class="alert">Cancel</button></li>
</ul>
<div data-bind="with: item">
<label for="Type">Type</label>
<input id="Type" data-bind="value: Type" disabled="disabled" type="text" />
<label for="Status">Status</label>
<select id ="Status" data-bind="value: Status">
<option value="Not Started">Not Started</option>
<option value="In Progress">In Progress</option>
<option value="Completed">Completed</option>
</select>
<label for="Subject">Subject</label>
<input id="Subject" data-bind="value: Subject" type="text"/>
<label for="Content">Content</label>
<textarea id="Content" data-bind="value: Content" type="text"></textarea>
label for="DateCreated">Date Created (DD/MM/YYYY)</label>
<input id="DateCreated" disabled data-bind="valueFormat: DateCreated, type: 'datetime', format: 'DD/MM/YYYY'" type="text" placeholder="Enter date in format DD/MM/YYYY" />
<label for="DateLastModified">Date Last Modified (DD/MM/YYYY)</label>
<input id="DateLastModified" data-bind="valueFormat: DateLastModified, type: 'datetime', format: 'DD/MM/YYYY'" type="text" placeholder="Enter date in format DD/MM/YYYY" />
<label for="DateCompleted">Date Completed (DD/MM/YYYY)</label>
<input id="DateCompleted" data-bind="valueFormat: DateCompleted, type: 'datetime', format: 'DD/MM/YYYY'" type="text" placeholder="Enter date in format DD/MM/YYYY" />
</div>
And heres what my js file consists of so far
var Module = function(){
var self = this;
var updateItem = function(item) {
if (item) {
self.setupEntityValidation(item, self);
self.item(item);
}
};
self.title = ko.observable();
self.item = ko.observable();
self.isLoadingData = ko.observable(true);
self.entityName = 'Task';
self.entityId = null;
self.activate = function(cid, idOrNew, newType) {
var loadedItem,
types = {
task: {
type: 'Task',
newStatus: 'Not Started'
},
phone: {
type: 'Phone',
newStatus: 'Completed'
},
email: {
type: 'Email',
newStatus: 'Completed'
},
note: {
type: 'Note',
newStatus: 'Completed'
}
},
now = null,
mode = 'new' === idOrNew ? 'Create new' : 'Edit';
// Page title
self.entityId = 'new' === idOrNew ? 0 : parseInt(idOrNew);
self.title(mode + ' task');
if ('new' !== idOrNew) {
// Load the item
self.isLoadingData = ko.observable(true);
ds.getEntityWithKey('Task', self.entityId)
.then(function(data) {
if (data && data.entity) {
// Load item
updateItem(data.entity);
} else {
log.error('#todo get by id failed with result', data);
}
})
.fail(function(err) {
log.error('#todo get by id failed completely', err.stack);
})
.finally(function() {
self.isLoadingData(false);
});
} else {
// No id, create new. Check newType is valid
if (types.hasOwnProperty(newType)) {
// Create new task
now = new Date();
loadedItem = ds.createEntity('Task', {
CentreID: parseInt(cid),
Type: types[newType].type,
Status: types[newType].newStatus,
DateCreated: now.toISOString()
});
if (loadedItem) {
updateItem(loadedItem);
} else {
log.error('Could not create new task item');
}
} else {
log.error('Cannot create new task, illegal type:' + newType);
}
self.isLoadingData(false);
}
};
};
var moduleInstance = new Module();
modex.addComponent('EntitySaveCancel', moduleInstance);
modex.addComponent('EntityValidation', moduleInstance);
return moduleInstance;
});
If you want to instantly apply the change when the field changes to "Completed" you can add a subscribe function that watches the observable "Status" for any change:
self.Status.subscribe(function (value) {
if (value === "Completed") {
//Change date here.
}
});
If you want to change it upon clicking save, you can check "Status" observable value there and set the date accordingly.
Please let us know if this works with you.
I am still new to AJAX and struggling a bit with form validation before uploading files to the server side using cgi-bin and IFrame.
So, my code is as below:
HTML:
<body>
<h1 align="center">Network Failure Detection</h1>
<form id="input" action= "../cgi-bin/test.py" method="post">
<div id = "table">
<table class = "center" border="1" cellpadding="10">
<tr><td style="height: 131px">Product Details</td>
<td style="height: 131px">Product Name*: <input type="text" name="product" id="product" size="35" ><br /><br />
Platform*: <input type="text" name="platform" id="platform" size="35" >
</td></tr>
<tr><td style="height: 131px">File Upload</td>
<td style="height: 131px"><p>Upload Host File: <input type="file" name="hostupload" id = "hostupload"/></p><br/>
Upload Test File: <input type="file" name="testupload" id = "testupload"/></p>
</td></tr>
<tr align="center"><td></td><td><input type = "submit" id="submit" value = "UPLOAD"/>
</td></tr>
</table>
</div>
</form>
<div id="output"></div>
JS:
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>
<script>
$.fn.ajaxForm = function(options) {
options = $.extend({}, {
onSubmit:function() {},
onResponse:function(data) {}
}, options);
var iframeName = 'ajaxForm', $iframe = $('[name=' + iframeName + ']');
if (!$iframe.length) {
$iframe = $('<iframe name=' + iframeName + ' style="display:none">').appendTo('body');
}
return $(this).each(function() {
var $form = $(this);
$form
.prop('target', iframeName)
.prop('enctype', 'multipart/form-data')
.prop('encoding', 'multipart/form-data')
.submit(function(e) {
options.onSubmit.apply($form[0]);
$iframe.one('load', function() {
var iframeText = $iframe.contents().find('body').text();
options.onResponse.apply($form[0], [iframeText]);
});
});
});
};
$('#input').ajaxForm({
onResponse:function(data) {
alert(data);
//console.log("the data is"+data);
//$('#output').html(data);
}
});
This code works fine, and I can upload files and my text box fields. But I want to perform validation on the form for empty fields before submitting, so I tried to use the JQuery validate plugin, but my form does not submit through AJAX if I do so. Can anybody please tell me how I can perform form validation here?
The below javascript code does not submit form through AJAX:
<script>
$.fn.ajaxForm = function(options) {
$('#upload').validate({
rules: {
product: {
required: true,
},
platform: {
required: true,
},
hostupload:{
required: true,
},
testupload:{
required: true,
},
},
messages: {
product: {
required: '***Product Name Required***'
},
platform: {
required: '***Platform Required***'
},
hostupload:{
required: '***Hostfile Required***'
},
testupload:{
required: '***Testfile Required***'
},
},
options = $.extend({}, {
onSubmit:function() {},
onResponse:function(data) {}
}, options);
var iframeName = 'ajaxForm', $iframe = $('[name=' + iframeName + ']');
if (!$iframe.length) {
$iframe = $('<iframe name=' + iframeName + ' style="display:none">').appendTo('body');
}
return $(this).each(function() {
var $form = $(this);
$form
.prop('target', iframeName)
.prop('enctype', 'multipart/form-data')
.prop('encoding', 'multipart/form-data')
.submit(function(e) {
options.onSubmit.apply($form[0]);
$iframe.one('load', function() {
var iframeText = $iframe.contents().find('body').text();
options.onResponse.apply($form[0], [iframeText]);
});
});
});
});
};
$('#input').ajaxForm({
onResponse:function(data) {
alert(data);
//console.log("the data is"+data);
//$('#output').html(data);
}
});