I have some code that opens a modal that contains a form when a marker is placed on a layer in leaflet. It all worked well with out any issues. I copied this code so I could make a second button to control the opening of another modal containing a different form. I changed the link information but when the button is clicked the
L.DomEvent.on(link, 'click', L.DomEvent.stop)
.on(link, 'click', L.bind(this.startCreating, this));
Opens up both forms at the same time or opens one then when closed and clicked againit will open both. Im not sure whats going on because each modal has a different ID.
Here is a live example of the map with the modals. Click the small elements/buttons on the left under the zoom control and drag the new market and click again to set its place on the map.
Leaflet Map with modals
Here is the JS code that should call the first modal called eventDataModal. The main link in the code is near the top:
L.MarkerControl = L.Control.extend({
options: {
position: 'topleft',
url: 'http://echostorm.mynetgear.com:8080/geoserver/usa/ows',
userName: 'wfspost',
password: 'createfeature'
},
map: null,
marker: null,
binded: false,
onAdd: function (map) {
this.map = map;
var container = L.DomUtil.create('div', 'leaflet-control leaflet-bar'),
// link = L.DomUtil.create('a', 'glyphicon glyphicon-map-marker', container);
link = L.DomUtil.create('a', 'glyphicon glyphicon-eye-open', container);
link.href = '#';
link.title = 'Create a new visual report';
link.innerHTML = '';
L.DomEvent.on(link, 'click', L.DomEvent.stop)
.on(link, 'click', L.bind(this.startCreating, this));
map.on("editable:drawing:commit", L.bind(this.onMarkerAdd, this));
return container;
},
startCreating: function() {
this.marker = this.map.editTools.startMarker();
},
onMarkerAdd: function(e) {
this.nearestFeature = null;
this.findNearestPoints(e.layer.getLatLng());
},
onFormClosed: function() {
if (this.marker!=null) {
this.map.editTools.featuresLayer.removeLayer(this.marker);
this.marker = null;
}
},
findNearestPoints: function(latlng) {
var defaultParameters = {
service: 'WFS',
version: '1.0.0',
request: 'GetFeature',
typeName: 'usa:within5mi',
maxFeatures: 5,
outputFormat: 'text/javascript',
format_options: 'callback: nearestPoints',
srsName: 'EPSG:4326',
viewparams: 'radius:802;lon:'+latlng.lng+';lat:'+latlng.lat,
};
var parameters = L.Util.extend(defaultParameters);
$.ajax({
jsonp: false,
url: this.options.url + L.Util.getParamString(parameters),
dataType: 'jsonp',
jsonpCallback: 'nearestPoints',
success: L.bind(this.handleNearestPoints, this)
});
},
handleNearestPoints: function(data) {
this.clearModal();
this.setModalDate();
if (data && data.type=="FeatureCollection"
&& data.features && data.features.length
&& data.features.length > 0) {
this.fillModal(data.features[0]);
}
this.openPopup();
},
formatDate: function(date) {
var day = date.getDate();
return date.getFullYear()+"-"+(date.getMonth()+1)+"-"+(day < 10 ? "0"+day : day);
},
clearModal: function() {
$('#eventDataModal').find('input').each(
function() {
$(this).val("");
}
);
$('#eventDataModal').find('textarea').each(
function() {
$(this).val("");
}
);
},
setModalDate: function() {
$("#form-patrolDate").val(this.formatDate(new Date()));
},
fillModal: function(feature) {
var props = feature.properties;
$("#form-region").val(props["Region"]);
$("#form-circuitID").val(props["Circuit_ID"]);
$("#form-circuitName").val(props["Circuit_Name"]);
$("#form-vendor").val(props["Vendor"]);
$("#form-quad").val(props["Quad"]);
},
openPopup: function() {
this.bindEvents();
$('#eventDataModal').modal('show');
},
bindEvents: function() {
if (!this.binded) {
$('#eventDataModal').on('hidden.bs.modal', L.bind(this.onFormClosed, this));
$("#saveEventDataModal").on('click', L.bind(this.onSave, this))
this.binded = true;
}
},
onSave: function() {
var properties = this.getFormData(),
request = this.wfsBody("usa", "usa:pecotest", "geom", properties);
console.log(request);
this.makeRequest(request);
},
makeRequest: function(body) {
$.ajax({
method: "POST",
crossDomain: true,
url: this.options.url,
contentType: "text/xml",
dataType: "text",
data: body,
headers: {
"Authorization": "Basic " + btoa(this.options.userName + ":" + this.options.password)
},
jsonpCallback: 'datasave',
success: L.bind(this.onDataSave, this),
failure: function(r){console.log("AJAX Failure!");console.log(r);}
});
},
onDataSave: function(data) {
console.log(data);
},
getFormData: function() {
var result = {};
$('#eventDataModal').find('input').each(
function() {
if (this.type=="checkbox") {
result[this.name] = this.checked ? "Yes" : "No";
} else {
result[this.name]=$(this).val();
}
}
);
$('#eventDataModal').find('textarea').each(
function() {
result[this.name]=$(this).val();
}
);
return result;
},
wfsBody: function(namesapce, typeName, geometryField, properties) {
var xml;
xml ='<wfs:Transaction service="WFS" version="1.0.0"';
xml += ' xmlns:wfs="http://www.opengis.net/wfs"';
xml += ' xmlns:usa="http://census.gov"';
xml += ' xmlns:gml="http://www.opengis.net/gml">\n';
xml += ' <wfs:Insert>\n';
xml += ' <'+typeName+'>\n';
xml += ' <usa:'+geometryField+'>\n';
xml += this.marker.toGML()+"\n";
xml += ' </usa:'+geometryField+'>\n';
for (var k in properties) {
if (properties.hasOwnProperty(k)) {
xml += "<"+namesapce+":"+k+">";
xml += properties[k];
xml += "</"+namesapce+":"+k+">\n";
}
}
xml += ' </'+typeName+'>\n';
xml += ' </wfs:Insert>\n';
xml += '</wfs:Transaction>\n';
return xml;
}
});
L.Marker.include({
toGML: function(){
var latlng = this.getLatLng(),
xml;
xml = '<gml:Point srsName="EPSG:4326"><gml:coordinates cs=","
decimal="." ts=" ">';
xml += latlng.lng + ',' + latlng.lat;
xml += '</gml:coordinates></gml:Point>';
return xml;
}
});
Here is the corresponding HTML for the modal evenDataModal
<div class="modal fade" id="eventDataModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-
label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Create New Visual Report</h4>
</div>
<div class="modal-body">
<form action="php\new_peco_visual_report_db_insert.php
method="POST"><div class="form-group">
<label for="form-priority">ID Code</label>
<input type="number" class="form-control" id="form-priority"
name="ID_Code" placeholder="ID_Code">
</div>
<div class="form-group">
<label for="form-region">Region</label>
<input type="text" class="form-control" id="form-region"
name="Region" placeholder="region">
</div>
<div class="form-group">
<label for="form-circuitID">Circuit ID</label>
<input type="number" class="form-control" id="form-circuitID"
name="Circuit_ID" placeholder="Circuit ID">
</div>
<div class="form-group">
<label for="form-circuitName">Circuit Name</label>
<input type="text" class="form-control" id="form-circuitName"
name="Circuit_Name" placeholder="Circuit Name">
</div>
<div class="form-group">
<label for="form-patrolDate">Patrol Date</label>
<input type="date" class="form-control" id="form-patrolDate"
name="Patrol_Date" placeholder="Patrol Date">
</div>
<div class="form-group">
<label for="form-vendor">Vendor</label>
<input type="text" class="form-control" id="form-vendor"
name="Vendor" placeholder="Vendor">
</div>
<div class="form-group">
<label for="form-repairNumber">Repair Number</label>
<input type="text" class="form-control" id="form-repairNumber"
name="Repair_Number" placeholder="Repair Number">
</div>
<div class="form-group">
<label for="form-problemDescription"> Problem
Description</label>
<input type="text" class="form-control" id="form-
problemDescription" name="Problem_Description"
placeholder="Problem
Description">
</div>
<div class="form-group">
<label for="form-urgency">Priority</label>
<input type="number" class="form-control" id="form-urgency"
name="Urgency" placeholder="Urgency">
</div>
<div class="form-group">
<label for="form-circuitPortion">Circuit Portion</label>
<input type="text" class="form-control" id="form-circuitPortion"
name="Circuit_Portion" placeholder="Circuit Portion">
</div>
<div class="form-group">
<label for="form-quad">Quad</label>
<input type="text" class="form-control" id="form-quad"
name="Quad" placeholder="Quad">
</div>
<div class="form-group">
<label for="form-location">Location</label>
<input type="text" class="form-control" id="form-location"
name="Location" placeholder="location">
</div>
<div class="form-group">
<label for="form-poleSub">PolSub</label>
<input type="number" class="form-control" id="form-polSub"
name="PolSub" placeholder="PolSub">
</div>
<div class="form-group">
<label for="form-poleNumber">Pole Number</label>
<input type="number" class="form-control" id="form-poleNumber"
name="Pole_Number" placeholder="Pole Number">
</div>
<div class="form-group">
<label for="form-aerialName">Aerial Name</label>
<input type="text" class="form-control" id="form-aerialName"
name="Aerial_Name" placeholder="Aerial Name">
</div>
<div class="form-group">
<label for="form-workRequired">Work Required?</label>
<input type="text" class="form-control" id="form-workRequired"
name="Work_Required" placeholder="Work Required">
</div>
<div class="form-group">
<label for="form-long">GPS Longitude</label>
<input type="text" class="form-control" id="form-long"
name="long" placeholder="long">
</div>
<div class="form-group">
<label for="form-lat">GPS Latitude</label>
<input type="text" class="form-control" id="form-lat" name="lat"
placeholder="lat">
</div>
<div class="form-group">
<label for="form-notes">Comments</label>
<textarea class="form-control" id="form-comments"
name="Comments" rows="3"></textarea>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-
dismiss="modal">Close</button>
<button type="sumbit" class="btn btn-primary"
id="saveEventDataModal">Save</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
Here is the code for that should call the second modal called evenDataModal2
L.MarkerControl2 = L.Control.extend({
options: {
position: 'topleft',
url: 'http://echostorm.mynetgear.com:8080/geoserver/usa/ows',
userName: 'wfspost',
password: 'createfeature'
},
map: null,
marker: null,
binded: false,
onAdd: function (map) {
this.map = map;
var container = L.DomUtil.create('div', 'leaflet-control leaflet-bar'),
// link = L.DomUtil.create('a', 'glyphicon glyphicon-map-marker', container);
link = L.DomUtil.create('a', 'glyphicon glyphicon-fire', container);
link.href = '#';
link.title = 'Create a new thermal report';
link.innerHTML = '';
L.DomEvent.on(link, 'click', L.DomEvent.stop)
.on(link, 'click', L.bind(this.startCreating, this));
map.on("editable:drawing:commit", L.bind(this.onMarkerAdd, this));
return container;
},
startCreating: function() {
this.marker = this.map.editTools.startMarker();
},
onMarkerAdd: function(e) {
this.nearestFeature = null;
this.findNearestPoints(e.layer.getLatLng());
},
onFormClosed: function() {
if (this.marker!=null) {
this.map.editTools.featuresLayer.removeLayer(this.marker);
this.marker = null;
}
},
findNearestPoints: function(latlng) {
var defaultParameters = {
service: 'WFS',
version: '1.0.0',
request: 'GetFeature',
typeName: 'usa:within5mi',
maxFeatures: 5,
outputFormat: 'text/javascript',
format_options: 'callback: nearestPoints',
srsName: 'EPSG:4326',
viewparams: 'radius:802;lon:'+latlng.lng+';lat:'+latlng.lat,
};
var parameters = L.Util.extend(defaultParameters);
$.ajax({
jsonp: false,
url: this.options.url + L.Util.getParamString(parameters),
dataType: 'jsonp',
jsonpCallback: 'nearestPoints',
success: L.bind(this.handleNearestPoints, this)
});
},
handleNearestPoints: function(data) {
this.clearModal();
this.setModalDate();
if (data && data.type=="FeatureCollection"
&& data.features && data.features.length
&& data.features.length > 0) {
this.fillModal(data.features[0]);
}
this.openPopup();
},
formatDate: function(date) {
var day = date.getDate();
return date.getFullYear()+"-"+(date.getMonth()+1)+"-"+(day < 10 ? "0"+day : day);
},
clearModal: function() {
$('#eventDataModal2').find('input').each(
function() {
$(this).val("");
}
);
$('#eventDataModal2').find('textarea').each(
function() {
$(this).val("");
}
);
},
setModalDate: function() {
$("#form-patrolDate").val(this.formatDate(new Date()));
},
fillModal: function(feature) {
var props = feature.properties;
$("#form-region").val(props["Region"]);
$("#form-circuitID").val(props["Circuit_ID"]);
$("#form-circuitName").val(props["Circuit_Name"]);
$("#form-vendor").val(props["Vendor"]);
$("#form-quad").val(props["Quad"]);
},
openPopup: function() {
this.bindEvents();
$('#eventDataModal2').modal('show');
},
bindEvents: function() {
if (!this.binded) {
$('#eventDataModal2').on('hidden.bs.modal', L.bind(this.onFormClosed, this));
$("#saveEventDataModal2").on('click', L.bind(this.onSave, this))
this.binded = true;
}
},
onSave: function() {
var properties = this.getFormData(),
request = this.wfsBody("usa", "usa:pecotest", "geom", properties);
console.log(request);
this.makeRequest(request);
},
makeRequest: function(body) {
$.ajax({
method: "POST",
crossDomain: true,
url: this.options.url,
contentType: "text/xml",
dataType: "text",
data: body,
headers: {
"Authorization": "Basic " + btoa(this.options.userName + ":" + this.options.password)
},
jsonpCallback: 'datasave',
success: L.bind(this.onDataSave, this),
failure: function(r){console.log("AJAX Failure!");console.log(r);}
});
},
onDataSave: function(data) {
console.log(data);
},
getFormData: function() {
var result = {};
$('#eventDataModal2').find('input').each(
function() {
if (this.type=="checkbox") {
result[this.name] = this.checked ? "Yes" : "No";
} else {
result[this.name]=$(this).val();
}
}
);
$('#eventDataModal2').find('textarea').each(
function() {
result[this.name]=$(this).val();
}
);
return result;
},
wfsBody: function(namesapce, typeName, geometryField, properties) {
var xml;
xml ='<wfs:Transaction service="WFS" version="1.0.0"';
xml += ' xmlns:wfs="http://www.opengis.net/wfs"';
xml += ' xmlns:usa="http://census.gov"';
xml += ' xmlns:gml="http://www.opengis.net/gml">\n';
xml += ' <wfs:Insert>\n';
xml += ' <'+typeName+'>\n';
xml += ' <usa:'+geometryField+'>\n';
xml += this.marker.toGML()+"\n";
xml += ' </usa:'+geometryField+'>\n';
for (var k in properties) {
if (properties.hasOwnProperty(k)) {
xml += "<"+namesapce+":"+k+">";
xml += properties[k];
xml += "</"+namesapce+":"+k+">\n";
}
}
xml += ' </'+typeName+'>\n';
xml += ' </wfs:Insert>\n';
xml += '</wfs:Transaction>\n';
return xml;
}
});
The corresponding HTML for eventDataModal is exactly the same as the above html code except the id has been changed to eventDataModal2
Related
As you can see below, I have a modal that should be validated then send a request to the server. The problem is that if I try to submit for the first time, that validation is worked properly but for the second time it won't work. When I debug the codes I found out that validationCheck() worked fine but the resolve() doesn't return any result to the add() in certificate-manager file.
request.js
let insert = function (isPost = false, url, data, reloadLocation = false, table = null,
modal = null, ponds) {
let request = null;
if (isPost) {
let uploadNotify = uploadNotification();
//step 3
let config = {
onUploadProgress: function (progressEvent) {
let percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
console.log(percentCompleted);
uploadNotify.update('message', '<strong>Uploading</strong> ' + percentCompleted + ' %');
uploadNotify.update('progress', percentCompleted);
},
headers: {
'content-type': 'multipart/form-data'
}
};
//step 4
request = axios.post(url, data, config)
} else {
//step 4
request = axios.get(url, {
params: data
});
}
request.then(function (response) {
console.log(response);
let data = response['data'];
if (data['status'] === 200) {
let content = {
'title': 'Done!',
'message': data['message']
};
notification(content, 1);
if (reloadLocation)
location.reload();
if (table) {
table.ajax.reload();
clearModal('.inp', ponds);
}
}
})
.catch(function (error) {
console.log(error);
let data = error['data'];
let content = {
'title': 'Error!',
'message': data['message']
};
notification(content, 0);
})
.then(function () {
if (modal)
closeModal(modal);
});
};
utilities.js
async function validationCheck (id, rules) {
jQuery.validator.addMethod('passwordCheck', function (value, element, param) {
//Your Validation Here
let oldPass = jQuery('#input-old-password').val();
let confirmPass = jQuery('#input-confirm-password').val();
return oldPass != null && confirmPass === value;
// return bool here if valid or not.
}, 'Your error message!');
jQuery.validator.addMethod('phoneNumber', function (value, element, param) {
value = value.replace(/\s+/g, "");
return this.optional(element) || value.length > 9 &&
value.match(/\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/);
}, 'Please specify a valid phone number');
jQuery.validator.addMethod('startDate', function (value, element, param) {
return (parseInt(value) > 2000)
}, 'Please specify a valid year');
jQuery.validator.addMethod('endDate', function (value, element, param) {
return (parseInt(value) >= parseInt(jQuery('#input-start-time').val()) ||
jQuery('#input-current').is(":checked"))
}, 'Please specify a valid year');
jQuery.validator.addMethod('uendDate', function (value, element, param) {
return (parseInt(value) >= parseInt(jQuery('#input-update-start-time').val()) ||
jQuery('#input-update-current').is(":checked"))
}, 'Please specify a valid year');
return new Promise((resolve, reject)=> {
jQuery(id).validate({
// define validation rules
rules: rules,
errorPlacement: function (error, element) {
let group = element.closest('.input-group');
if (group.length) {
group.after(error.addClass('invalid-feedback'));
} else {
element.after(error.addClass('invalid-feedback'));
}
},
// messages: {
// username: {
// required: "Username is required"
// }
// },
//display error alert on form submit
invalidHandler: function (event, validator) {
// let alert = jQuery('#kt_form_1_msg');
// alert.removeClass('kt--hide').show();
KTUtil.scrollTo(id, -200);
reject(false);
},
submitHandler: function (form) {
resolve(true);
//form[0].submit(); // submit the form
}
});
});
}
certificate-manager.js
let add = async function () {
let check = await validationCheck("#form", {
title: {
required: true
},
company: {
required: true
},
start: {
required: true,
date: true,
digits: true,
minlength: 4,
maxlength: 4,
startDate: true
},
end: {
date: true,
digits: true,
minlength: 4,
maxlength: 4,
endDate: true
},
description: {
required: true
}
}).then(value => {
console.log(value)
insert(
false,
'/api/add/certificate',
getInputsData(),
false,
table,
"#kt_modal")
}, reason => {
console.log(reason)
}).catch(reason => {
console.log(reason)
});
}
<!--begin:: insert Modal-->
<div class="modal fade" id="kt_modal" tabindex="-1" role="dialog"
aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">New Certificate</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
</button>
</div>
<div class="modal-body">
<form id="form">
<div class="row">
<div class="col-12">
<div class="form-group">
<label for="input-title"
class="form-control-label">Title</label>
<input type="text" class="inp form-control"
name="title"
id="input-title">
</div>
<div class="form-group">
<label for="input-company-institute"
class="form-control-label">Company/Institute</label>
<input type="text" class="inp form-control" name="company" id="input-company-institute">
</div>
<div class="row">
<div class="form-group col-6">
<label for="input-start-time"
class="form-control-label">From Year</label>
<input type="text" class="inp form-control" name="start" id="input-start-time">
</div>
<div class="form-group col-6">
<label for="input-end-time"
class="form-control-label">To Year</label>
<input type="text" class="inp form-control" name="end" id="input-end-time">
<div class="mt-2">
<label for="input-current" class="kt-checkbox kt-checkbox--brand col-6">
<input type="checkbox" id="input-current"> Current
<span></span>
</label>
</div>
</div>
</div>
<div class="form-group">
<label for="input-description"
class="form-control-label">Description</label>
<textarea class="inp form-control" name = "description" id="input-description"></textarea>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button id="add-btn" onclick="add()" type="submit" class="btn btn-primary" >Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!--end::insert Modal-->
the order of the files is:
'../../../assets/adminPanel/js/utilities.js',
'../../../assets/adminPanel/js/request.js',
'../../../assets/adminPanel/js/pages/resume/certificate-manager.js'
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);
}
);
My html code is
I also need to add sez which is in array format and also i need to add multiple images, need to provide add image and when clicking on it, need to add images as needed by the client
<form method="POST" enctype="multipart/form-data" v-on:submit.prevent="handleSubmit($event);">
<div class="row">
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Name</label>
<input type="text" class="form-control" v-model="name">
</div>
</div>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Alias</label>
<input type="text" class="form-control" v-model="alias">
</div>
</div>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Sex</label>
<select class="form-control" v-model="sex" id="level">
<option value="Male">Male</option>
<option value="female">Female</option>
</select>
</div>
</div>
</div>
<div class="row" v-for="(book, index) in sez" :key="index">
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Date </label>
<input type="date" class="form-control" v-model="book.date">
</div>
</div>
<div class="col-md-8">
<div class="form-group label-floating">
<label class="control-label"> Details</label>
<input type="text" class="form-control" book.details>
</div>
</div>
</div>
<a #click="addNewRow">Add</a>
<div class="card-content">
<div class="row">
<div class="col-md-4">
<div class="button success expand radius">
<span id="save_image_titlebar_logo_live">Signature</span>
<label class="custom-file-upload"><input type="file" name="photo" accept="image/*" />
</label>
</div>
</div>
<div class="col-md-4">
<div class="button success expand radius">
<span id="save_image_titlebar_logo_live">Recent Photograph</span>
<label class="custom-file-upload">
<input type="file" name="sign"/>
</label>
</div>
</div>
</div>
</div>
</form>
My vue js code is
addForm = new Vue({
el: "#addForm",
data: {
name: '',
alias: '',
sex: '',
sez: [{
date: null,
details: null,
}, ],
photo: '',
sign: '',
},
methods: {
addNewRow: function() {
this.seziure.push({
date: null,
details: null,
});
},
handleSubmit: function(e) {
var vm = this;
data = {};
data['sez'] = this.sez;
data['name'] = this.name;
data['alias'] = this.alias;
data['sex'] = this.sex;
//how to add images
$.ajax({
url: 'http://localhost:4000/save/',
data: data,
type: 'POST',
dataType: 'json',
success: function(e) {
if (e.status) {
vm.response = e;
alert("success")
} else {
vm.response = e;
console.log(vm.response);
alert("Registration Failed")
}
}
});
return false;
},
},
});
This is my code. I have no idea about how to add images in this case.
Can anyone please help me pass this data.
How to pass this data along with images to the backend?
I don't want to use base64 encoding. I need to just pass this image in this ajax post request along with other data
Using axios:
Template
...
<input type="file" name="photo" accept="image/*" #change="setPhotoFiles($event.target.name, $event.target.files) />
...
Code
data () {
return {
...
photoFiles: [],
...
}
},
...
methods: {
...
setPhotoFiles (fieldName, fileList) {
this.photoFiles = fileList;
},
...
handleSubmit (e) {
const formData = new FormData();
formData.append('name', this.name);
formData.append('alias', this.alias);
formData.append('sex', this.sex);
...
this.photoFiles.forEach((element, index, array) => {
formData.append('photo-' + index, element);
});
axios.post("http://localhost:4000/save/", formData)
.then(function (result) {
console.log(result);
...
}, function (error) {
console.log(error);
...
});
}
}
I'm not sure where would you like the extra images to appear, but I added them after this column:
<div class="col-md-4">
<div class="button success expand radius">
<span id="save_image_titlebar_logo_live">Recent Photograph</span>
<label class="custom-file-upload">
<input type="file" name="sign"/>
</label>
</div>
</div>
And here's the column I added — "add images": (You can try this feature here, with the updates)
<div class="col-md-4">
<ul class="list-group" :if="images.length">
<li class="list-group-item" v-for="(f, index) in images" :key="index">
<button class="close" #click.prevent="removeImage(index, $event)">×</button>
<div class="button success expand radius">
<label class="custom-file-upload">
<input type="file" class="images[]" accept="image/*" #change="previewImage(index, $event)">
</label>
</div>
<div :class="'images[' + index + ']-preview image-preview'"></div>
</li>
</ul>
<button class="btn btn-link add-image" #click.prevent="addNewImage">Add Image</button>
</div>
And the full Vue JS code (with jQuery.ajax()):
addForm = new Vue({
el: "#addForm",
data: {
name: '',
alias: '',
sex: '',
sez: [{
date: null,
details: null
}],
// I removed `photo` and `sign` because (I think) the're not necessary.
// Add I added `images` so that we could easily add new images via Vue.
images: [],
maxImages: 5,
// Selector for the "Add Image" button. Try using (or you should use) ID
// instead; e.g. `button#add-image`. But it has to be a `button` element.
addImage: 'button.add-image'
},
methods: {
addNewRow: function() {
// I changed to `this.sez.push` because `this.seziure` is `undefined`.
this.sez.push({
date: null,
details: null
});
},
addNewImage: function(e) {
var n = this.maxImages || -1;
if (n && this.images.length < n) {
this.images.push('');
}
this.checkImages();
},
removeImage: function(index) {
this.images.splice(index, 1);
this.checkImages();
},
checkImages: function() {
var n = this.maxImages || -1;
if (n && this.images.length >= n) {
$(this.addImage, this.el).prop('disabled', true); // Disables the button.
} else {
$(this.addImage, this.el).prop('disabled', false); // Enables the button.
}
},
previewImage: function(index, e) {
var r = new FileReader(),
f = e.target.files[0];
r.addEventListener('load', function() {
$('[class~="images[' + index + ']-preview"]', this.el).html(
'<img src="' + r.result + '" class="thumbnail img-responsive">'
);
}, false);
if (f) {
r.readAsDataURL(f);
}
},
handleSubmit: function(e) {
var vm = this;
var data = new FormData(e.target);
data.append('sez', this.sez);
data.append('name', this.name);
data.append('alias', this.alias);
data.append('sex', this.sex);
// The `data` already contain the Signature and Recent Photograph images.
// Here we add the extra images as an array.
$('[class~="images[]"]', this.el).each(function(i) {
if (i > vm.maxImages - 1) {
return; // Max images reached.
}
data.append('images[' + i + ']', this.files[0]);
});
$.ajax({
url: 'http://localhost:4000/save/',
data: data,
type: 'POST',
dataType: 'json',
success: function(e) {
if (e.status) {
vm.response = e;
alert("success");
} else {
vm.response = e;
console.log(vm.response);
alert("Registration Failed");
}
},
cache: false,
contentType: false,
processData: false
});
return false;
},
},
});
Additional Notes
I know you're using Node.js in the back-end; however, I should mention that in PHP, the $_FILES variable would contain all the images (so long as the fields name are properly set); and I suppose Node.js has a similar variable or way of getting the files.
And in the following input, you may have forgotten to wrap book.details in v-model:
<input type="text" class="form-control" book.details>
<input type="text" class="form-control" v-model="book.details"> <!-- Correct -->
UPDATE
Added feature to limit number of images allowed to be selected/uploaded, and added preview for selected image. Plus the "send images as array" fix.
If you're using HTML5, try with a FormData object ; it will encode your file input content :
var myForm = document.getElementById('addForm');
formData = new FormData(myForm);
data: formData
Use below templete to show/upload the image:
<div v-if="!image">
<h2>Select an image</h2>
<input type="file" #change="onImageUpload">
</div>
<div v-else>
<img :src="image" />
<button #click="removeImage">Remove image</button>
</div>
Js code:
data: {
image: '',
imageBuff: ''
},
methods: {
onImageUpload(e) {
var files = e.target.files || e.dataTransfer.files;
if (!files.length)
return;
this.createImage(files[0]);
},
createImage(file) {
var image = new Image();
var reader = new FileReader();
this.imageBuff = file;
reader.onload = (e) => {
this.image = e.target.result;
};
reader.readAsDataURL(file);
},
removeImage: function(e) {
this.image = '';
},
handleSubmit(e) {
const formData = new FormData();
formData.append('name', this.name);
formData.append('alias', this.alias);
formData.append('sex', this.sex);
formData.append('image', this.imageBuff);
...
// Ajax or Axios can be used
$.ajax({
url: 'http://localhost:4000/save/',
data: formData,
processData: false, // prevent jQuery from automatically transforming the data into a query string.
contentType: false,
type: 'POST',
success: function(data) {
console.log(data);
...
}
});
}
}
Im new in Laravel, and I have problem in my method store like this.
this is my method in my controller.
public function store(Request $request)
{
if($request->ajax()){
$data = array(
'karyawan_id'=>$request->id_kar,//here it is the problem
'tgl_berlaku'=>$request->tgl_berlaku,
'jumlah_gapok'=>$request->jumlah_gapok,
'created_by'=>auth()->user()->id,
'data_sekolah_id' => Library::sekolahSelected(),
);
$this->save("tb_gaji_pokok",$data);
if($data){
$response = $this->returnSuccess('', trans('messages.success.add'));
return response()->json($response);
}else{
$response = $this->returnData('', trans('messages.error.add'));
return response()->json($response);
}
}
}
and this is my ajax which is create the modal in view.
function atur(id,a){
var kar_id ='<div class="col-sm-9"><input
type="text" class="form-control" id="id_kar"
name="id_kar" disabled> <input type="hidden"
class="form-control" name="id" value="{{ $id }}">
</div>';
var input_gaji = '<div class="form-group"><label
class="col-sm-3 control-label">Atur Gaji
Pokok</label><div class="col-sm-6"><input
type="text" id="jumlah_gapok" class="form-control"
name="jumlah_gapok" placeholder="Jumlah"></div>
</div>';
var tanggal = '<div class="form-group"><label
class="col-sm-3 control-label">Tanggal
Berlaku</label><div class="col-sm-6"><div
class="input-group"><input type="text"
id="tgl_berlaku" class="form-control tgl_berlaku"
name="tgl_berlaku" placeholder="Tanggal Berlaku">
<span class="input-group-addon"><i class="fa fa-
calendar"></i></span></div></div></div>';
var infoModal = $('#gajipokok');
if(id) {
$.ajax({
url: path+'/aturgaji/'+id+'/'+a,
type: "GET",
dataType: "json",
success:function(data) {
alert(data.karyawan.nama);
htmlData = '<h4>Nama karyawan :
'+data.karyawan.nama+'</h4><h4>Status :
'+data.karyawan.status_karyawan+'</h4><h4>Jabatan :
'+data.jabatan.nama_jabatan+'</h4>
<td>'+input_gaji+'</td><td>'+tanggal+'</td>'+kar_id;
infoModal.find('.modal-body').html(htmlData);
$('.tgl_berlaku').datepicker({
format: "yyyy-mm-dd",
todayBtn: "linked",
autoclose: true,
todayHighlight: true,
}).on('changeDate', function(e) {
$('#form').formValidation('revalidateField',
'tgl_berlaku');
});//datepicker tgl_awal
$('#id_kar').val(data.karyawan.id);
modalGajiShow();
}
);
}
else {
modalGajiHide();
notify(0, 'Something when wrong');
}
}
and the problem is here :
'karyawan_id'=>$request->id_kar,
that request return nothing, so in the database, karyawan_id's column still Null
can someone help me fix this? thank 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);
}
});