Why AJAX doesn't work once I add these code? - ajax

I have a page for deleting ORDER record. This page was called from AJAX, which work perfectly. However once I added some code that I made for updating inventory table at the same time. It seemed that AJAX function became malfunction and I can't figure out what is wrong with them. Please suggest me. Thanks in advance.
My AJAX function (order_edit.asp)
<script language="JavaScript">
var HttPRequest = false;
function doCallAjax(ID) { // delete order
HttPRequest = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
HttPRequest = new XMLHttpRequest();
if (HttPRequest.overrideMimeType) {
HttPRequest.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
try {
HttPRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
HttPRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!HttPRequest) {
alert('Cannot create XMLHTTP instance');
return false;
}
var url = '../engine/delorder_edit.asp';
var pmeters = "tID="+ID;
var bill_id = document.getElementById('bill_id').value; // additional for delorder_edit.asp
HttPRequest.open('POST',url,true);
HttPRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// HttPRequest.setRequestHeader("Content-length", pmeters.length);
HttPRequest.send(pmeters);
HttPRequest.onreadystatechange = function()
{
if(HttPRequest.readyState == 4) // Return Request
{
if(HttPRequest.responseText == 'Y')
{
document.getElementById("tr"+ID).style.display = 'none';
}
}
}
}
</script>
My delorder_edit.asp Page
<%
Option Explicit
Dim strID
strID = Request.Form("tID")
Dim Conn,strSQL,objExec
Set Conn = Server.Createobject("ADODB.Connection")
Conn.Open "DRIVER=Microsoft Access Driver (*.mdb);DBQ=" & Server.MapPath("../database/TKP.mdb"),"" , ""
'********** *****************************
'Open recorset in order to add od_qty back to tbl_inventory before this record was removed
'****** Once I added these code, my ajax became malfunction ******
Set rsOrder = conn.Execute("SELECT * FROM tbl_order WHERE od_id = "&strID&"" )
pd_id = rsOrder.fields.item("pd_id")
od_qty = rsOrder.fields.item("od_qty")
od_qty = DzToPcs(od_qty)
strSQL1 = "UPDATE tbl_inventory SET inv_qty_act = inv_qty_act + " & od_qty & ", inv_date = date() WHERE pd_id = '" & pd_id & "'"
Set objExec = Conn.Execute(sql1)
'*******************************************
strSQL = ""
strSQL = strSQL&"DELETE * FROM tbl_order "
strSQL = strSQL&"WHERE od_id = "&strID&" "
Set objExec = Conn.Execute(strSQL)
If Err.Number = 0 Then
Response.write("Y")
Else
Response.write("N")
End IF
Conn.Close()
Set Conn = Nothing
%>

First of all i will suggest to use the jQuery.ajax method to call the server method, so your code will be less and also more convenience to understand. And second thing, debug :
"HttPRequest.onreadystatechange = function()",
and check what value is being returned. Until unless we didn't get a exact error we can not suggest you a solution.

Related

Validate a dynamically generated CheckBox

I'm generating an asp:CheckBox dynamically and I need to validate that it is checked with a CustomValidator().
private void AddCheckBox(HtmlGenericControl newDiv, AdditionalFields field)
{
var additionalFieldDiv = new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
additionalFieldDiv.Attributes.Add("class", "additional-field-row");
var additionalLabel = new RadLabel();
additionalLabel.Text = field.Label;
additionalLabel.ID = "AdditionalLabel" + field.ControlId;
additionalLabel.CssClass += "title ";
additionalLabel.Width = new Unit(field.LabelWidth ?? 175);
if (field.Required??false) additionalLabel.CssClass += "additional-field-required";
var additionalField = new System.Web.UI.WebControls.CheckBox();
additionalField.ID = "AdditionalField" + field.ControlId;
additionalField.CssClass += "additional-field-checkbox";
additionalField.Width = new Unit(field.Width ?? 200);
var customValidator = new CustomValidator();
customValidator.ID = "CustomValidator" + field.ControlId;
//customValidator.ClientValidationFunction = "CheckBoxValidation(AdditionalField"+ field.ControlId +")";
customValidator.ControlToValidate = "AdditionalField" + field.ControlId;
customValidator.ErrorMessage = string.IsNullOrEmpty(field.ErrorMessage) ? field.Label + " required" : field.ErrorMessage;
customValidator.CssClass += "additional-fields-validator";
customValidator.Display = ValidatorDisplay.Dynamic;
customValidator.ValidationGroup = "valGroup";
customValidator.EnableClientScript = true;
newDiv.Controls.Add(additionalFieldDiv);
additionalFieldDiv.Controls.Add(additionalLabel);
additionalFieldDiv.Controls.Add(additionalField);
if (field.Required ?? false)
{
additionalFieldDiv.Controls.Add(customValidator);
}
}
I get an error if I try to use customValidator.ControlToValidate = "AdditionalField" + field.ControlId;
Control 'AdditionalField9' referenced by the ControlToValidate property of 'CustomValidator9' cannot be validated.
I have several other controls on the page that are in the validation group "valGroup" and I like the CheckBox validated client side. If I can't use the ControlToValidate property do I need to use JavaScript, and if so how do I pass the ID of the CheckBox to validate?
<script type = "text/javascript">
function ValidateCheckBox(sender, args) {
if (document.getElementById("<%=AdditionalField9.ClientID %>").checked == true) {
args.IsValid = true;
} else {
args.IsValid = false;
}
}
</script>
Hope you can help

Return ldap entries on paginated form in springboot

I have a ldap method that returns all users that are in it (almost 1300 users) and I want to return them by page, similar to what PagingAndSortingRepository does in Springboot:
If I have this endpoint ( users/?page=0&size=1 )and I wnat to return on page 0 just 1 entry.
Is there any way to do that?
Currently I have this but it doesn´t work:
SearchRequest searchRequest = new SearchRequest(ldapConfig.getBaseDn(), SearchScope.SUB,
Filter.createEqualityFilter("objectClass", "person"));
ASN1OctetString resumeCookie = null;
while (true) {
searchRequest.setControls(new SimplePagedResultsControl(pageable.getPageSize(), resumeCookie));
SearchResult searchResult = ldapConnection.search(searchRequest);
numSearches++;
totalEntriesReturned += searchResult.getEntryCount();
for (SearchResultEntry e : searchResult.getSearchEntries()) {
String[] completeDN = UaaUtils.searchCnInDn(e.getDN());
String[] username = completeDN[0].split("=");
UserEntity u = new UserEntity(username[1]);
list.add(u);
System.out.println("TESTE");
}
SimplePagedResultsControl responseControl = SimplePagedResultsControl.get(searchResult);
if (responseControl.moreResultsToReturn()) {
// The resume cookie can be included in the simple paged results
// control included in the next search to get the next page of results.
System.out.println("Antes "+resumeCookie);
resumeCookie = responseControl.getCookie();
System.out.println("Depois "+resumeCookie);
} else {
break;
}
Page<UserEntity> newPage = new PageImpl<>(list, pageable, totalEntriesReturned);
System.out.println("content " + newPage.getContent());
System.out.println("total elements " + newPage.getTotalElements());
System.out.println(totalEntriesReturned);
}
I'm unsure if this is the proper way, but here's how I went about it:
public PaginatedLookup getAll(String page, String perPage) {
PagedResultsCookie cookie = null;
List<LdapUser> results;
try {
if ( page != null ) {
cookie = new PagedResultsCookie(Hex.decode(page));
} // end if
Integer pageSize = perPage != null ? Integer.parseInt(perPage) : PROCESSOR_PAGE_SIZE;
PagedResultsDirContextProcessor processor = new PagedResultsDirContextProcessor(pageSize, cookie);
LdapName base = LdapUtils.emptyLdapName();
SearchControls sc = new SearchControls();
sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
sc.setTimeLimit(THREE_SECONDS);
sc.setCountLimit(pageSize);
sc.setReturningAttributes(new String[]{"cn", "title"});
results = ldapTemplate.search(base, filter.encode(), sc, new PersonAttributesMapper(), processor);
cookie = processor.getCookie();
} catch ( Exception e ) {
log.error(e.getMessage());
return null;
} // end try-catch
String nextPage = null;
if ( cookie != null && cookie.getCookie() != null ) {
nextPage = new String(Hex.encode(cookie.getCookie()));
} // end if
return new PaginatedLookup(nextPage, results);
}
The main issue I kept on hitting was trying to get the cookie as something that could be sent to the client, which is where my Hex.decode and Hex.encode came in handy.
PersonAttributesMapper is a private mapper that I have to make the fields more human readable, and PaginatedLookup is a custom class I use for API responses.

Image Upload doesn't work in Server. Works fine in localhost

So, this code works just fine in localhost. It deletes the previous image and uploads the new one. It does nothing on server however. Any clue?
I have used AJAX for asynchorous call By the way if that makes a difference.
var db=Database.Open("StarterSite");
var contentQuery="Select * from Contents where id =#0";
var content=db.QuerySingle(contentQuery,"1");
var message="";
var imgCount=0;
var alreadyExist=false;
try{
if (IsPost && Request.Files.Count > 0) {
bool deleteSuccess = false;
var fileName = "";
var photoName = "";
var fileSavePath = "";
var uploadedFile = Request.Files[0];
var toDelete=Request["toDelete"];
var toUpload=Request["toUpload"];
if(uploadedFile.ContentLength>0){
#******************DELETE***************#
var fullPath = Server.MapPath("~/img/" + toDelete);
if (File.Exists(fullPath))
{
File.Delete(fullPath);
deleteSuccess = true;
}
#****************UPLOAD*******************#
fileName = Path.GetFileName(uploadedFile.FileName);
fileSavePath = Server.MapPath("~/img/" +
fileName);
uploadedFile.SaveAs(fileSavePath);
var updateQuery="Update Contents Set "+toUpload +"=#0";
db.Execute(updateQuery, fileName);
//Response.Redirect("editMode.cshtml");
}
}
}
catch(HttpException ex){
message="Image size you selected was too large. Please select a different Image.";
}
Try changing the permission of the folder to 777.

Exporting to excel when there are special characters in the data ( French descriptions)

I am exporting data to excel file using Excel query table. There will be a text file with the data containing many rows, each cell is separated by | character. I am dumping the data to excel file using the following code
try
{
//Start Excel and get Application object.
oXL = new Excel.Application();
oXL.Visible = false;
oXL.UserControl = false;
//Get a new workbook.
oWBook = (Excel._Workbook)(oXL.Workbooks.Open(strFilename, 0, false, 5, "", "", true, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false));
oSheet = (Excel._Worksheet)oWBook.ActiveSheet;
oSheet.Activate();
//Create header row 2
oXL.ReferenceStyle = Microsoft.Office.Interop.Excel.XlReferenceStyle.xlR1C1;
Excel.Range oRange2 = oSheet.get_Range("A2", "A2");
oRange2.FormulaR1C1 = HeaderLine1;
//Create header row 2
oRange2 = oSheet.get_Range("A3", "A3");
oRange2.FormulaR1C1 = HeaderLine2;
oRange2 = oSheet.get_Range("A" + StartRowNumber.ToString().Trim(), Missing.Value);
var temp = oSheet.QueryTables.Add("TEXT;" + TextFileName, oRange2, Missing.Value);
temp.Name = TextFileName.ToUpper().Replace(".TXT", "");
temp.PreserveFormatting = true;
temp.AdjustColumnWidth = false;
temp.TextFileStartRow = 1;
temp.TextFileParseType = Microsoft.Office.Interop.Excel.XlTextParsingType.xlDelimited;
temp.TextFileTextQualifier = Microsoft.Office.Interop.Excel.XlTextQualifier.xlTextQualifierDoubleQuote;
temp.TextFileConsecutiveDelimiter = false;
temp.TextFileTabDelimiter = true;
temp.TextFileSemicolonDelimiter = false;
temp.TextFileCommaDelimiter = false;
temp.TextFileSpaceDelimiter = false;
temp.TextFileOtherDelimiter = "|";
temp.TextFilePlatform = 1252;//65001;//1252;//65001;//1200;
//http://en.wikipedia.org/wiki/Code_page
temp.TextFileColumnDataTypes = GetDataType(ColumnDataType);
temp.TextFileTrailingMinusNumbers = true;
temp.Refresh(false);
//temp.Connection.ToString();
temp.Delete();
oXL.ReferenceStyle = Microsoft.Office.Interop.Excel.XlReferenceStyle.xlA1;
oWBook.Save();
oWBook.Close(false, Missing.Value, Missing.Value);
}
catch (Exception ex)
{
oWBook.Close(false, Missing.Value, Missing.Value);
}
finally
{
oXL.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(oSheet);
oSheet = null;
System.Runtime.InteropServices.Marshal.ReleaseComObject(oWBook);
oWBook = null;
System.Runtime.InteropServices.Marshal.ReleaseComObject(oXL);
oXL = null;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
}
When the text file contains some special characters( Ex French words) it will not display as they are when the excel file is opened after generating....
Can anyone help to solve this problem ?
Thanks
Suresh

how to send multiple variables from servlet as response to ajax post?

I am developing a testing system with jsp and java
At client side i have the following code:
var xmlhttp = new getXmlHttpRequestObject(); //xmlhttp holds the ajax object
function servletPost() {
if(xmlhttp) {
//var txtname = document.getElementById("testForm");
var form = $('#testForm');
xmlhttp.open("POST","servlet/TestingController",true);
xmlhttp.onreadystatechange = handleServletPost;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(form.serialize());
}
}
function handleServletPost() {
//var qComplexity = document.getElementsByName("qComplexity")[0].value;
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
var respText = xmlhttp.responseText;
document.getElementById("fullQuestion").innerHTML = respText;
// here i also should change the content of the answer options
// so i should get from servlet multiple variables
// which allows me to change div contents in my jsp like as respText.question or respText.answer[0]
} else {
alert("Ajax calling error");
}
}
}
At server side: (my Servlet)
public void doPost (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
.........................................................
.........................................................
PrintWriter out = res.getWriter();
String complex = null;
int categ_id = -1;
String asked_by = null;
String Qtext = null;
int qid = -1;
q_numb = 1;
q_numb++;
String sqlSelect = "SELECT * FROM questions WHERE complexity = '" + complexity
+ "'ORDER BY RANDOM() LIMIT 1;";
ResultSet r = myConnection.runQuery( sqlSelect );
session.setAttribute("member", tempMem);
while (r.next()) {
complex = r.getString(5);
categ_id = r.getInt(4);
asked_by = r.getString(3);
Qtext = r.getString(2);
qid = r.getInt(1);
String sqlA = "select * from answers where question_id = '" + qid
+ "' ORDER by RANDOM();";
ResultSet result = myConnection.runQuery( sqlA );
session.setAttribute("member", tempMem); }
So i need to send values of complex, Qtext, qid, categ_id and so on.
Is there any structures to send like from ajax to servlet, but visa versa?
And how to handle sent data in client side?
Thanks in advance!!!!
Use JSON. There are a myriad of free Java JSON marshallers. And JSON is natively supported by JavaScript.

Resources