Javascript with Spring not send data from field - javascript

I am new to Javascript and spring coding.
It is a web app working on Spring framework and with frontend with Mustache template with jQuery.
What I want add new form field (id="exampleTextarea") to the working example. I think this problem is on JavaScript part because checking in java code back null on added field value.
Anybody can direct me what things I am missing?
In post.html I added new field, smile duplicate existed on.
<!-- add textarea in form-->
<div class="form-group">
<label for="exampleTextarea" class="col-sm-2 control-label" >Textarea</label>
<div class="col-sm-10 ">
<textarea type="text" class="form-control input-sm" id="exampleTextarea" name="exampleTextarea" rows="3"></textarea>
</div>
</div>
In graphstory.js javascript file was changed functions.
addContent(), contentformToJSON(), on
.on()
$('#contentAddEdit').on('click', 'a#addcontent', function() {
console.log( $( this ).text() );
if ( $("#contentform").is(":visible") ) {
$("#addcontent").text('Add Content');
$("#contentform")[0].reset();
$("#contentform").hide();
$("#btnSaveContent").text('Add Content XXX');
}else{
$("#contentform").show();
$("#addcontent").text("Cancel");
$("#btnSaveContent").text('Add Content');
}
return false;
});
addContent()
function addContent(){
$.ajax({
type: 'POST',
contentType: 'application/json',
url: '/posts/add',
dataType: "json",
data: contentformToJSON(),
success: function(data, textStatus, jqXHR){
$('#content').prepend('<tr><td>'+data.title+'
<br/>tags: '+data.tagstr+' ::
//text fild
<br/>Textarea: '+data.exampleTextarea+' ::
Posted by '+data.userNameForPost+' at '+data.timestampAsStr+'<br/></td></tr>');
$('#title').val("");
$('#url').val("");
$("#contentform").hide();
$("#addcontent").text('Add Content');
},
error: function(jqXHR, textStatus, errorThrown){
alert('add contnt error: ' + errorThrown);
}
});
}
contentformToJSON()
function contentformToJSON() {
/* added text fild*/
if($("#tagstr").length == 0 | $("#exampleTextarea").length == 0) {
return JSON.stringify({"title": $('#title').val(), "url": $('#url').val() });
}if else($("#tagstr").length == 0){
return JSON.stringify({"title": $('#title').val(), "url": $('#url').val(), "exampleTextarea": $('#exampleTextarea').val() });
}if else($("#exampleTextarea").length == 0){
return JSON.stringify({"title": $('#title').val(), "url": $('#url').val(), "tagstr": $('#tagstr').val() });
}else{
return JSON.stringify({"title": $('#title').val(), "url": $('#url').val(), "tagstr": $('#tagstr').val(),"exampleTextarea": $('#exampleTextarea').val() });
}
}
I changes the code only in two files post.html and graphstory.js here code from files.
Here is post.html
<div class="global/base-app"><!-- add textarea in form-->
<div class="form-group">
<label for="exampleTextarea" class="col-sm-2 control-label" >Textarea</label>
<div class="col-sm-10 ">
<input type="text" class="form-control input-sm" id="exampleTextarea" name="exampleTextarea" rows="3"></textarea>
</div>
</div>

I found a cure for this stack. It was made from html tag <textarea>. Exchange it with <input> works fine.

Related

How I can upload and show temporary images inside html with javascript

How I can upload and show temporary images inside HTML with javascript? I show my code below. Please check and help me.
//Portfolio Images upload
function Portfolio_Image_upload_form_tow() {
FileUpload = $("#FileUpload_towId").val();
var data = new FormData();
data.append('FileName', $('#load_Portfolio_image_tow')[0].files[0]);
var ReaderObj = new FileReader();
var imgname = $('#load_Portfolio_image_tow').val();
var size = $('#load_Portfolio_image_tow')[0].files[0].size;
var ext = imgname.substr((imgname.lastIndexOf('.') +1));
if(ext=='jpg' || ext=='jpeg' || ext=='png' || ext=='gif' || ext=='PNG' || ext=='JPG' || ext=='JPEG'){
$.ajax({
url: FileUpload,
type: "POST",
dataType : "json",
data: data,
contentType: false,
cache: false,
processData:false,
enctype: 'multipart/form-data',
mimeType:"multipart/form-data",
success: function(response){
var msgType = response.msgType;
var msg = response.msg;
var filename = response.FileName;
if (msgType == 'success') {
$("#Portfolio_image_tow_show").html('<img src="'+public_path+'/media/'+filename+'">');
$("#Portfolio_image_tow").val(filename);
$("#Portfolio_image_tow_errorMgs").hide();
$("#Portfolio_image_tow_errorMgs").html('');
} else {
$("#Portfolio_image_tow_show").html('');
$("#Portfolio_image_tow").val('');
$("#Portfolio_image_tow_errorMgs").show();
$("#Portfolio_image_tow_errorMgs").html(msg);
}
},
error: function(){
return false;
}
});
}else{
$("#Portfolio_image_show").html('');
$("#Portfolio_image").val('');
$("#Portfolio_image_errorMgs").show();
$("#Portfolio_image_errorMgs").html(langtext.Sorry_only_you_can_upload_jpg_png_and_gif_file_type);
}
}
<div class="col-md-6">
<div class="form-group">
<label for="Portfolio_image_tow"><span class="red">*</span> {{ __('Portfolio Image') }}</label>
<div class="errorMgs display-none" id="Portfolio_image_tow_errorMgs"></div>
<div class="file_up">
<input type="text" name="Portfolio_image_tow" id="Portfolio_image_tow" class="form-control parsley-validated" data-required="true" readonly>
<div class="file_browse_box">
<input type="file" name="load_Portfolio_image_tow" id="load_Portfolio_image_tow" class="file_browse" multiple>
<label for="load_Portfolio_image_tow" class="file_browse_icon"><i class="fa fa-window-restore"></i>{{ __('Browse') }}</label>
</div>
</div>
<small class="form-text text-muted">{{ __('Portfolio image size 400x350 pixels or 400x450 pixels') }}</small>
<div class="file_up_box tp-image-w" id="Portfolio_image_tow_show"></div>
</div>
</div>
Basically I want add multiple image with file input and show it under id="Portfolio_image_tow_show" div but it's not working. if anything wrong here please talk where I mistake.

Highlight and append msg to element on return from .ajax

Upon ajax successful return, the return data contains status. if status is false(not ajax fail), return data contains array of element names and associated error message. The goal is to replicate .validate() error functionality by appending msg after element and highlight.
HTML form:
<form class="form-horizontal" id="chngPwdForm" action="changepwd.php" method="post">
.
. various HTML....
.
<div class="form-group">
<div class="alert alert-div font-weight-bold" id="errorTxt" role="alert" style="display:none;"> </div>
<label for="crntPwd">Existing Password:</label>
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-key fa-fw"></i></span>
<input type="password" class="form-control" id="crntPwd" name="crntPwd" required>
</div>
</div>
.
. more HTML follows
.
JQUERY:
.
.yada, yada, yada
.
$("#chngPwdForm").submit(function(event){
event.preventDefault();
if ($("#chngPwdForm").valid() ) {
$('#chngPwdForm div[id="errorTxt"]').hide();
Msg = $('#chngPwdForm div[id="errorTxt"]').text("Password changed. Click on Login to continue.");
var formURL = $("#chngPwdForm").attr('action');
$.ajax({
url: formURL,
type: 'POST',
data: $(this).serialize(),
dataType: 'JSON'
})
.done (function(data, textStatus, jqXHR) {
if (!data.status) {
var Msg = "Password Not Changed. Password Change Failed.";
var element;
var errorObj = new Error("");
$.each(data.Msg, function(elemName, errMsg) {
element = $("#chngPwdForm").filter("#" + elemName);
errorObj.message = errMsg;
$(element).closest(".form-group").addClass("has-error");
errorObj.insertAfter(element);
});
}
$('#chngPwdForm div[id="errorTxt"]').text(Msg).show();
})
.fail (function(response){
var Msg = "chngPwd call failed. errorThrown: " + response;
var obj = JSON.stringify(response);
alert("obj is: " + obj);
$('#chngPwdForm div[id="errorTxt"]').text(Msg);
})
}
else {
$('#chngPwdForm div[id="errorTxt"]').text('Please Correct errors').show();
}
return false;
The JSON response from changepwd.php:
{\"status\":false,\"Msg\":{\"crntPwd\":\"Current Password may only contain a-z, A-Z, 0-9, ! or #\"}
JS error
"TypeError: errorObj.insertAfter is not a function" is thrown for
"errorObj.insertAfter(element);"
The implemented solution:
JQuery:
// New Code has leading and trailing *
$("#chngPwdForm").submit(function(event){
*$(".chngPwderr").removeClass("error").text('');* //used to remove old messages
event.preventDefault();
if ($("#chngPwdForm").valid() ) {
$('#chngPwdForm div[id="errorTxt"]').hide();
Msg = $('#chngPwdForm div[id="errorTxt"]').text("Password changed. Click on Login to continue.");
var formURL = $(this).attr('action');
$.ajax({
url: formURL,
type: 'POST',
data: $(this).serialize(),
dataType: 'JSON'
})
.done (function(data, textStatus, jqXHR) {
if (!data.status) {
var Msg = "Password Not Changed. Password Change Failed.";
var focusSet = false;
$.each(data.Msg, function(elemName, errMsg) {
*$("#" + elemName).attr("type", "text");
if (!$("#" + elemName).parent().hasClass("error")) {
$("#" + elemName).parent().append('<div class="chngPwderr error">' + errMsg + '</div>');
}
if (!focusSet) {
$("#" + elemName).focus();
focusSet = true;
}*
});
}
$('#chngPwdForm div[id="errorTxt"]').text(Msg).show();
})

Ajax not Writing to Database

I have an HTML form that I'm trying to read data from and write into a database. A sample of the HTML for the form is shown below:
<div id="form">
<div class="container-tabby1">
<div class="wrap-tabby1">
<form class="tabby1-form validate-form">
<span class="tabby1-form-title">
New Form
</span>
<div class="wrap-inputtabby validate-input bg1" data-validate="Internal Error">
<span class="label-inputtabby">Change Request Number</span>
<input id="ChangeRequestNo" class="inputtabby" type="text" name="ChangeRequestNo" onload="onLoad" readonly>
</div>
<div class="container-contact100-form-btn">
<input id="submitRequest" type="button" class="contacttabby-form-btn" value="Submit Request" onclick="SaveChangeRequest()"/>
</div>
The ajax used to write this to the database is as follows:
function SaveChangeRequest() {
var o = form.getData();
var errorMsg = "";
msg = mini.loading("Submit...");
var jsonform = mini.encode(o);
debugger;
$.ajax({
url: urlCR,
type: "post",
data: { CR: jsonCR },
cache: false,
success: function (text) {
debugger;
if (text != null && text != '') {
mini.hideMessageBox(msg);
onOk();
}
else {
jAlert("Submit failed", "Error Message");
}
},
error: function (jqXHR, textStatus, errorThrown) {
mini.hideMessageBox(msg);
alert(jqXHR.responseText);
}
})
Every time I attempt to submit to the database I get the "Submit failed" error message. I have another form as shown below that works perfectly fine:
<div id="form" style="margin-left:5px;margin-right:5px;">
<table width="100%;" align="center">
<tr>
<td width="100px;"><label>Applicant:</label></td>
<td width="300px;"><input id="ApplicantEmail" name="ApplicantEmail" class="mini-textbox" allowinput="false" style="width: 290px;" /></td>
<td align="center">
<input type="button" class="searchsubmit" value="Submit" onclick="SaveForm()" style="width:120px;" />
<script type="text/javascript">
mini.parse();
SecurityLog_PageLoad();
var urlPersonInfo = "data/AjaxSecurityService.aspx?method=Sec_CurUserLoginInfo";
var urlFormGetItem = "Data/ajaxservice.aspx?method=CSC_Form_GetWholeFormo&FormID=";
var urlFormUpdateWithNotice = "Data/ajaxService.aspx?method=CSC_Form_UpdateChanges";
var form = new mini.Form("#form");
var searchGrid = mini.get("dgSearchResult");
var applyGrid = mini.get("dgApplyResult")
function SaveForm() {
var o = form.getData();
form.validate();
if (form.isValid() == false) return;
var errMsg = '';
if (o.RequestComments == null || o.RequestComments == '')
errMsg=".Justification is empty.\n";
if (applyGrid.data.length < 1)
errMsg+= ".At least apply one report before you submit.\n";
if (errMsg != '')
{
jAlert(errMsg, "Validate Error");
return;
}
$.ajax({
url: urlFormUpdateWithNotice,
type: "post",
data: { dataForm: jsonClaim, dataList: jsonList },
cache: false,
success: function (text) {
var impactID = mini.decode(text);
if (impactID != null && impactID != "") {
SecurityLog_Submit('Submit',impactID);
CloseWindow("ok");
};
},
error: function (jqXHR, textStatus, errorThrown) {
mini.hideMessageBox(msg);
alert(jqXHR.responseText);
}
});
</script>
Why does the latter form work while the first form does not?
This is not a answer as such at this stage, but a few points of note that might help reach an answer:
the code that displays the "Submit failed" message is actually in the success response section. It shows the message if there is a non-null, non-empty string returned by the AJAX call. It would help if the string was output to help debug if it's an actual failure to save the data, or not
following on from the above, check if the data submitted has been saved or not - that will help establish what is actually happening
In the second form, we can see the URL (urlFormUpdateWithNotice) but in the first we can't, so it's hard to tell if that is a problem (e.g. there could be a typo in the URL)
Ideally you need to include as much detail as possible, including any critical data, so that diagnosing the problem is easier and quicker.
In any case the best place to start is to see what text is in success: function (text) {... and take it from there.

How to get only the newest value response from Ajax?

I have the issue with AJAX response and display errors.
For example, when I submit my form, I see 1 in console, but If I write something in first input and submit again, then
I see:
1
2
Ajax below read 1 and 2 as both responses, so I see 2 errors but I should see only the newest, so it should be only 2.
Also, I getting value when I try to use search (invite), but Ajax skipping everything and showing only success message after Submit.
ajax.js
$(document).ready(function() {
$('#form_create_circle').submit(function(event){
event.preventDefault();
$.ajax({
url: 'form-create-circle.php',
type: 'POST',
data: $('#form_create_circle').serialize(),
dataType: 'json',
success: function(response) {
console.log(response);
if (response == 1) {
$('#title').addClass('is-invalid');
$('#invalid_title').append('<div class="invalid-feedback"><p>This field is required.</p></div>');
} else if (response == 2) {
$('#invite').addClass('is-invalid');
$('#invalid_invite').append('<div class="invalid-feedback"><p>This field is required.</p></div>');
} else if (response == 3) {
$('#color').addClass('is-invalid');
$('#invalid_color').append('<div class="invalid-feedback"><p>This field is required.</p></div>');
} else {
// success message
$('#_noti-container').append('<div class="noti noti-success noti-top-right noti-close-on-click noti-on-leave" style="z-index:100000"><div class="noti-content-wrapper"><div class="noti-content">Circle has been created!</div><div class="noti-close">×</div></div></div>');
}
}
});
return false;
});
});
form-create-circle.php
require_once($_SERVER['DOCUMENT_ROOT'].'/system/mysql/config.php');
$title = $db->EscapeString($_POST['title']);
$invite = $db->EscapeString($_POST['invite']);
$color = $db->EscapeString($_POST['color']);
$time = date('Y-m-d H:i:s');
$search = $db->QueryFetchArrayAll("SELECT * FROM user_about WHERE firstname LIKE '%".$invite."%' OR lastname LIKE '%".$invite."%'");
foreach ($search as $key) {
echo "
<div class='invite_search_cont'>
<div class='invite_search_img'><img src='{$key['profile_image']}'></img></div>
<div class='invite_search_name'>{$key['firstname']} {$key['lastname']}</div>
</div>
";
}
if ($title == '' || (!preg_match('/^[a-zA-Z0-9]+$/', $title))) {
echo 1;
} elseif ($search == '') {
echo 2;
} elseif ($color == '') {
echo 3;
} else {
$db->Query("INSERT INTO user_circle (user_id, user_added, title, color, time_added) VALUES ('{$user['id']}', '$invite', '$title', '$color', '$time')");
}
HTML
<form method='POST' id='form_create_circle'>
<div class='modal-body'>
<div>
<div class='form-group'>
<input type='text' name='title' id='title' placeholder='Family' class='form-control'>
<div id='invalid_title'></div>
</div>
<div class='form-group'>
<input type='text' name='invite' id='invite' placeholder='Search' class='form-control'>
<div id='invite_search_result'></div>
<div id='invalid_invite'></div>
</div>
<div class='form-group'>
<select name='color' id='color' class='form-control'>
<option value='0'>white</option>
<option value='1'>yellow</option>
<option value='2'>red</option>
</select>
<div id='invalid_color'></div>
</div>
</div>
</div>
<button type='submit' class='btn btn-primary' id='ajax_create_circle'>Submit</button>
</form>
<div id='_noti-container' class='noti-t-right'></div>
Sounds to me you just need to add $('#invalid_...').empty() to the start of the script before the ajax or change .append to .html
Also removeClass on all the divs involved:
$('#form_create_circle').submit(function(event) {
event.preventDefault();
$.ajax({
url: 'form-create-circle.php',
type: 'POST',
data: $('#form_create_circle').serialize(),
dataType: 'json',
success: function(response) {
console.log(response);
$('#title, #invite, #color').removeClass('is-invalid');
$("[id^=invalid]").empty(); // empty all error divs
if ("123".indexOf(response) > -1) {
var type = ["", "title", "invite", "color"][response];
$('#' + type).addClass('is-invalid');
$('#invalid_' + type).html('<div class="invalid-feedback"><p>This field is required.</p></div>');
} else {
// success message
$('#_noti-container').html('<div class="noti noti-success noti-top-right noti-close-on-click noti-on-leave" style="z-index:100000"><div class="noti-content-wrapper"><div class="noti-content">Circle has been created!</div><div class="noti-close">×</div></div></div>');
}
}
});
});

How to submit form using JQuery and Spring Controller

I am having difficulty understanding why my form submits successful when i disable the ajax function. When i enable ajax on my input form. Input values i fill are not submitted. I used chrome developer tools to check the FormData being submitted. I realized nothing was being submit.
Hence i get an error asking me to fill those fields.
Controller
#PostMapping(value = "/basicAjax.json")
#ResponseBody
public ResponseEntity<Object> addCertJson(#Valid #ModelAttribute CertificateProgramme certificate, BindingResult result, Principal principal) {
User user = (User) ((UsernamePasswordAuthenticationToken) principal).getPrincipal();
certificate.setUser(user);
if (result.hasErrors()) {
List<String> errors = result.getAllErrors().stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage)
.collect(Collectors.toList());
return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);
} else {
certificateService.save(certificate);
return new ResponseEntity<>(HttpStatus.ACCEPTED);
}
}
JS Script
var $form = $('.editCert');
var formData = $form.serialize();
var url = $form.attr('action');
var storage = {};
$.each($('.editCert').serializeArray(), function(i, field) {
storage[field.name] = field.value;
});
$form.on('submit',function(e){
e.preventDefault();
$.ajax(url,{
dataType: 'JSON',
data: storage,
type: "POST",
}).done(function(response){
if(response.status === 'SUCCESS'){
console.log('I am Okay' + response);
}else{
console.log('Holly Molly');
}
}).fail(function(jqXHR, textStatus, errorThrown){
var errorInfo="";
for(i =0 ; i <jqXHR.responseJSON.length ; i++){
errorInfo += "<br>" + (i + 1) +". " + jqXHR.responseJSON[i];
}
var $myerror = $form.find('.flash').addClass(' failure');
$myerror.html("Please correct following errors: " + errorInfo);
});
});
Form
<form method="post" th:object="${certificate}"
th:action="#{${action1}}" class="form-inline inline new-item editCert">
<input type="hidden" th:field="*{id}"/>
<div th:replace="common/layout :: flash"></div>
<div class="flash"></div>
<fieldset>
<legend th:text="${heading}"> Personal Information</legend>
<div class="row" th:classappend="${#fields.hasErrors('fullName')}? 'error' : ''">
<input type="text" class="form-control input-sm" th:field="*{fullName}"
placeholder="Full Name example Jane Doe"/>
<div class="error-message" th:if="${#fields.hasErrors('fullName')}" th:errors="*{fullName}"></div>
</div>
<div class="row" th:classappend="${#fields.hasErrors('gender')}? 'error' : ''">
<select th:field="*{gender}" class="form-control input-lg ">
<option value="">[Select Gender]</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<div class="error-message" th:if="${#fields.hasErrors('gender')}" th:errors="*{gender}"></div>
</div>
<div class="row" th:classappend="${#fields.hasErrors('date')}? 'error' : ''">
<input th:type="date" data-value="20/04/2015" class="form-control input-sm datepicker" th:field="*{date}"
placeholder="Date Of Birth"/>
<div class="error-message" th:if="${#fields.hasErrors('date')}" th:errors="*{date}"></div>
</div>
Solved my problem, Moved the form iteration into the submit $.ajax submit function
$form.on('submit',function(e){
e.preventDefault();
$.each($(this).serializeArray(), function(i, field) {
storage[field.name] = field.value;
});
console.log(storage);
$.ajax(url,{
//dataType: 'json',
data: storage,
type: "POST",
}).done(function(response){
console.log('I am Okay' + response);
}).fail(function(jqXHR, textStatus, errorThrown){
console.log(jqXHR);
if(jqXHR.status === 400){
var errorInfo="";
for(i =0 ; i <jqXHR.responseJSON.length ; i++){
errorInfo += "<br>" + (i + 1) +". " + jqXHR.responseJSON[i];
}
var $myerror = $form.find('.flash').addClass(' failure');
$myerror.html("Please correct following errors: " + errorInfo);
}
});
});

Categories

Resources