missing data from Request - javascript

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.

Related

How can I retrieve data from the controller and process it using jQuery Autocomplete?

I'm using this: https://github.com/devbridge/jQuery-Autocomplete
I want to suggestions as the user writes something from my input element with ID tags.
My controller:
public function addProducts(Request $request)
{
$word = $request->input('name');
$data = itemsNames::select('i_name')->where('i_name', 'like', '%' . $word . '%')->get();
return view('admin.settings.products.addProduct', compact('data'));
}
My view
<div class="form-group col-4 labelform">
<label> name *</label>
<div class="controlsopop">
<i class="far fa-envelope"></i>
<input type="text" name="name" id="tags" value="" class="form-control">
</div>
</div>
I tried this:
$(function () {
var availableTags = $data;
$("#tags").autocomplete({
source: availableTags
});
});
I want your help to find out what the wrong point I fell in and thank you
You can use your route as serviceUrl:
$('#tags').autocomplete({
serviceUrl: "{{ route('your_route') }}",
preserveInput: true,
autoSelectFirst: false,
onSelect: function (suggestion) {
console.log(suggestion);
// your operation
}
});
And your route method in the controller:
public function addProducts(Request $request)
{
$word = $request->input('name');
$data = itemsNames::select('i_name')
->where('i_name', 'like', '%' . $word . '%')->get()->toArray();
return response()->json([
'suggestions' => $data,
]);
}

JQuery Validation - Remote method always check and become true before submit the form

Using jQuery validation plugin, I have been trying to validate and submit my form. JS code for this as shown below.
jQuery.validator.addMethod(
"regex",
function(value, element, regexp) {
var re = new RegExp(regexp);
return this.optional(element) || re.test(value);
},
"Enter a valid phone number."
);
var phoneNumbers_default = {
maxlength: 11,
regex: /^0+\d{2}[ -]\d{7}( x\d{1,6})?$/,
remote: "./includes/check-duplicate-mobile.php"
// remote: {
// url: "./includes/check-duplicate-mobile.inc.php",
// type: "post"
// }
};
var phoneNumbers_required = {
required: true
};
var phoneNumber_message = {
minlength: "Your mobile number should be at least 11 digits long.",
maxlength: "Your mobile number cannot be longer than 11 digits.",
remote: "One active user account already exists for this mobile number. Duplicates are not allowed."
}
jQuery.extend(phoneNumbers_default,phoneNumbers_required);
function processForms(el,fileAttached=false) {
var $el = $('#'+el)
$el.validate({
errorElement: 'span',
focusInvalid: false,
//ignore: ".ignore",
ignore: "",
rules: {
email: {
required: true,
email: true
},
mobileNumber: phoneNumbers_default,
p_mobile: phoneNumbers_default,
},
messages: {
email: {
required: "Please provide a valid email.",
email: "Please provide a valid email."
},
mobileNumber:phoneNumber_message,
p_mobile:phoneNumber_message,
},
submitHandler: function (form) {
var $form = $(form);
var url = 'add_user_form.php';
var formData = new FormData(form);
$.ajax({
url: url,
type: "POST",
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(json) {
json = jQuery.parseJSON(json)
if (json.success) {
// it worked
} else {
// it not worked
}
},
});
return false;
}
})
}
Above code works fine for the first submit. I meant it is new form submission. But my problem is when I try to update the existing data using the same form it always checks remote method and become return ture. That means, if I want to update the existing data, I always have to change the mobile number.
UPDATE:
Form markup
<form class="mt-2 text-dark-m1" id="addNew_user" method="post" action="" >
<div class="form-group row">
<div class="col-sm-3 col-form-label text-sm-right pr-0">
Email:
</div>
<div class="col-sm-9">
<input type="text" name="principal_email" class="form-control col-sm-4" value="<?=$p_email?>" />
</div>
</div>
<div class="form-group required row">
<div class="col-sm-3 col-form-label text-sm-right pr-0">
Mobile :
</div>
<div class="col-sm-9">
<input type="text" name="p_mobile" class="form-control col-sm-4" value="<?=$p_mobile?>" required />
</div>
</div>
<div class="border-t-1 bgc-secondary-l4 brc-secondary-l2 py-35 mx-n25 mt-5">
<div class="offset-md-3 col-md-9 text-nowrap flex-align-center">
<button class="btn btn-info btn-bold px-4" type="submit"><i class="fa fa-check mr-1"></i>Submit</button>
</div>
</div>
</form>
Serverside Code:
$mobileNumber = isset($_GET['p_mobile']) ? $_GET['p_mobile'] : '';
if (strlen($mobileNumber) >= 10 && strlen($mobileNumber) <= 12) {
$sql ="SELECT user_id FROM user WHERE mobile = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$mobileNumber]);
$uid = $stmt->fetchColumn();
if ($uid) echo "false"; // it comes to this line
else echo "true";
} else {
echo "false";
}
Can anybody tell me, how I fix this issue?
What about making this change in the server side? I am still learning php, but i believe you will get the idea.
$mobileNumber = isset($_GET['p_mobile']) ? $_GET['p_mobile'] : '';
$requestUserId = isset($_GET['user_id']) ? $_GET['user_id'] : '';
if (strlen($mobileNumber) >= 10 && strlen($mobileNumber) <= 12) {
$sql ="SELECT user_id FROM user WHERE mobile = ?";
if (requestUserId) $sql += " AND user_id <> ?"
$stmt = $pdo->prepare($sql);
$stmt->execute([$mobileNumber, $requestUserId]);
$uid = $stmt->fetchColumn();
if ($uid) echo "false"; // it comes to this line
else echo "true";
} else {
echo "false";
}

Laravel 7: How to get name instead of id in dependent dropdown?

I have a dependent dropdown and it gets values by comparing ID's, the issue here is when I am trying to save the form values I am getting the ID's instead of names of the select fields. Can anyone tell me how can I get the NAME instead of ID.
My blade view with the javascript: index.blade.php`
<div class="container">
<h2>Region</h2><br>
<form action="details" method="POST">
{{ csrf_field() }}
<div class="form-group">
<label for="title">Select Country:</label>
<select id="country" name="country" class="form-control" style="width:350px" required>
<option value="" selected disabled>Select</option>
#foreach($countries as $key => $country)
<option value="{{$key}}">{{$country}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="title">Select State:</label>
<select name="state" id="state" class="form-control" style="width:350px" required>
</select>
</div>
<div class="form-group">
<label for="title">Select City:</label>
<select name="city" id="city" class="form-control" style="width:350px" required>
</select>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
<script type="text/javascript">
$('#country').change(function() {
var countryID = $(this).val();
if (countryID) {
$.ajax({
type: "GET",
url: "{{url('get-state-list')}}?country_id=" + countryID,
success: function(res) {
if (res) {
$("#state").empty();
$("#state").append('<option value="">Select</option>');
$.each(res, function(key, value) {
$("#state").append('<option value="' + key + '">' + value + '</option>');
});
} else {
$("#state").empty();
}
}
});
} else {
$("#state").empty();
$("#city").empty();
}
});
$('#state').change(function() {
var stateID = $(this).val();
if (stateID) {
$.ajax({
type: "GET",
url: "{{url('get-city-list')}}?state_id=" + stateID,
success: function(res) {
if (res) {
$("#city").empty();
$("#city").append('<option value="">Select</option>');
$.each(res, function(key, value) {
$("#city").append('<option value="' + key + '">' + value + '</option>');
});
} else {
$("#city").empty();
}
}
});
} else {
$("#city").empty();
}
});
</script>
My Controller for the dropdown: DropdownController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class DropdownController extends Controller
{
public function index()
{
$countries = DB::table("countries")->pluck("name", "id");
return view('index', compact('countries'));
}
public function getStateList(Request $request)
{
$states = DB::table("states")
->where("country_id", $request->country_id)
->pluck("name", "id");
return response()->json($states);
}
public function getCityList(Request $request)
{
$cities = DB::table("cities")
->where("state_id", $request->state_id)
->pluck("name", "id");
return response()->json($cities);
}
public function show(Request $request)
{
dd(request()->all());
}
}
The payload I am getting after data dump is the ID's:
array:4 [▼
"_token" => "xxxxxxxxxxxxxxxxxxxxxxxxx"
"country" => "1"
"state" => "5"
"city" => "124"
]
What I want is to get Names:
array:4 [▼
"_token" => "xxxxxxxxxxxxxxxxxxxxxxxxx"
"country" => "country_name"
"state" => "state_name"
"city" => "city_name"
]
You should change the name of your select from name to name[]

Getting error in input-group-addon when validating the field using ajax and jquery in codeigniter

Now its been 46 day's till i am stuck with this. Or there is Another way to Do this.
I Know This very simple But How can i wrap input-group under form-group. I am submitting the form data in codeigniter using ajax and showing validation errors.
The issue is that input-group-addon wraps to the next line underneath the form field when the error control is added by Jquery Validate.
Controller
function infoValidation() {
$result = array('status' => false, 'message' => array());
$this->form_validation->set_error_delimiters('<div class="text-danger">','</div>');
if ($this->form_validation->run('company_registration')) {
$result['status'] = true;
}else {
foreach ($_POST as $key => $value) {
$result['message'][$key] = form_error($key);
}
}
echo json_encode($result);
}
view
<div class="col-lg-6">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">*</span>
<input type = "text" name="creditCardNumber" class="form-control input-md" id="creditCardNumber" placeholder="Mobile No">
</div>
</div>
ajax
I have also try to append the element But Nothing Happens
$.ajax({
url : me.attr('action'),
dataType : 'json',
type : 'POST',
data : me.serialize(),
success: function(resp) {
console.log(resp);
if (resp.status == true) {
$('#myModal').modal('show');
$(".form-group").removeClass('has-error').removeClass('has-success');
$(".text-danger").remove();
}else {
$('#msg').html('<div class="well"><h5>Please Check Your Details</h5></div>');
$.each(resp.message, function(key, value) {
var element = $("#"+key);
element.closest('div.form-group, div.input-group')
.addClass(value.length > 0 ? 'has-error' : 'has-success')
.find('.text-danger').remove();
element.after(value);
});
}
}
});
I think you need to override the jQuery validate plugin method in order to get compatibility with bootstrap.
Refer http://jsfiddle.net/mapb_1990/hTPY7/7/
Example code
$('form').validate({
rules: {
firstname: {
minlength: 3,
maxlength: 15,
required: true
},
lastname: {
minlength: 3,
maxlength: 15,
required: true
}
},
highlight: function(element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-error');
},
errorElement: 'span',
errorClass: 'help-block',
errorPlacement: function(error, element) {
if(element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});
Just add label for error at your desired location:
<label for="creditCardNumber" generated="true" class="error">
<div class="col-lg-6">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">*</span>
<input type = "text" name="creditCardNumber" class="form-control input-md" id="creditCardNumber" placeholder="Mobile No">
</div>
<label for="creditCardNumber" generated="true" class="error"></label>
</div>

Two modals opening from a single link

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

Categories