How do i use the AJAX request in JSP - ajax

I have created a registration page in JSP and I wanted to validate it with AJAX. So far I have written a piece of code that creates a request object(AJAX).
validate.js
window.onload=initPage;
function initPage() {
document.getElementById("username").onblur = checkUsername;
document.getElementById("register").disabled = true;
}
function createRequest() {
try {
request = new XMLHttpRequest();
} catch (tryMS) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (otherMS) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = null;
}
}
}
return request;
}
function checkUsername() {
document.getElementById("username").className="thinking";
request=createRequest();
if(request==null)
alert("Unable To Fetch Request");
else
{
var name=document.getElementById("username").value;
var userName=escape(name);
var url="checkName.jsp?username="+userName;
request.onreadystatechange=showUserNameStatus;
request.open("GET", url, true);
request.send(null);
}
}
The problem that I'm into is the url. I don't know how to validate that username in checkName.jsp. Actually the scenario is if the userName is validated then user can register himself and if the username is already registered, then server should force the user to choose different username.
function showUserNameStatus() {
if(request.readyState==4)
{
if(request.status==200)
{
if(request.responseText=="okay")
{
document.getElementById("username").className="approved";
document.getElementById("register").disabled = false;
}
else
{
document.getElementById("username").className = "denied";
document.getElementById("username").focus();
document.getElementById("register").disabled = true;
}
}
}
}

If I understand, you have a registration page jsp , in which you are posting an AJAX call to validate the user , if the user is valid then you want to go ahead else you would like to throw back stating the user is already present ,choose a new one .
Instead of posting a call to the jsp ,what I will suggest is you can post the same to a servlet/controller/action class (whichever standard framework you are referring to) and then return back the response to the ajax call.

Related

Pass ViewModel to JSONresult in controller

My application was working but I was asked to change how message are displayed by using the JSONResponseFactory. But when I try that my ViewModel is empty going back to the JSonResult (which used to be ActionResult). I've been told I may have to serialize the form fields. Here are some present code excerpts:
cshtml:
function SubmitForm() {
$.ajaxSetup({ cache: false });
$.post('#Url.Action("StoreLevelPlanning", "StoreLevelPlanning")', { actionType: "Submit"})
.done(function (data) {
if (data.Success == true) {
CreateInformationMessage(data.Message, 'window.location.href = "#Url.Action("storemanagement", "AccountListing")";');
}
else {
CreateErrorMessage(data.Message);
}
});
}
Controller:
public JsonResult StoreLevelPlanning_Post(string actionType) // actionType is Save or Submit
{
// message to return to the view on success
string successMessage = "";
var model = new VM_StoreLevelPlanning();
TryUpdateModel(model);
try
{
if (ModelState.IsValid)
{
model.buttonPressed = actionType;
repo.UpdateCLPCategoryAndRemark(model);
//Render different message depending on ActionType
if (actionType == "Save")
{
successMessage = "Your plan was saved. You will now be directed to the Listing Screen";
}
else if (actionType == "Submit")
{
successMessage = "Your plan has been submitted. You will now be directed to the Listing Screen.";
}
else
{
//return RedirectToAction("storemanagement", "AccountListing");
// need to revisit to figure out if this can be removed
throw new Exception("Else case happened");
}
}
else
{
if (actionType == "Save")
{
// TODO : change this to throw an error so that the ErrorLog class is utilized
throw new Exception("Your plan was not saved. Please retry.");
}
else
{
// TODO : change this to throw an error so that the ErrorLog class is utilized
throw new Exception("Your plan was not submitted. Please retry.");
}
}
}
catch (Exception e)
{
return Json(JsonResponseFactory.ErrorResponse(e.Message));
}
return Json(JsonResponseFactory.SuccessResponse(successMessage));
}
I'm open to any suggestions since I'm new to MVC. The idea is to put out a successful save message and redirect the user to the Listing page. But he way I changed the code now the view model is empty. It does not use a form collection. The data is in a list in the view model.
Thank you in advance...

POST data through Ajax without using JQuery methods

I've an Ajax code, through which i want to send securely a private access_token to a url via http POST, how to achieve this using below given code??
function getstatus(url, placeid, access_token)
{
if(window.XMLHttpRequest)
{
xmlRequest = new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
try
{
xmlRequest = new ActiveXObject("Msxm12.xMLHTTP");
}
catch(e)
{
try
{
xmlRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
xmlRequest = false;
}
}
}
xmlRequest.open("GET",url,true);
xmlRequest.onreadystatechange = function()
{
if(xmlRequest.readyState==4)
{
if(placeid == "adminstatus")
adminstatus.innerHTML=xmlRequest.responseText;
if(placeid == "dbview")
{
dbview.innerHTML=xmlRequest.responseText;
}
}
}
xmlRequest.send();
}
Consider the parameter "access_token" in the function getstatus is to be http POST-ed!
Take a look at XMLHttpRequest, assuming you are attempting to send the data as key/value pairs,
xmlRequest.open("POST",url,true);//use the post method
xmlRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");//set the content type
...
xmlRequest.send("access_token="+encodeURIComponent(access_token));//send the token

AJAX - Return responseText

I've seen the myriad threads sprawled across the Internet about the following similar code in an AJAX request returning undefined:
AJAX.onreadystatechange = function() {
if(AJAX.readyState == 4) {
if(AJAX.status == 200) {
var response = AJAX.responseText;
return response;
}
else {
window.alert('Error: ' + AJAX.status);
return false;
}
}
};
I know that I'm supposed to "do something with" responseText like writing it to the HTML. The problem: I don't have that luxury. This bit of code is intended to be inside of a generic method for running fast AJAX requests that way all the code for making an AJAX request doesn't have to written out over and over again (~40×) with the chance of a minor problem here or there that breaks the application.
My method HAS to explicitly return responseText "or else." No writing to HTML. How would I do this? Also, I'd appreciate a lack of plugs for JQuery.
What I'm looking for:
function doAjax(param) {
// set up XmlHttpRequest
AJAX.onreadystatechange = function() {
if(AJAX.readyState == 4) {
if(AJAX.status == 200) {
var response = AJAX.responseText;
return response;
}
else {
window.alert('Error: ' + AJAX.status);
return false;
}
}
};
// send data
}
...
function doSpecificAjax() {
var param = array();
var result = doAjax(param);
// manipulate result
}
Doing a little research I came across this SOF post:
Ajax responseText comes back as undefined
Based on that post, it looks like you may want to implement your ajax method like this:
function doRequest(url, callback) {
var xmlhttp = ....; // create a new request here
xmlhttp.open("GET", url, true); // for async
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
if (xmlhttp.status == 200) {
// pass the response to the callback function
callback(null, xmlhttp.responseText);
} else {
// pass the error to the callback function
callback(xmlhttp.statusText);
}
}
}
xmlhttp.send(null);
}
Then, you can call that method like this...
doRequest('http://mysite.com/foo', function(err, response) { // pass an anonymous function
if (err) {
return "";
} else {
return response;
}
});
This should return the responseText accurately. Let me know if this doesn't give you back the correct results.

not able to navigate using RedirectToAction

I am notable to naviagate to another page using Redirect ie when result is false, then i would like to navigate to exception page which is not happening.
public ActionResult IsLoginExsit(CustomerDO loginData)
{
if (!string.IsNullOrEmpty(loginData.UserName) && !string.IsNullOrEmpty(loginData.Password))
{
bool result = Businesss.Factory.BusinessFactory.GetRegistrations().IsLoginExist(loginData.UserName, loginData.Password);
if (result)
{
CustomerDO custInfo = new CustomerDO();
JsonResult jsonResult = new JsonResult();
jsonResult.Data = loginData;
custInfo = Businesss.Factory.BusinessFactory.GetRegistrations().GetCustInfoByUserName(loginData.UserName);
SessionWrapper.SetInSession("CustomerID", custInfo.Id);
SessionWrapper.SetInSession("CustomerFirstName", custInfo.FirstName);
SessionWrapper.SetInSession("CustomerLastName", custInfo.LastName);
return jsonResult;
}
else
{
return RedirectToAction("UnAuthorized", "Exceptions");
}
}
return View();
}
You seem to be invoking this action using AJAX. If you want to redirect this should be done on the client side in the success callback of this AJAX call using window.location.href. So for example you could adapt your action so that in case of error it returns a JSON object containing the url to redirect to:
else
{
return Json(new { errorUrl = Url.Action("UnAuthorized", "Exceptions") });
}
and then inside your AJAX success callback:
success: function(result) {
if (result.errorUrl) {
window.location.href = result.errorUrl;
} else {
...
}
}

problem with AJAX request

i hava created the ajax XMLHttpRequest request for getting the data dyanmically ,
here is the code
var XMLHttpReq;
function createXMLHttpRequest() {
if (window.XMLHttpRequest) {
XMLHttpReq = new XMLHttpRequest();
} else {
if (window.ActiveXObject) {
try {
if(XMLHttpReq==null)
XMLHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
if(XMLHttpReq==null)
XMLHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
}
}
}
}
}
this is the method which sends the request
function personList(person) {
createXMLHttpRequest();
var url="query?option=person&userName="+person.innerHTML;
XMLHttpReq.open("GET", url, true);
XMLHttpReq.onreadystatechange =personListResponse;
XMLHttpReq.send(null);
}
function personListResponse() {
if (XMLHttpReq.readyState == 4) {
if (XMLHttpReq.status == 200) {
var xml=XMLHttpReq.responseXML;
}
}
}
the request is sent to the servlet only for the first time,when i try for the second the request is not sent ,instead am getting the previous response what i got earlier
I suppose it's cache.
Try adding this before the request:
XMLHttpReq.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
XMLHttpReq.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
XMLHttpReq.setRequestHeader("Pragma", "no-cache");
If it doesn't work, try adding an additional parameter to your url, making it unique and therefore, not caching.
var url="query?option=person&userName="+person.innerHTML + "&d=" + new Date().getTime()
I really don't like this solution, but it helps you to know if the problem is related to cache.

Resources