Javascript calling webservice error - javascript

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";

Related

How can I pass a parameter from javascript to RESTful web service using XMLHttpRequest

When i try to print the received parameter at the web service.
The parameter is empty.
If I view domain server log of glass fish server I can see the following
print:
Inside getJson()
countryKey =
So I understand the request arruved to the web service, but the parameter
that was sent from the javascript url is empty
// This is the code of the web service method
#GET
#Produces(MediaType.APPLICATION_JSON)
public String getJson(String countryKey) {
System.out.println("Inside getJson()");
System.out.println("countryKey = " + countryKey);
return "countryKey = " + countryKey;
}
// This is the javascript method
function populateDistrictList() {
var element = document.getElementById("selectCountry");
var selectedCountryKey = element.value;
var selectedCountry = element.options[element.selectedIndex].text;
var xmlHttp = new XMLHttpRequest();
var url = "http://localhost:8080/MissionWS/webresources/generic?selectedCountryKey="+selectedCountryKey;
xmlHttp.open('GET', url, true);
xmlHttp.responseType = 'json';
if (xmlHttp) {
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
alert(xmlHttp.responseText);
} else {
alert("Something is wrong !");
}
}
};
xmlHttp.send();
}
}
Please try adding the #QueryParam to your method signature as follows.
public String getJson(#QueryParam("selectedCountryKey") String countryKey)

Login using Javascript and REST

I made a REST service, which will return a String "hej" if the log in is true.
I have tested in Java with a rest client and it works fine, but pretty new to javascript and need some help.
I'm using this function
function UserAction() {
console.log(User());
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "http://localhost:8080/Footballmanagerrestservice/webresources/login");
xhttp.setRequestHeader("login", User());
xhttp.responseType = 'text';
xhttp.onreadystatechange = function () {
console.log('DONE', xhttp.readyState);
if (xhttp.readyState == 4) {;
// handle response
var response = xhttp.responseText;
console.log(response);
if (response == "hej") {
var url = "http://localhost:8080/FM3/spil2.jsp";
window.location.href = url;
}
}
};
// send the request *after* the callback is defined
xhttp.send();
return false;
}
function User() {
username = document.getElementById("username").toString();
username = document.getElementById("password").toString();
var UserAndPass = "?username=" + username + "&password=" + password;
return UserAndPass;
}
I show you the client i have i Java, maybe you can see why it's not working.
public static void main(String[] args) {
Client client = ClientBuilder.newClient();
String root="http://localhost:8080/Footballmanagerrestservice/webresources/";
String functionPath="login";
String parameters="?username=s153518&password=holger";
Response res = client.target(root+functionPath+parameters)
.request(MediaType.APPLICATION_JSON).get();
String svar = res.readEntity(String.class);
System.out.println(svar);
}
first part of the code looks ok, the following instead must be handled inside a function because is intrinsically asynchronous
var response = JSON.parse(xhttp.responseText);
console.log(response);
if (response.toString() == "hej") {
var url = "http://localhost:8080/FM3/spil2.jsp";
window.location.href = url
}
return false;
doc: https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest/onreadystatechange
essentially you're trying to handle the response as a syncrhonous call, but it's not, the response it's not immediatly avaiable, for this reason you have to register a callback (from the doc must be attached to the field onreadystatechange) that will be triggered by javascript as soon as the server response is available.
try to change it like so:
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4) {
// handle response
var response = JSON.parse(xhttp.responseText);
console.log(response);
if (response.toString() == "hej") {
var url = "http://localhost:8080/FM3/spil2.jsp";
window.location.href = url
}
}
}
xhr.send();

Unable to POST JSON object from Javascript to a Servlet via AJAX

I am trying to POST a JSON object to a servlet via AJAX. However, the object is null in the servlet. I am unable to figure out what's wrong with this code.
JAVASCRIPT
function submitValues(event, val1, val2)
{
var xmlHttpObj = new XMLHttpRequest();
if(window.XMLHttpRequest)
{
xmlHttpObj = new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
xmlHttpObj = new ActiveXObject("Microsoft.XMLHttp");
}
var jsonObject = submitTheValues(event, val1, val2);
alert("json is:" +jsonObject);
var json = JSON.stringify(jsonObject);
alert("json after stringify:" +json);
xmlHttpObj.open("POST", "../myapp/myservlet", true);
xmlHttpObj.setRequestHeader("Content-type", "application/json");
xmlHttpObj.send(json);
}
SERVLET
String jsonObj = request.getParameter("json");
If you want to receive the data as a parameter you'll have to send it as application/x-www-form-urlencode.
xmlHttpObj.open("POST", "../myapp/myservlet", true);
xmlHttpObj.setRequestHeader("Content-type", "application/x-www-form-urlencode");
xmlHttpObj.send('json='+encodeURIComponent(json));

Newbie AJAX Qn: request.send(information)

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");

How do I force or add the content length for ajax type POST requests in Firefox?

I'm trying to POST a http request using ajax, but getting a response from the apache server using modsec_audit that: "POST request must have a Content-Length header." I do not want to disable this in modsec_audit.
This occurs only in firefox, and not IE. Further, I switched to using a POST rather than a GET to keep IE from caching my results.
This is a simplified version of the code I'm using for the request, I'm not using any javascript framework.
function getMyStuff(){
var SearchString = '';
/* build search string */
...
/* now do request */
var xhr = createXMLHttpRequest();
var RequestString = 'someserverscript.cfm' + SearchString;
xhr.open("POST", RequestString, true);
xhr.onreadystatechange = function(){
processResponse(xhr);
}
xhr.send(null);
}
function processResponse(xhr){
var serverResponse = xhr.responseText;
var container = document.getElementById('myResultsContainer');
if (xhr.readyState == 4){
container.innerHTML = serverResponse;
}
}
function createXMLHttpRequest(){
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
try { return new XMLHttpRequest(); } catch(e) {}
return null;
}
How do I force or add the content length for ajax type POST requests in Firefox?
xhr.setRequestHeader("Content-Length", "0");
would be my best guess.
BTW, if you want to stop caching in IE, just add a random number onto the end, as in:
var RequestString = 'someserverscript.cfm' + SearchString + '&random=' + Math.random();
Try to actually send something instead of null (xhr.send(null);).

Categories

Resources