jQuery returning null - selected option not being posted correctly? - ajax

This jQuery script is returning null. I've tried using other syntax for selected options but here's what I've got below:
The script works and runs correctly, allowing me to download the Excel file. However the ID is not being set correctly (via the option selected) and thus is parsing as "0".
<script>
//When Page Loads....
$(document).ready(function(){
$('#dropdown').change(function(){
// Call the function to handle the AJAX.
// Pass the value of the text box to the function.
sendValue($(this).val());
});
});
// Function to handle ajax.
function sendValue(str){
// post(file, data, callback, type); (only "file" is required)
$.post(
"scripts/export_to_excel/index.php", //Ajax file
{ sendValue: str }, // create an object will all values
//function that is called when server returns a value.
function(data){
$('#linkDiv').html(data.returnValue);
},
//How you want the data formatted when it is returned from the server.
"json"
);
}
</script>
Select HTML
<p>Select event for export to Excel:</p>
<p>
<select name="eventIDExport" id="dropdown">
<option value=0>
<?=$options?>
</select>
</p>
<?php var_dump($_POST['eventIDExport']); ?>
<div id="linkDiv"></div>
Rendered mark-up
<p>Select event for export to Excel:</p>
<p>
<select name="eventIDExport" id="dropdown">
<option value=0>
<option value="1">BIG event</option>
<option value="54">2013 Network Conference</option>
</select>
</p>
NULL
<div id="linkDiv"></div>
Some of the code in index.php to process Ajax request - I think this is triggering the null value?
if (isset($_POST['eventIDExport']))
{
$eventIDExport = $_POST['eventIDExport'];
}else{
$eventIDExport = "";
}

Why you POST sendValue and check if eventIDExport is set?
$.post("scripts/export_to_excel/index.php", {
sendValue: str
^^^^^^^^^
and
if (isset($_POST['eventIDExport']))
^^^^^^^^^^^^^
Your code should be:
if(isset($_POST['sendValue']))
{
$eventIDExport = $_POST['sendValue'];
} else {
$eventIDExport = "";
}
or
$.post("scripts/export_to_excel/index.php", {
eventIDExport: str

Related

How do I set selected value that is base on drop-down list in Jquery and assign it to my model?

I need the value from the option to be assigned to my model once the user clicks on the specific option.
<select name="isEmailVerified" class="form-select">
<option value="" selected> all </option>
<option value="true"> verified </option>
<option value="false"> unverified </option>
</select>
expected value => #Model.IsEmailVerified.XXXXX(my value)
What I usually do when I want to asyncronously send data back and forth is this:
I take advantage of Tag Helpers as they're great and saves you a ton of boilerplate code, so I create a standard <form> element without an actual Submit button, just a div that looks like one. You might want to check official MSDN Documentation for the Select Tag Helper to create an appropriate model.
#model VerificationModel
<form asp-action="CheckEmail" method="post">
<select asp-for="IsEmailVerified" asp-items="Model.VerificationTypes">
<div id="SubmitCheck" class="btn">Check email</div>
</form>
Create a javascript function that takes care of the actual submitting chore. Since the form is created with the Tag Helpers, the request body will automatically bind
$('#SubmitCheck').on('click', function() {
let form = $(this).parents('form')[0];
let formData = new FormData(form);
let request = function () {
return fetch(form.getAttribute('action'), {
method: 'POST',
body: formData
});
};
let onresponse = function() {
// do some preliminary actions on 200 response
}
let callback = function() {
// deal with response result
}
let onerror = function() {
// deal with errors
}
request()
.then(response => onresponse())
.then(result => callback())
.fail(err => onerror());
})
Add the [FromForm] attribute to Controller props (model is the same used in the page) to ensure model binding
public async Task<CustomResultClass> CheckEmail([FromForm] VerificationModel model)
{
// do something
}

Can't set multiple selected value select2 on edit mode

I'm trying to load selected values from db and set it on the select2. i'm using the select2 4.0.10 version. im loading the data using ajax and set the select option to the select2 element after the document is ready.
so, i tried using the $("#area").val(selectedValues).trigger("change"); but nothing seems to be selected.
here is some code of my view.
<input class="form-control" type="text" id="sourceValues" value="CMS,KDY,RWG">
here is my select2 element
<div class="form-group row">
<label class="col-md-3" for="area">Area Tagih Kolektor</label>
<div class="col-md-9">
<select id="area" class="js-example-basic-multiple form-control" name="area[]" multiple="multiple" required>
</select>
</div>
</div>
and here is my script for set the selected values.
<script>
$(document).ready(function(){
nav_active();
var selectedValues = ["CMS","KDY","RWG"];
$('.js-example-basic-multiple').select2({
placeholder: "Pilih Cabang Area Tagih Collector Agency...",
multiple: true
});
console.log(selectedValues);
//Date picker
$('#tgl_berlaku').datepicker({
autoclose: true
})
//Prevent enter to submit
$(window).keydown(function(event){
if(event.keyCode == 13) {
event.preventDefault();
alertify.error('Untuk melakukan submit form, tekan tombol "Simpan"!');
return false;
}
});
$.ajax({
url: "<?php echo base_url();?>ama/c_agency/populate_dropdown_cabang",
type: 'GET',
success: function(data) {
var html = '';
var j;
data = JSON.parse(data);
for(j=0; j<data.length; j++){
html += '<option value="'+data[j].GroupBranchID+'">'+data[j].branch+'</option>';
}
var posisi = "#area";
$(posisi).append(html);
}
});
$("#area").val(selectedValues).trigger("change");
});
function nav_active(){
var d = document.getElementById("nav-ama-agency");
d.className = d.className + "active";
}
</script>
there is no error when im running the script.
You need to change the way you are appending options to Select Box in your ajax success callback.
Instead of following way to append options.
data = JSON.parse(data);
for(j=0; j<data.length; j++){
html += '<option value="'+data[j].GroupBranchID+'">'+data[j].branch+'</option>';
}
You need to append options using the following method
for(j=0; j<data.length; j++){
var option = new Option(data[j].branch, data[j].GroupBranchID );
$("#area").append(option);
}
Document states that
New options can be added to a Select2 control programmatically by creating a new Javascript Option object and appending it to the control:
Here is the JS Fiddle which adds New Option to Select Box on a Click Event. In your case, Click Event fires an AJAX Call and remotely fetches data.

vue.js: vue-multiselect, clearing input value after selected

I am working on my project in laravel/vue.js and I decided to use simple vue-multiselect to choose categories from my database. Thing is I want to clear the value from input field (to look for item in list).
My multiselect component:
<multiselect
v-model="value"
placeholder="Find the category"
label="category_name"
:options="categories"
#input="addReceiversFromCategory">
</multiselect>
I try to clear an v-model but it work only on first select after page load (and also it is not a smart way..).
Last thing i try was the :clear-on-select="true" but it works onlu when multiple is true (which I dont want to be true).
I think its simple to do but I didn't find any way in documentation doc
If your v-model is just modeling the value selected, then you need to use that value however you want and reset value to null. I don't really know how your component is set up but it would look something like this:
<template>
<select v-model="value" v-on:change="doSomething()">
<option :value="null">-- Select --</option>
<option value="foo">Foo</option>
<option value="bar">Bar</option>
</select>
</template>
<script>
module.exports = {
data: function(){
return {
value: null
};
},
methods: {
doSomething: function() {
if( this.value ) {
var data = this.value; // now you can work with data
this.value = null; // reset the select to null
}
}
}
}
</script>

Passing file from ajax to spring contorller

I have form in that, apart from other fields, there is file drop down and file browser button. When the user uploads a file and clicks the button, an Ajax call is made and the file is submitted to the controller. The Javascript shows the file, but in controller it's empty.
HTML:
<label for="selectEnclosure" style="margin-left:8%; ">Select an Enclosure:</label>
<select id="templateEnclosuresDropDown" class="validate[required] input_user" style="width:25%" title="Select>Enclosure"</select>
<c:forEach items="${templateEnclosures}" var="templateDDEnclosure" varStatus="loopStatus">
<c:if test="${templateEnclosure.enclosureType.name!='Default'}"> {
<option value="${templateDDEnclosure.persistentId}"> ${templateDDEnclosure.enclosure.name} </option>
</c:if>
</c:forEach>
<option value="0">Additional Enclosure</option>
Ajax call:
userhome.upload = function() {
alert(" pelae sai");
var form=$('<form></form>');
form.attr("method", "post");
form.attr("action", SECURE_CONTEXT_PATH_ROOT + "/letter/melletter/uploadEnclosure")
form.processData()
var field =$('<input></input>');
field.attr("enclosureFile", $('#enclosureFile').prop('files')[0]);
field.attr("enclosurename" ,$('#templateEnclosuresDropDown :selected').text());
field.attr("templateId",$("#codeNameId").val());
var url = SECURE_CONTEXT_PATH_ROOT + '/letter/melletter/uploadEnclosure';
$(document.body).append(form);
form.submit();
}
First thing to do would be adding this attribute to your form element:
enctype="multipart/form- data"

Trying to check each form input and blank its default value in jquery ajaxform()

I am using the ajaxform() plugin, which so far is working well. However, my input fields have default values, and if the user just submits the untouched form, I need to blank them out before the form is submitted using the beforeSubmit: callback.
In nutshell, I don't know the syntax to check the forms input fields and stop the submit if necessary. I have an idea its using the each() method and this.defaultValue, and maybe a return false? but I'm not sure of the details.
Could anyone perhaps give me an idea? Thanks. Heres my code so far, its the checkValues() function that I'm stuck with.
$(document).ready(function(){
//========= Functions =========
function styleForm() {
$('.quickcontact label').hide();
$('input[type="text"],textarea').addClass("idleField");
$('input[type="text"],textarea').focus(function() {
$(this).removeClass("idleField").addClass("focusField");
if (this.value == this.defaultValue){
this.value = '';
}
if(this.value != this.defaultValue){
this.select();
}
});
$('input[type="text"],textarea').blur(function() {
$(this).removeClass("focusField").addClass("idleField");
if ($.trim(this.value) == ''){
this.value = (this.defaultValue ? this.defaultValue : '');
}
});
}
//options for ajaxform() function
var options = {
target: '.quickcontactDisplay', // target element(s) to be updated with server response
beforeSubmit: checkValues, // pre-submit callback
success: reBind // post-submit callback
// other available options:
//url: url // override for form's 'action' attribute
//type: type // 'get' or 'post', override for form's 'method' attribute
//dataType: null // 'xml', 'script', or 'json' (expected server response type)
//clearForm: true // clear all form fields after successful submit
//resetForm: true // reset the form after successful submit
// $.ajax options can be used here too, for example:
//timeout: 3000
};
//rebinds the ajax functionality to updated form html
function reBind() {
// re-do the form, as it has just been replaced
$('form.quickcontact').ajaxForm(options);
styleForm();
}
//checks for default values of form on submit to prevent them being submitted
function checkValues(){
}
// ==== logic =====
$('form.quickcontact').ajaxForm(options);
styleForm();
});
And my form html:
<form action="/enquiries/add" method="post" id="EnquiryAddForm" class="quickcontact">
<input type="hidden" value="POST" name="_method"/>
<input type="hidden" id="EnquiryVisitorId" value="276" name="data[Enquiry][visitor_id]"/>
<input type="text" id="EnquiryName" maxlength="200" value="Your name" name="data[Enquiry][name]"/>
<input type="text" id="EnquiryEmailAddress" maxlength="200" value="Your Email" name="data[Enquiry][emailAddress]"/>
<textarea id="EnquiryEnquiry" rows="6" cols="30" name="data[Enquiry][enquiry]">Your Email Address</textarea>
<input type="submit" value="Ok, I'm done"/>
</form>
You are abusing the default value as a label. This is causing you problems. Rather then trying to work around those problems, I suggest fixing the cause instead.
When setting default values — set default values. Don't use the default value as a pseudo-label. Use a <label> element instead.
Haven't you looked at the documentation?
beforeSubmit:
Callback function to be invoked before the form is submitted. The
'beforeSubmit' callback can be
provided as a hook for running
pre-submit logic or for validating the
form data. If the 'beforeSubmit'
callback returns false then the form
will not be submitted. The
'beforeSubmit' callback is invoked
with three arguments: the form data in
array format, the jQuery object for
the form, and the Options Object
passed into ajaxForm/ajaxSubmit. The
array of form data takes the following
form:
[ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
Default value: null
Here the idea, didn't check it yet.
function checkValues(formData, jqForm, options)
{
for( var i in formData)
if ( formData[i].value == "")
return false;
return true;
}
sounds as if you need to:
run through all the inputs / textarea at the start and grab the default values, then stick it into an associative array with the element id as key
within checkValues, iterate through inputs once again and compare the pre-submit value against your array - when finding a match, you can set the value to "".

Resources