Newbie AJAX Qn: request.send(information) - javascript

I am completely new to AJAX hence this question. I want to send some information from my javascript code to my servlet.
function getDetails() {
vals = document.getElementById("name").value;//works: vals does get inputted value
request = createRequest();
if (request == null) {
alert("Unable to create request");
return;
}
var url= "ValidateUser.do";
request.open("POST", url, true);
request.onreadystatechange = displayDetails;
//How do I send the value of "vals" to my servlet?
request.send("name="+vals);
}
When I run req.getParameter("name") on my servlet, I always get no value even though "vals" does contain the inputted value. So my question is- how do I access this value from my servlet?
EDIT:
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;
}
FURTHER EDIT:
Servlet code: I want the println statement to print out the name.
//shortened: this method is called by a ControllerServlet
public Object perform(HttpServletRequest req, HttpServletResponse resp) {
//retrieve customer from database
model = SeekerCustomer.getCustomer(req.getParameter("name"));
System.out.println(req.getParameter("name"));
}

function ajaxRequest(){
var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"] //activeX versions to check for in IE
if (window.ActiveXObject){ //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)
for (var i=0; i<activexmodes.length; i++){
try{
return new ActiveXObject(activexmodes[i])
}
catch(e){
//suppress error
}
}
}
else if (window.XMLHttpRequest) // if Mozilla, Safari etc
return new XMLHttpRequest()
else
return false
}
function postReq(){
var mypostrequest=new ajaxRequest()
mypostrequest.onreadystatechange=function(){
if (mypostrequest.readyState==4){
if (mypostrequest.status==200 || window.location.href.indexOf("http")==-1){
document.getElementById("my_Result_tag").innerHTML=mypostrequest.responseText //this is where the results will be put!
}
else{
alert("An error has occured making the request")
}
}
}
var vals = document.getElementById("name").value
var parameters="name="+vals
mypostrequest.open("POST", "ValidateUser.do", true)
mypostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
mypostrequest.send(parameters)
}
In the servlet access vals using:
request.getParameter("name");

Related

Ajax, why the setInterval function doesn't work?

I just have a json page in localhost and I save the data of this page in a file , I need to save this page every 5 seconds, so I developed this code in ajax , using a page in php with an exec command,I used a setinterval function for the update but my code execute the function getRequest only one time.
Here the html:
<script type="text/javascript">
// handles the click event for link 1, sends the query
function getOutput() {
setInterval(function(){
getRequest(
'prova1.php', // URL for the PHP file
drawOutput, // handle successful request
drawError // handle error
);
return false;
},3000);
}
// handles drawing an error message
function drawError() {
var container = document.getElementById('output');
container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
var container = document.getElementById('output');
container.innerHTML = responseText;
}
// helper function for cross-browser request object
function getRequest(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req.readyState == 4) {
return req.status === 200 ?
success(req.responseText) : error(req.status);
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
</script>
And here the php page:
<?php
exec(" wget http://127.0.0.1:8082/Canvases/Fe0_Cbc1_Calibration/root.json -O provami3.json", $output);
echo 'ok';
?>
I'm new to php , javascript ajax etc and I-m learning it a piece at time, I know that maybe there is an easy way for it using jQuery but for now I'm learning Ajax, so I'd like have an advice for doing it with Ajax.
Thank you all.
Do you have called getOutput() function?I don't see it...
Working example with your code here: http://jsfiddle.net/v9xf1jsw/2/
I've only added this at the end:
getOutput();
Edit:
Working example with getOutput call into a link: http://jsfiddle.net/v9xf1jsw/8/
The JS is fine, see example here counting the loops https://jsfiddle.net/tk9kfdna/1/
<div id="output"></div>
<div id="log"></div>
<script type="text/javascript">
// handles the click event for link 1, sends the query
var times=0;
function getOutput() {
setInterval(function(){
getRequest(
'prova1.php', // URL for the PHP file
drawOutput, // handle successful request
drawError // handle error
);
return false;
},3000);
}
// handles drawing an error message
function drawError() {
var container = document.getElementById('output');
container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
var container = document.getElementById('output');
container.innerHTML = responseText;
}
function getRequest(url, success, error) {
times++;
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req.readyState == 4) {
return req.status === 200 ?
success(req.responseText) : error(req.status);
}
}
req.open("GET", url, true);
req.send(null);
var log = document.getElementById('log');
log.innerHTML = 'Loop:'+times;
return req;
}
getOutput();
</script>
Assuming here your calling getOutput() somewhere as that was not included in your original question if not it may just be that. Otherwise what may be happening is a response from prova1.php is never being received and so the script appears like it's not working. The default timeout for XMLHttpRequest request is 0 meaning it will run forever unless you specify the timeout.
Try setting a shorter timeout by adding
req.timeout = 2000; // two seconds
Likely there is an issue with prova1.php? does prova1.php run ok when your try it standalone.
1) Return false at the end of the setInterval method, I don't believe this is necessary.
2) Use a global variable to store the setInterval, (this will also give you the option to cancel the setInterval).
var myInterval;
function getOutput() {
myInterval = setInterval(function(){
getRequest(
'prova1.php', // URL for the PHP file
drawOutput, // handle successful request
drawError // handle error
);
},3000);
}

Getting response From Ajax call

When trying to get the responseText from an ajax call built in plain vanilla javascript, Firebug seems to see the request but one cannot get a reference to the responseText.
This is the code for function
function getAjaxResponse(){
var ajaxObj = getAjaxObj();
ajaxObj.open('get', 'responsePage.php', true);
ajaxObj.onReadyStateChanged = function(){
if(ajaxObj.readyState == 4
&& ajaxObj.status == 200){
//no functions are getting fired in here
//this does not get logged to console
console.log(ajaxObj.responseText);
//neither does this
console.log(2);
}
};
ajaxObj.send(null);
//this does gets logged to console
console.log(1);
}
function for the ajax object
function getAjaxObj(){
var req;
if(window.XMLHttpRequest){
try{
req = new XMLHttpRequest();
} catch(e){
req = false;
} finally {
return req;
}
} else {
if(window.ActiveXObject){
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e){
try{
req = new ActiveXObject("Msxml.XMLHTTP");
} catch(e){
req = false;
} finally {
return req;
}
}
}
}
}
Also here is the view from firebug
How to get a reference to the response from the ajax call?
OnReadyStateChanged needs to be onreadystatechange. JavaScript is case-sensitive.
ajaxObj.onReadyStateChanged: onreadystatechange should all be lower case (and without the trailing 'd')

Javascript calling webservice error

I'm trying to call a simple web service and send an email address as a parameter, and i'm getting this error saying "Request format is unrecognized for URL unexpectedly ending in '/IsPreUsedEmail'".
Any Idea?
Thanks.
Client side:
function GetIsPreUsedEmail(sEmail)
{
var Url = "http://localhost:52476/MyShul/Services/GetData.asmx/IsPreUsedEmail";
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", Url, false);
xmlHttp.send('jbjkb#kjbk');
var xmldoc;
xmldoc = new ActiveXObject("Msxml2.DOMDocument.3.0");
xmldoc.loadXML(xmlHttp.responseXML.xml);
if (xmldoc.parseError.errorCode != 0) {
alert("DOM Not Loaded")
}
return xmlHttp.responseXML.xml;
}
Server side:
[WebMethod]
public bool IsPreUsedEmail(string sEmail)
{
return true;
}
change the url to,
var Url = "http://localhost:52476/MyShul/Services/GetData.asmx/IsPreUsedEmail?sEmail=example#example.com";

How do i link a xml file with several nodes and subnodes?

am looking for a javascript that will load an xml file and will display something like rectangules with links based on the xml child nodes, parents linked to childs and subnodes linked to nodes. how would i be able to do this?
You can accomplish this with AJAX.
First, create a function that will pull information from your XML file:
function loadXMLdoc(url) {
var ajaxRequest;
try {
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch(e) {
// Internet Explorer Browsers
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function() {
if (ajaxRequest.readyState === 4) {
if (ajaxRequest.status === 200) {
// a hidden div to display the result
var result = document.getElementById('result');
result.style.display = 'block';
result.innerHTML = ajaxRequest.responseText;
} else {
result.innerHTML = 'An error has occurred making the request';
}
}
ajaxRequest.open("GET", url, true);
ajaxRequest.send();
};
}
From here, you can start grabbing data from your XML file. Inside your if (ajaxRequest.status === 200) { } statement, you can start calling elements:
var elem = ajaxRequest.responseXML.getElementById('elem');
var parents = elem.parentNodes;
var children = parents.childNodes;
It's up to you exactly how you'd like to format this and what data you're grabbing, but this should be a good starting point for you.

Ajax response works after two clicks?

I just wrote a basic user-login system where the html page uses javascript to send the ajax request to a servlet which accesses through database.
Here's the js code
var res;
function getXMLObject()
{
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP") // For Old Microsoft Browsers
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") // For Microsoft IE 6.0+
}
catch (e2) {
xmlHttp = false // No Browser accepts the XMLHTTP Object then false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest(); //For Mozilla, Opera Browsers
}
return xmlHttp; // Mandatory Statement returning the ajax object created
}
var xmlhttp = new getXMLObject(); //xmlhttp holds the ajax object
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
res=xmlhttp.responseText;
}
else {
return false;
alert("Error during AJAX call. Please try again");
}
}
function ajaxFunction() {
var veid=document.getElementById("eid").value;
var vpwd=document.getElementById("pwd").value;
//window.alert('here inside ajaxFunction'+vconf+' '+vseid);
if(xmlhttp) {
xmlhttp.open("GET","check_login?eid="+ veid +"&pwd="+ vpwd,true); //this is the servlet name
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(null);
}
}
function def()
{
//window.alert('hi');
ajaxFunction();
//alert('res:'+res);
if(res=='y')
{
return true;
}
else
{
document.getElementById("uhidden").style.color="#CC0000";
document.getElementById("uhidden").innerHTML="Invalid E-Mail ID or Password"
return false;
}
}
But the code works only after two clicks :(
Any help guys?
Your def function calls ajaxFunction and then straight away checks the res variable. However ajaxFunction just sends the AJAX request; it does not wait for the AJAX response to arrive. Your code is checking the res variable before it is being set from the AJAX response.
This is why it works on the second click - not because the res variable is being set by the second click's AJAX response, but because it is still set from the first click's AJAX response.
The solution is to re-arrange your code a bit. Move the code to display the invalid login message to where the AJAX response is received. In other words, replace the res=xmlhttp.responseText; line with some code to check if xmlhttp.responseText is not y and display the invalid login message.
I guess you call def()
Your Request ist asynchron(because you set the 3rd argument of open() to true ), but in def() you immediately after sending the request work with the the result:
ajaxFunction();
//alert('res:'+res);
if(res=='y')
At this time the request usually is not finished, the result not available yet
Put all code that has to work with the server-response into handleServerResponse()

Categories

Resources