We are getting a issue wherein while submitting a form via javascript one of the parameters (invoiceCodes) is not sent to the server. Below is the snippet of the javascript code.
The flow is as follows. When user clicks on "Print" button validateTransition() method is called in which we make a ajax call. After response of that ajax we call couponPopup(url, invoiceCodes). In this function we submit newWinForm but sometimes invoiceCodes parameter is sent empty.
Also checkForInvoiceCode is true in this case which require user to input invoice codes
Is there anything wrong in the manner in which we are putting values in the form which may lead to invoiceCodes being not sent sometimes.
function couponPopup(url, invoiceCodes)
{
var selectedOrders = '';
$(".selectedOrder:checked").each(function() {
selectedOrders += $(this).val() + ',';
});
var frm = document.forms["newWinForm"];
frm.action = url;
frm.selectedShipments.value= selectedOrders;
frm.invoiceCodes.value = invoiceCodes;
console.log("Selected orders are "+selectedOrders);
console.log("Invoice codes with them in order are "+invoiceCodes);
document.getElementById("hiddenInvoiceCodes").value=invoiceCodes;
document.getElementById("hiddenselectedShipments").value=selectedOrders;
frm.submit();
return false;
}
function validateTransition() {
$('#statusChangeSuccess').hide();
$('#statusChangeFail').hide();
var selectedOrders = '';
var invoiceCodes = '';
var flag = 0;
var spaceError = 0;
var commaError = 0;
$(".selectedOrder:checked").each(function() {
selectedOrders += $(this).val() + ',';
<c:if test="${checkForInvoiceCode}">
var emptyPattern = /^\s*$/;
var commaPattern = /,/;
var inv_code = $("#invoice-code-" + $(this).val()).val().trim();
if (emptyPattern.test(inv_code)) {
spaceError = 1;
flag = 1;
}
if (commaPattern.test(inv_code)) {
commaError = 1;
flag = 1;
}
invoiceCodes += inv_code + ",";
</c:if>
});
if(selectedOrders=='') {
alert('Please select at least one order');
return false;
}
if ( flag ) {
if ( commaError ) {
alert('One or more specified codes have comma, please remove comma from them');
}
if ( spaceError ) {
alert('One or more specified codes has been left blank, please fill them up');
}
if ( !commaError && !spaceError ) {
alert('Please contact tech');
}
return false;
}
var inputdata = {"selectedShipments" : selectedOrders,
"statusCode" : "PRINT"
};
//this is where we are making an ajax call
jQuery(function($){
setTimeout(function(){
var ajaxUrl = '/product/update/';
$.ajax({url:ajaxUrl, type: "POST", dataType: 'json', data:inputdata , success: function(data) {
if(data['status'] == 'success') {
//couponPopup function is called where form is submitted
couponPopup("${path.http}/product/print/", invoiceCodes);
$('#statusChangeSuccess').html(data['message']).show();
$(".selectedOrder:checked").each(function() {
$("#row-" + $(this).val()).remove();
});
} else{
$('#statusChangeFail').html(data['message']).show();
}
}});
}, 10 );
});
return false;
}
<form id="newWinForm" name="newWinForm" action="" method="post" target="_blank" >
<input type="hidden" id="hiddenselectedShipments" name="selectedShipments" value="" />
<input type="hidden" id="hiddenInvoiceCodes" name="invoiceCodes" value="" />
</form>
Controller for the form. Invoice codes is sometimes empty even when we are sending it from client side.
#RequestMapping("/product/print")
public void printSelectedPendingOrders(#RequestParam("selectedShipments") String selectedShipments,
#RequestParam(defaultValue = "", value = "invoiceCodes", required = false) String invoiceCodes, ModelMap modelMap, HttpServletResponse httpResponse)
throws IOException, DocumentException, ParserConfigurationException, SAXException {
Related
The situation
I have a page in which I have multiple forms keeping track of the attendance and one progress_update.
On submit of the progress_update form I have got it so that ajax sends the attendance form submissions separately having used the preventdefault() method to stop the original submission, however I would like to on the condition that no errors were returned by the ajax methods allow the original submission that was originally prevented.
What I have so far:
The ajax function:
function send_attendance(name, lesson, form_id, i) {
var url = '/attendance/' + name + '/' + lesson
$('#error-' + i).hide('slow')
$('#error-' + i).html('')
$.ajax({
type: "POST",
url: url,
data: {
attended: $('#attended' + i).val(),
score: $('#score' + i).val(),
writing: $('#writing' + i).val(),
speaking: $('#speaking' + i).val()},
success: function(data) {
if (data.data.message == undefined) {
allow=false;
if (data.data.score[1] == undefined) {
var error_data = data.data.score[0]
} else {
var error_data = data.data.score[1]
}
$('#error-' + i).show('slow')
$('#error-' + i).html('<p style="color:red;">' + error_data + '</p>')
} else {
console.log(data.data.message) // display the returned data in the console.
}
}
});
}
The Intention:
The intention behind this ajax is to send the forms to a separate route for validation and then on success "receiving data.data.message == 'submitted'" pass to the next form in the loop, while on error set the allow variable to false and display the message in hopes to prevent the final form being submitted at the same time.
The call:
$('#update_form').submit(function (e) {
var allow = true;
for (var i = 0; i < studentcount ; i++) {
send_attendance(name=st[i], lesson=lesson, form_id='attendance-' + i, i=i)
}
if (allow == true){
} else {
e.preventDefault();
}
});
The Problem
In doing what I have done I have ended up with a situation of it either submits the ajax submitted forms and that is that preventing the submit form or it submits the form whether errors occured in the ajax that need to be displayed, now how do I get this to work in the way expected? I have tried the methods involved in these previous questions:
How to reenable event.preventDefault?
How to unbind a listener that is calling event.preventDefault() (using jQuery)?
which revolve around using bind and unbind but this doesn't seem to work as needed and results in a similar error.
Any advice would be greatly appreciated.
Edit:
I have adjusted the code based on the comment below to reflect, however it still seems to be evaluating the allow before the ajax have completed. either that or the ajax function isn't changing the allow variable which is set in the submit() call how could i get this to change the allow and evaluate it after the ajax calls are complete?
The Ajax call
function send_attendance(name, lesson, form_id, i) {
var url = '/attendance/' + name + '/' + lesson
$('#error-' + i).hide('slow')
$('#error-' + i).html('')
var form = $('#' + form_id)
$.ajax({
type: "POST",
url: url,
data: $('#'+ form_id).serialize(),
context: form,
success: function(data) {
console.log('done')
if (data.data.message == undefined) {
allow = false;
if (data.data.score[1] == undefined) {
var error_data = data.data.score[0]
} else {
var error_data = data.data.score[1]
}
$('#error-' + i).show('slow')
$('#error-' + i).html('<p style="color:red;">' + error_data + '</p>')
} else {
console.log(data.data.message) // display the returned data in the console.
}
}
});
The function is being called here:
$('#update_form').submit(function (e) {
e.preventDefault();
var allow = true;
var deferreds = [];
for (var i = 0; i < studentcount ; i++) {
deferreds.push(
send_attendance(st[i], lesson, 'attendance-' + i, i));
}
$.when(...deferreds).then(function() {
if (allow == true){
console.log('True')
} else {
console.log('False')
}
});
I also tried:
$('#update_form').submit(function (e) {
e.preventDefault();
var allow = true;
var deferreds = [];
for (var i = 0; i < studentcount ; i++) {
deferreds.push(
send_attendance(st[i], lesson, 'attendance-' + i, i));
}
$.when.apply(deferreds).done(function() {
if (allow == true){
console.log('True')
} else {
console.log('False')
}
});
I have a HTML form as the output of a java that gets a text from database and fill an input of that form with it. In form I can edit the text that on submit
Is sent back to java via a jquery AJAX call. Through java the text is saved in the database.
If I enter test% in text area it is coming as test% at server side.
Let’s say the HTML form looks like this :
<form id="form_used_0" action="#" method="post" onclick="hideAjaxList();">
<textarea name="summary" id=" summary " data-mini="true"><%=HtmlWriter.preformat(summary)%></textarea>
<a id="saveBtn" class="actionBtn" href="#" data-theme="b" onclick="onSave (this);">Save</a>
</form>
On saveBtn click this AJAX call is made:
function onSave(thisHref)
{
var respData = "";
var id = $("#id").attr("value");
var params = $("#form_used").serialize()+"&ajaxAction=SaveHeader"+"&id="+id;
$.post(ajaxURL, params, function(data){
if(data.length >0)
{
respData = data.substring(data.indexOf("|")+1, data.lastIndexOf("|"));
}
}).complete(function(){
if (respData.length > 0)
{
var responseData = respData.split("|");
var status = responseData[0];
var msg = responseData[1];
if (status == 'SUCCESS')
{
showSuccessMsgHeader(msg);
}
else if (status == 'ERROR')
{
showErrorMsgsOnly(msg);
}
}
});
}
I tried using the serializeArray method but now getting 400 Bad request error. I checked the form data in network tab and found that it is showing as unable to decode value beside input field .
function onSave(thisHref)
{
var respData = "";
var id = $("#id").attr("value");
var x = $("#form_used_0").serializeArray();
var paramsArr = "";
$.each(x, function(i, field){
if(i == x.length - 1){
paramsArr = paramsArr + field.name + "=" + field.value;
} else {
paramsArr = paramsArr + field.name + "=" + field.value + "&";
}
});
var params paramsArr +"&ajaxAction=SaveHeader"+"&id="+id;
$.post(ajaxURL, params, function(data){
if(data.length >0)
{
respData = data.substring(data.indexOf("|")+1, data.lastIndexOf("|"));
}
}).complete(function(){
if (respData.length > 0)
{
var responseData = respData.split("|");
var status = responseData[0];
var msg = responseData[1];
if (status == 'SUCCESS')
{
showSuccessMsgHeader(msg);
}
else if (status == 'ERROR')
{
showErrorMsgsOnly(msg);
}
}
});
}
Would it be possible for anyone to help me on the same.
As per jQuery documentation, The .serialize() method creates a text string in standard URL-encoded notation.
You can use Apache Commons StringEscapeUtils.unescapeHtml() to decode the string at server level.
Alternatively, if required you can pass the text from textarea as an additional param, which you can use it.
Thanks.
I have a script that makes an ajax call to an action in the controller and save some records.
The whole process is working fine but my little issue is to redirect to another page after saving records successfully.
With my code below, the records were added successfully with an alert indicating as it is described in the code "msg + "Courses were Registered"". Rather than doing that I want it to redirect to an action.
Javascript code:
<input type="submit" value="Register Courses" id="register" class="btn btn-rose" />
<script>
$(document).ready(function () {
$("#register").click(function () {
var items = [];
$('input:checkbox.checkBox').each(function () {
if ($(this).prop('checked')) {
var item = {};
item.CourseID = $(this).val();
item.CourseCode = $(this).parent().next().html();
item.CourseName = $(this).parent().next().next().html();
item.Units = $(this).parent().next().next().next().html();
items.push(item);
}
});
var options = {};
options.url = "/Course/SaveCourse";
options.type = "POST";
options.dataType = "json";
options.data = JSON.stringify(items);
options.contentType = "application/json; charset=utf-8;";
options.success = function (msg) {
alert(msg + " Courses were Registered");
};
options.error = function () {
alert("Error while Registering Courses");
};
$.ajax(options);
});
});
</script>
Controller
[HttpPost]
public IActionResult SaveCourse([FromBody]List<CourseRegModel> courseIDs)
{
var user = HttpContext.Session.GetString("currentUser");
if (user == null)
{
return RedirectToAction("Login", "Account");
}
ViewBag.student = user;
var pendingPayment = (from row in _context.BursaryTransactions where row.MatricNo == user && row.ResponseCode == "021" select row).Count();
if (pendingPayment > 0)
{
return RedirectToAction("PaymentSummary", "Student");
}
var student = _context.StStudentInfo.Include(m =>m.AdmInstProgramme.AdmInstDepartment).Include(m =>m.AdmInstClassLevels).FirstOrDefault(m => m.MatricNo == user);
var session = _context.AdmInstProgrammeTypeSession.Include(m => m.AdmInstSemesters).Include(m => m.AdmInstSessions).Include(m => m.AdmInstProgramType).Where(m => m.IsActive == true).FirstOrDefault(m => m.ProgramTypeId == student.ProgrammeTypeId);
foreach (CourseRegModel courseID in courseIDs)
{
courseID.Level = student.AdmInstClassLevels.ClassLevel;
courseID.Semester = session.AdmInstSemesters.Semester;
courseID.Session = session.AdmInstSessions.SessionName;
courseID.Department = student.AdmInstProgramme.AdmInstDepartment.Department;
_context.CourseRegModel.Add(courseID);
}
int courses = _context.SaveChanges();
return Json(courses);
}
Objective is to return RedirectToAction("MyCourses","Courses"); after SaveChanges();
If you want to redirect to another action method why would you use AJAX? But I think you can work around that by performing the redirect in the client side AJAX after it is successfully receive a response you use JavaScript to do the redirect
You can simply redirect your page inside ajax's success handler,
options.success = function (msg) {
window.localtion.href = "/Courses/MyCourses";
// or window.location.href = '#url.Action("MyCourses","Courses")';
};
I want to stop sending information if form validation is false.
I have a button Save with two functions in it:
<span class="logInBTN" v-on:click="validationFields(); function2(model)">Save</span>
The form validation is being proccessed in validationFields():
validationFields() {
if (this.model.codePerson == '') {
document.getElementById('codePerson').style.borderColor = "red";
this.errors.push("Choose a type!\n");
falseValidation = true;
} else {
document.getElementById('codePerson').style.borderColor = "#CCCCCC";
}
if (falseValidation == true) {
alert("Form validation:\n" + this.errors.join(""));
}
}
So if it's not chosen a type from the input field, function2() must not continue.
Update1:
<script>
export default {
components: {
},
data(){
return {
errors: [];
},
},
methods: {
validationFields() {
this.errors = [];
var falseValidation = false;
if (this.model.codePerson == '') {
document.getElementById('codePerson').style.borderColor = "red";
this.errors.push("Choose a type!\n");
falseValidation = true;
} else {
document.getElementById('codePerson').style.borderColor = "#CCCCCC";
}
if (falseValidation == true) {
alert("Form validation:\n" + this.errors.join(""));
}
if(falseValidation == false){
this.createEori(eoriData);
}
}
createEori(eoriData) {
eoriData.state = '1';
eoriData.username = this.$session.get('username');
console.log("updateEori state: " + JSON.stringify(eoriData));
const url = this.$session.get('apiUrl') + 'registerEORI';
this.submit('post',
url,
eoriData
);
},
submit(requestType, url, submitData) {
this.$http[requestType](url, submitData)
.then(response => {
console.log('EORI saved!');
console.log('Response:' + response.data.type);
if("E" == response.data.type){
alert(response.data.errorDescription);
} else {
alert("Saved!");
}
})
.catch(error => {
console.log('EORI rejected!');
console.log('error:' + error);
});
},
},
}
</script>
createEORI is the function2
Update2
Now it works, but the data from the fields it's not send to the server. That's all fields from the page, some are datepickers or an ordinary input text field. Before the change in the browser console show this, if I write a name in the first field it will show up in c1_name etc:
{"state":"1","c1_form":"","c1_identNumber":"","c1_name":"","c1_shortName":"","c1_8_street":"","c1_8_pk":"","c1_8_name":"","c1_8_city":"","c1_8_codeCountry":"","c1_identNumber1":"","c3_name":"","c3_nameShort":"","c3_city":"","c3_codeCountry":"","c3_street":"","c3_pk":"","c3_phone":"","codePerson":"","codeActivity":"","c1_date":"","c5_date":"","c7_date":"","dateFrom":"","dateTo":"","c8_date":"","c1_numberVAT":"","c8_provider":"","c8_number":"","codeMU":"","agreed1":"","agreed2":"","username":"testuser"}
However, after the change the sent data or at least the seen data is only:
{"state":"1","username":"testuser"}
The log is from
console.log("updateEori state: " + JSON.stringify(eoriData));
from createEORI() function
I think it would be better practice to only call one function from the HTML. Something like this:
<span class="logInBTN" v-on:click="submit(model)">Save</span>
submit(model) {
if (this.validateForm(model) == true)
{
// submission process here (maybe call function2())
}
}
validateForm(model) {
if (this.model.codePerson == ''){
document.getElementById('codePerson').style.borderColor = "red";
this.errors.push("Choose a type!\n");
this.handleFalseValidation();
return false;
}
document.getElementById('codePerson').style.borderColor = "#CCCCCC";
return true;
}
handleFalseValidation() {
alert("Form validation:\n" + this.errors.join(""));
}
Ok I fixed the problems with sending the data.
It was my fault.
I will copy the Chris answer. That worked.
When you call this.createEori(eoriData);, eoriData is undefined. It doesn't exist. Use this.createEori(); instead, and in the createEori function, remove the parameter and add var eoriData = {}; as first line. (note this is very basic javascript, how functions and variables work, and completely unrelated to Vue or server requests)
Good day,
I have a php file (db.php) which contains the following function
function edit_record($id, $value){
if($this->db->query('UPDATE tbl_prototype SET value = ' . $value .' WHERE id_component = '.$id)){
$this->register_changes();
return TRUE;
}
return FALSE;
}
Besides, I have some checkboxes in my html page as follows :
<input id="chk01" type="checkbox" data-onstyle="success" data-toggle="toggle">
<input id="chk02" type="checkbox" data-onstyle="success" data-toggle="toggle">
the html page contains also the following script.
<script>
/* AJAX request to checker */
function check(){
$.ajax({
type: 'POST',
url: 'checker.php',
dataType: 'json',
data: {
counter:$('#message-list').data('counter')
}
}).done(function( response ) {
/* check if with response we got a new update */
if(response.update==true){
var j = response.news;
$('#message-list').html(response.news);
sayHello(j);
}
});
};
//Every 1/2 sec check if there is new update
setInterval(check,500);
</script>
<script>
function sayHello(j){
var json=$.parseJSON(j);
var techname = "";
var techname1 = "";
var c;
var w;
$(json).each(function(i,val){
$.each(val,function(k,v){
if (k=="tech_name")
{
techname = "#" + v;
techname1 = v;
}
else
{
console.log("Mon nom est " + techname + " et ma valeur est " + v);
c=document.getElementById(techname1);
if (c.checked)
{
w = 1;
}
else
{
w = 0;
}
console.log(w);
console.log("techname : " + techname1);
if (v != w)
{
console.log ("Pas identique");
if (v==0)
{
// false
uncheckBox(techname);
}
else
{
// true
checkBox(techname);
}
}
else
{
console.log ("Identique");
}
}
});
});
}
function checkBox(pCtrl)
{
toggleOn(pCtrl);
}
function uncheckBox(pCtrl)
{
toggleOff(pCtrl);
}
</script>
Now for my question: where and how should I specify that I would like to run the function 'edit_record' stored in the 'db.php' file with the two parameters ($id and $value).
Contents of 'checker.php' :
<?php require('common.php');
//get current counter
$data['current'] = (int)$db->check_changes();
//set initial value of update to false
$data['update'] = false;
//check if it's ajax call with POST containing current (for user) counter;
//and check if that counter is diffrent from the one in database
//if(isset($_POST) && !empty($_POST['counter']) && (int)$_POST['counter']!=$data['current']){
if(isset($_POST)){
$data['news'] = $db->get_news2();
$data['update'] = true;
}
//just echo as JSON
echo json_encode($data);
/* End of file checker.php */
Thanks a lot for your valuable inputs. Sorry if the question sounds silly (I'm a newbie in php/ajax/jquery programming).
In modern web apps with rich interface You should go for REST API and create controller which should be in You case in checker.php. Example ( checker.php ):
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
//update code
edit_record($_POST['id'],$_POST['counter]);
}
if ($_SERVER['REQUEST_METHOD'] == 'GET'){
//get code
}
ps. i do not see passing id in ajax, you send only counter, so you should add id like:
...
data: {
id:yourId //here your id
counter:$('#message-list').data('counter')
}
Next thing remove from js:
setInterval(check,500);
and create bind:
$("yourcheckboxselector").on("click",function(e){
check($(this).prop("checked") ) //here you have it was checked or not as boolean
});