I am not a java developer, but my company purchase a product to handle their accounting stuff based on java. Now I am facing a problem because they want to prevent repeated invoices on the system and the software allows the user to do it. I called support and they suggested me to create a suppressed field on the client side, copy on that field the message I want to show and read that field when the user tab to the next field. those are a lot of steps and totally inefficient. Below is my code based on what they suggested. It currently showed me the invoice exist message twice.
server side
CSServer.log (Step)
if ((CSEvent.getTarget().getName() == "InvoiceNumber") && (CSEvent.getAction() == "Tabout" ) && (Step == 0))
{
if (!cnn)
{
CSServer.log ("GPCONNECT Lookup::CSForm_OnValidateLookup Connection to the database failed");
}
else
{
Sql = "SELECT COUNT (*) as Result FROM [DYNAMICS].[dbo].[AP_Invoice_Table] WHERE [VendorID] = '" + CSForm.getField("VendorID").getValue() + "' and [DocumentNumber] = '" + CSForm.getField("InvoiceNumber").getValue()+"'";
resultInvSet = cnn.executeSQL(Sql);
var x =null;
x = resultInvSet.getValue("Result");
}
if (x > 0)
{
CSForm.getField("msg").setValue("Invoice number already exist, please check your entry!");
return false;
}
else
{
CSForm.getField("msg").setValue("");
}
}
client side
function InvoiceAmount_OnFocus()
{
var m =CSForm.getField('msg').getValue();
if (m != "")
{
$("#InvoiceNumber").focus();
CSClient.alert(m);
CSForm.getField("InvoiceNumber").setFillColor("FF0000");
}
else
{
CSForm.getField("InvoiceNumber").setFillColor("FFFFFF");
}
return true;
}
Could someone please showed me the right way to handle this?
Update:
Client and server use SOAP and HTTP call to communicate.
Create a webmethod that you call via AJAX and pop the javascript alert based on the result of that function.
example (in your .aspx page):
function doSomething(id) {
$.ajax({
type: "POST",
url: "Do_Something.aspx/DoSomething?id=" + id,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response);
}
});
In Do_Something.aspx.cs:
[WebMethod]
public static string DoSomething(string id)
{
var docs = SqlHelper.SelectAllByInvoiceId(id);
if (docs.Count > 0)
{
return "exists";
}
return "does not exist";
}
Step 1: Create AJAX function to talk to server side function.
Step 2: Return message from server side function and handle that in AJAX function (success or done).
Step 3: Alert message if ajax function catches any result.
For ajax implementation you can refer: http://www.w3schools.com/jquery/ajax_ajax.asp
Or
http://api.jquery.com/jquery.ajax/
Related
I am developing a responsive user interface in CakePHP 4.x which occasionally uses Ajax requests.
My Ajax requests are performing just fine but I am having a lot of trouble incorporating a CSV-file in the request so my controller can handle the data. What I want to accomplish is that that I can choose a CSV-file, press submit and that the Ajax-request sends the file to the controller and uses the independent rows to update the database.
My code:
Javscript:
function importProducts() {
/* Getting form data */
let form = document.getElementById('importProductsForm');
let formData = new FormData();
let file = $(form.products_file).prop('files')[0];
formData.append("csv_file", file);
/* Moving product stock */
ajaxRequest('Products', 'importProducts', formData, processImportProducts);
}
function ajaxRequest(controller, action, data = null, callback = null) {
$.ajax({
url : "<?=$this->Url->build(['controller' => '']);?>" + "/" + controller + "/" + action,
type : 'POST',
data : {
'data': data
},
dataType :'json',
/*processData: false,*/
/*contentType: false,*/
success : function(dataArray) {
let response = dataArray.response;
if (typeof response.data !== 'undefined') {
data = response.data;
if (callback != null) {
callback(data);
}
} else if (response.success == 0) {
data = null;
giveError(response.errorTemplate);
} else {
data = null;
if (callback != null) {
callback(data);
}
}
},
error : function(request,error)
{
console.error(error);
}
});
}
At the moment the controller function does not do anything special but receiving and setting the data:
public function importProducts() {
$this->RequestHandler->renderAs($this, 'json');
$response = [];
if($this->request->is('post')) {
$data = $this->request->getData();
$response['test'] = $data;
} else {
$response['success'] = 0;
}
$this->set(compact('response'));
$this->viewBuilder()->setOption('serialize', true);
$this->RequestHandler->renderAs($this, 'json');
}
After some research I discovered I could use the FormData object to send the file. The error I then received was 'illegal invocation'. After some more research I discovered this had to with automatic string parsing by Ajax. According to some other StackOverflow posts I could resolve this by setting the processdata and contenttype properties to false. This fixed the problem but resulted in an Ajax request which always would be empty (that does not contain any data). I tested this without the CSV-file with a regular data object that contains a variable with a string but also resulted in a empty request (no data send to controller).
So my problem is that without the processdata property as false I get the 'illegal invocation' error, otherwise with processdata as false I literary do not receive any data in my controller. I am looking for solution to resolve this problem so I can send my CSV-file or at least the data within the file to my controller.
Other solutions than using the FormData are also welcome, for example I tried to read the CSV-file in Javascript and turn this into another object (with the jquery csv api) to send to the controller, sadly without success until now.
Good day guys. In my laravel application I'm trying to check if attendence for a particular date, subject, grade exists in my table. If so I have an if statement setup to display desire results based on what is returned.
I'm making the request with ajax but it seems like ajax keeps running the error function and I don't seem to get any error code whatsoever or internal server error(500, 404, 403, etc) In my console the status return is 200 ok
here is my script:
$(document).on('change', '#subject', function(event) {
event.preventDefault();
/* Act on the event */
var subject = $('#subject').val();
var grade = $('#grade').val();
var date = $('#date').val();
if (subject != "" && grade != "") {
$.ajax({
url:"/attendence/students",
method:"GET",
data:{"subject_id":subject, "grade_id":grade, "date":date},
dataType:"json",
success:function(data){
$("#result").html(data);
},
error:function(){
$("#result").html('There was an error please contact administrator');
}
});
}
});
Here is the controller the request is send to:
public function students(Request $request)
{
//
$grade = Grade::findOrFail($request->grade_id);
$subject = Subject::findOrFail($request->subject_id);
$students = Student::where('grade_id', $grade->id)->get(['id', 'first_name','middle_name', 'surname', 'grade_id']);
$statuses = Attendence::statuses();
// this check if attendence has been setup for the given date.
// if so prevent user for enter another date
$attendenceExists = Attendence::where([
'grade_id' => $grade->id,
'subject_id' => $subject->id,
'date' => $request->date
])->first();
if ($attendenceExists) {
return response()->json('A recorded attendence already exists for the seleced grade and subject!');
}
else {
return \View::make('attendence.partials.attendence-form')->with(array(
'students' => $students,
'subject' => $subject,
'date' => $request->date,
'statuses' => $statuses
));
}
}
Now, if this code returns true:
// this check if attendence has been setup for the given date.
// if so prevent user for enter another date
$attendenceExists = Attendence::where([
'grade_id' => $grade->id,
'subject_id' => $subject->id,
'date' => $request->date
])->first();
if ($attendenceExists) {
return response()->json('A recorded attendence already exists for the seleced grade and subject!');
}
The condition here runs and the right result is returned. But my else statement in the above does run but I don't get the right result. This is the result I get:
There was an error please contact administrator
Which shows that it is this part of the ajax request that is running:
error:function(){
$("#result").html('There was an error please contact administrator');
}
Surprisingly when I check the console this is what I see:
Which is exactly what I want but ajax is return otherwise. Am I doing something wrong?
Your dataType is set to json while you're returning html. Change it to html.
$.ajax({
url:"/attendence/students",
method:"GET",
data:{"subject_id":subject, "grade_id":grade, "date":date},
dataType:"json",
statusCode: {
200: function(data) {
$("#result").html(data.responseText);
};
}
}
});
Try this. I hope this will help you
I would say don't set the dataType at all. Just remove that setting altogether and let the jQuery ajax() method detect it automatically for you. That way, if the response type is JSON, it'll work. If the response type is HTML, it'll also work. 👍🏻
I have a static method in static class in MVC application that returns User Claims, when I access directly the url of this application,I am getting those values but when I access application url from another application using Javascript,it is not returning anything.I am not getting any error.It is returning empty result.I am also not getting CORS issue.i suspect it is something related to authentication & passing user credentials,both site is under same ADFS configuration
public static UserDetails GetUserDetails()
{
var userdetails = new UserDetails();
var objClaims = ((ClaimsIdentity)Thread.CurrentPrincipal.Identity).Claims;
foreach(var c in objClaims)
{
else if (c.Type == ConstantsHelper.emailAddress)
{
userdetails.Email = c.Value;
}
else if (c.Type == ConstantsHelper.userName)
{
userdetails.UserName = c.Value;
}
else if (c.Type == ConstantsHelper.shortName)
{
userdetails.ShortName = c.Value;
}
}
return userdetails;
}
Code to access it from another application.
function GetLoggedInUsermethod() {
var url = GetLoggedInUser;
$.ajax({
type: "GET",
url: url,
crossDomain: true,
success: function (json) {
},
error: function (e) {
}
});
}
If the calling application is hosted in different domain (different ports will qualify for different domains), then you may need to add the Access-Control-Allow-Origin header to the response with the value set to the calling application's domain for the call to succeed.
More details here.
I have been dealing with these issue for a few days, and I can't seem to be able to fix it on my own. I've already asked a question here on Stack regarding this, however I've been told this is resolved by using callback functions. I've done exactly that but the variable inside the callback still isn't changed.
I am using abide validation that is built into the Foundation framework, and I am trying to have my own custom validator for checking if an email already exists in our database. Everything works, even the console.log returns the correct results, but the variable value is not changed from false to true. Only check the code from emailVerification downwards.
Thank you for your help.
$(document).foundation({
abide : {
live_validate : false, // validate the form as you go
validate_on_blur : false,
patterns: {
positive_price: /^\+?[0-9]*\,?[1-9]+$/,
},
validators: {
positiveNumber: function(el, required, parent) {
var value = el.value.replace(/,/, '.'),
valid = (value > 0);
return valid;
},
emailVerification: function (el, required, parent) {
var email = el.value,
ajax = 1,
valid = false;
function checkServer(callback) {
$.ajax({
type: "GET",
url: "/check.do?action=userEmailAvailable",
data: "userEmail1=" + email + "&ajax=" + ajax,
success: callback
});
}
checkServer(function(data) {
if (data.result == 1) {
console.log(data.result + "does not exist");
valid = true;
} else {
console.log(data.result + "already exist");
valid = false;
}
});
return valid;
}
}
}
});
the valid that you declare in positiveNumber function is locally scoped to that function only. the next time you attempt to access it outside the function you actually create a global var called valid
As many answered, you need async validation and Abide does not support this.
I would suggest you use the excellent Parsley.js library which supports async validators through its Remote plugin
$.ajax runs asynchronously. You function returns "valid" before callback function is called. You can try running your ajax request synchronously or you need to add logic in your callback function that updates "valid" when it's called
How to create sync ajax
Add validation function to you callback
checkServer(function(data) {
if (data.result == 1) {
console.log(data.result + "does not exist");
valid = true;
} else {
console.log(data.result + "already exist");
valid = false;
}
DoCoolValidation(valid)
});
If you are sure that your server validation is fast enough you can do
function Validate(dataToSend) {
return JSON.parse($.ajax({
url: '/check.do?action=userEmailAvailable',
type: "GET",
dataType: "json",
data: dataToSend,
async: false
}).responseText);}
And use it:
valid = Validate("userEmail1=" + email + "&ajax=" + ajax);
Have a look at this post. It can help
For my current project Java/Spring project I have to validate a form. The webpage is a freemarker template file.
The <form> has no special attribute to send the data to the controller. The project uses Ajax to send the request. The controller doesn't receive the form at all.
When the user submits the data, a JavaScript function is called to receive all the data by collecting the elementID's. The data is put in a variable, like this (short version);
var userId = document.getElementById('input_id').value.toLowerCase();
var width = document.getElementById("width");
var height = document.getElementById("height");
The function then puts all the data into a JSON. This JSON is put in the Ajax, and then Ajax calls the right controller.
**Ajax code **
$.ajax({
url: url,
type: "POST",
dataType: "json", // expected format for response
contentType: "application/json", // send as JSON
Accept: "text/plain; charset=utf-8",
"Content-Type": "text/plain; charset=utf-8",
data: data,
success: function (response) {
// we have the response
if (response.status == "SUCCESS") {
console.log("succes");
//Redirect to the right page if the user has been saved successfully
if (type === "setupuser") {
window.location = "/setup/user/" + userId;
} else if (type === "simulatoruser") {
window.location = "/simulator/user/" + userId;
}
} else {
errorInfo = "";
for (i = 0; i < response.result.length; i++) {
errorInfo += "<br>" + (i + 1) + ". " + response.result[i].code;
}
$('#error').html("Please correct following errors: " + errorInfo);
$('#info').hide('slow');
$('#error').show('slow');
}
},
error: function (e) {
alert('Error: ' + e);
}
});
The following controller is called by the Ajax request:
#RequestMapping(method = RequestMethod.POST, value = "/adduser/{userType}")
#ResponseBody
JsonResponse addUserMapping(#ModelAttribute(value="user") User user, BindingResult result, #RequestBody String jsonString, #PathVariable String userType) {
def json = new JsonSlurper().parseText(jsonString)
String userId = json.userId
String userName = json.userName
user.setId(userId)
user.setName(userName)
log.warn("User id..... "+user.getId())
log.warn("User name..... "+user.getName())
JsonResponse res = new JsonResponse();
ValidationUtils.rejectIfEmpty(result, "id", "userId can not be empty.");
ValidationUtils.rejectIfEmpty(result, "name", "userName can not be empty");
if(!result.hasErrors()){
userService.addUser(jsonString)
res.setStatus("SUCCESS");
}else{
res.setStatus("FAIL");
res.setResult(result.getAllErrors());
}
return res;
}
As you can see, Ajax sends a JSON to the controller. The controller unpacks the JSON and puts the data into the user object. Then the user object is being validated using "rejectIfEmpty()" method...
Now I've been reading about making a userValidator class extending Validator, or simply putting Annotations in the bean class like:
#Size(min=1, max=3)
I prefer these annotations since you don't have to write special code for checking certain simple things (like the field not being empty .. #NotEmpty)
But that doesn't work because the controller doesn't take a user object the second it's called, instead it takes the JSON and then unpacks it (Validating is too late..)
TL:DR
Controller takes a JSON as a parameter instead of an Object. The JSON has to be unpacked and then validated in the controller as a java object using rejectIfEmpty as an example. I don't want a full page reload, but I still want to keep Ajax.
BTW: I want to validate the data against more things like regex etc. But the rejectifEmpty is a simple example.
Does anyone have an idea how to handle this?
I fixed the validation by parsing the JSON in the controller and setting it in the user object. The user object is then put in my UserValidator class and validated.
Link for more info using the validator:
http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/html/validation.html