Calling a Servlet from Ajax - javascript

I have a Java servlet, that i need to call and pass it a variable using Ajax. I have written an Ajax script, to get the variable that needs to be passed to the servlet. However i am not sure how to do so. Any help on this matter please?
This is my ajax code:
var data;
data = "NUMBER ='" + Number + "'";
var Key = '';
$.ajax({
type: "POST",
url: "Record?DB=EMP&Table=EMP_HISTORY&",
dataType: 'xml',
data: {
"Where": data
},
success: function(xml) {
$(xml).find('record').each(function() {
key = $(this).find("PK").text();
});
},
error: function(error) {
}
});

Your url parameter has & at last, I don't know if you have done it purposefully. However you may try this :
$.ajax({
url:"Record?DB=EMP&Table=EMP_HISTORY",
data:{Where:data},
contentType:"application/json; charset=utf-8",
dataType:"json",
success: function(xml) {
$(xml).find('record').each(function() {
key = $(this).find("PK").text();
});
},
error:function () {
}
});

It's unclear that which step u r in.Since that ,i would rather give u some advice.
1、if u dont use any webframework, then goto file web.xml and edit the servlet tag.configure the url and the according serlvet.Then u can overwrite the doPost() method in the servlet and receive the http request.
2、if u use webframework like struts.u can modify the configuration in struts.xml and write the according method in ur action to deal with the request.
3、if u use jsp as ur solution.u can simple do it in the jsp file. Deal with the request variables through getRequestParameter and out.print the result.
hope my advice is helpful!

Related

Ajax jquery making web api call

I made an api in java , which allows the user to get data.
there is an call : ..../api/users where i give a list back of all users avalible.
Now i got a site with a search user button, wen you press that button i want to make a call to /api/users with the help of Ajax.
i got the part that you can click on the search button, but i don't understand how to make that call with ajax
This is my code:
$.ajax({
url: ”api / resource / users ",
dataType: "json”,
}
).fail(
funcNon(jqXHR, textStatus) {
alert("APIRequestfailed: " + textStatus);
}
).done(
funcNon(data) {
alert("succes!")
}
);
Is this the way of making a good call with ajax ?
or do i have to use :
http://localhost/projectUser/api/resource/users ?
Assuming you are using JQuery to make the Ajax call then this sample code should be helpful to you. What it does is;
On search button was clicked
Do AJAX call to fetch stuff from your Java REST API
When the expected JSON object was returned, parse it and do something
O
$(document).ready(function() {
$('#demoSearchBtn').click(function () {
// Search button was clicked!
$.ajax({
type: "GET",
url: "http://localhost/projectUser/api/resource/users", // edit this URL to point into the URL of your API
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (data) {
var jsonObj = $.parseJSON(data);
// Do something with your JSON return object
},
error: function (xhr) {
alert('oops something went wrong! Error:' + JSON.stringify(xhr));
}
});
});
}
if this http://localhost/projectUser/api/resource/users is the url, it's either
$.ajax({
url: ”api/resource/users", ...
or
$.ajax({
url: ”http://localhost/projectUser/api/resource/users", ...
depending on what the browsers current URL is (relative or absoute depends on context of the browser).
but it is never ever ”api / resource / users " with spaces between words and slashes.

pass data($post) to php file using javascript without callback

I need to pass data from HTML page to PHP page But without data callback ....
i'm used two method but One of them did not succeed
1)
$.ajax({
type: "POST",
url: 'phpexample.php',
data: {voteid: x },
success: function(data)
{
alert("success! X:" + data);
}
});
2)
$.post("getClassStudent.php",
{
},
function(data){
$("#div_id.php").html(data);
}
);
as i can understand, you just want to send info to a php script and don't need the response, is that right?
try this
$.post("phpexample.php", {voteid:x});
or simply remove the "succes" function from the equation if you feel more confortable using $.ajax instead of $.post
$.ajax({
type: "POST",
url: 'phpexample.php',
data: {voteid: x }
});
your fisrt example is correct, the second is not well formed.
more info:
http://api.jquery.com/jquery.post/
EDIT: to help you some more :)
<button type="button" id="element-id">click</button>
<button type="button" class="class-name">Click</button>
$(document).ready(function(){
//if you are marking ans element by class use '.class-name'
$(".class-name").click(function(){
$.post("getClassStudent.php");
});
//if marking by id element use '#id-name'
$("#element-id").click(function(){
$.post("getClassStudent.php");
});
});
be carefful with the markings, for debuggin try to use "console.log()" or "alert()" so you can see where is the problem and where the code crushes.
var formData = {
'voteid' : 'x',
};
$.ajax({
type : 'POST',
url : 'phpexample.php',
data : formData, // our data object
dataType : 'json',
encode : true
}).done(function(data) {
console.log(data);
});

Jquery - parse XML received from URL

I have this URL, that I supposedly should receive an XML from. So far I have this:
function GetLocationList(searchString)
{
$.ajax({
url: "http://konkurrence.rejseplanen.dk/bin/rest.exe/location?input=" + searchString,
type: "GET",
dataType: "html",
success: function(data) {
//Use received data here.
alert("test");
}
});
Tried to debug with firebug, but it doesn't go into the success method.
Though, in DreamWeaver it is able to post a simple alert, which is inside the success method.
I tried writing xml as dataType, but it doesn't work (in DreamWeaver) when I write alert(data).
But it shows an alert with the entire XML, when I write html as dataType.
How do I get the XML correctly, and how do I parse and for example get the "StopLocation" element?
Try to add an Error function as well.
See enter link description here
This will give you all the informations you need to debug your code with Firefox.
$.ajax({
url: "http://konkurrence.rejseplanen.dk/bin/rest.exe/location?input=" + searchString,
type: "GET",
dataType: "html",
success: function(data) {
//Use received data here.
alert("test");
},
error: function(jqXHR, textStatus, errorThrown ){
// debug here
}
});
you need to parse it first, and then you can search for the attributes. like this.
success: function(data) {
var xml = $.parseXML(data)
$(xml).find('StopLocation').each(function()
{
var name = $(this).attr('name');
alert(name);
}
);
this will give you the name of each StopLocation.
hope this helps, you can use the same method for all other attributes in the document also.

load view using ajax symfony2

I'm very new to symfony2 and I'm getting some problems to load a view using ajax when the user clicks on a div. Using firebug I can see the data is returned but I can not append the result in the page.
My Code:
//Default Controller
public function indexAction($num, Request $request)
{
$request = $this->getRequest();
if($request->isXmlHttpRequest()){
$content = $this->forward('PaginationBundle:Default:ajax');
$res = new Response($content);
return $res;
}
return $this->render('PaginationBundle:Default:index.html.twig', array('num' => $num));
}
public function ajaxAction()
{
return $this->render('PaginationBundle:Default:page.html.twig');
}
}
My Js:
When clicking on #target, I'd like to load page.html.twig in my div
$("div#target").click(function(event){
t = t +1;
$.ajax({
type: "POST",
cache: "false",
dataType: "html",
success: function(){
$("div#box").append(data);
}
});
});
I'm using isXmlHttpRequest() in my controller to detect if it's an ajax request to load ajaxAction. I get that view on firebug but it's not appended in my div#box. div#box exists in index.html.twig
Thanks everybody in advance
In your
$("div#target").click(function(event) event you didn't specify the url parameter in ajax call, and another thing is you must specify an argument inside the 'success'
parameter of ajax call.
$("div#target").click(function(event){
t = t +1;
$.ajax({
type: "POST",
url: "{{path('yourpath-means header name in routing.yml')}}",
cache: "false",
dataType: "html",
success: function(result){
$("div#box").append(result);
}
});
});
Hope this helps...
Happy coding
This has nothing to do with symfony but with your ajax options. Pece is right though: You can use the return from §this->forward directly as it is a Response object.
The problem lies within your ajax options. You must pass the data object within your inner function or data is simply null. Try this:
success: function(data){
$("div#box").append(data);
}
I don't get your forward to treat AJAX call. Try this :
if($request->isXmlHttpRequest()){
return $this->forward('PaginationBundle:Default:ajax');
}
Controller::forward() already returns a Response object ;)

How to Parse XML Response Using jQuery

I am trying to parse an xml response using jQuery and just output an element the a page but i am unsuccessful in this.
Below is the code that I am using for the response & parsing of it.
$.ajax({
url: UCMDBServiceUrl,
type: "POST",
dataType: "xml",
data: soapMessage,
success: UCMDBData,
crossDomain: true,
contentType: "text/xml; charset=\"utf-8\""
});
alert("Sent2");
return false;
}
function UCMDBData(xmlHttpRequest, status, msg)
{
alert("Came back1");
$(xmlHttpRequest.responseXML).find('tns:CIs').each(function()
{
alert("Came back2");
$(this).find("ns0:CI").each(function()
{
alert("Came back3");
$("#output").append($(this).find("ns0:ID").text());
});
});
}
I am receiving alerts for "Came back1" but it doesnt appear to be going any further. Below is the XML Response that I am trying to parse using my above jquery code. The text that I am ultimately trying to return out of the response is in this element
<?xml version='1.0' encoding='utf-8'?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Header />
<soapenv:Body>
<tns:getFilteredCIsByTypeResponse xmlns:ns0="http://schemas.hp.com/ucmdb/1/types" xmlns:ns1="http://schemas.hp.com/ucmdb/ui/1/types" xmlns:ns2="http://schemas.hp.com/ucmdb/1/types/query" xmlns:ns3="http://schemas.hp.com/ucmdb/1/types/props" xmlns:ns4="http://schemas.hp.com/ucmdb/1/types/classmodel" xmlns:ns5="http://schemas.hp.com/ucmdb/1/types/impact" xmlns:ns6="http://schemas.hp.com/ucmdb/1/types/update" xmlns:ns7="http://schemas.hp.com/ucmdb/discovery/1/types" xmlns:ns8="http://schemas.hp.com/ucmdb/1/types/history" xmlns:tns="http://schemas.hp.com/ucmdb/1/params/query">
<tns:CIs>
<ns0:CI>
<ns0:ID>4d030502995a00afd989d3aeca2c990c</ns0:ID>
<ns0:type>nt</ns0:type>
<ns0:props>
<ns0:strProps>
<ns0:strProp>
<ns0:name>name</ns0:name>
<ns0:value>prodoo</ns0:value>
</ns0:strProp>
</ns0:strProps>
<ns0:booleanProps>
<ns0:booleanProp>
<ns0:name>host_iscomplete</ns0:name>
<ns0:value>false</ns0:value>
</ns0:booleanProp>
</ns0:booleanProps>
</ns0:props>
</ns0:CI>
</tns:CIs>
<tns:chunkInfo>
<ns0:numberOfChunks>0</ns0:numberOfChunks>
<ns0:chunksKey>
<ns0:key1 />
<ns0:key2 />
</ns0:chunksKey>
</tns:chunkInfo>
</tns:getFilteredCIsByTypeResponse>
</soapenv:Body>
</soapenv:Envelope>
So my question is that how do I properly parse the data? I believe the code syntax is correct but I am not getting the expected returned results. I would appreciate any help, thanks.
EDIT
I have modified my code to the following like the suggestion, but still no luck:
$.ajax({
url: UCMDBServiceUrl,
type: "POST",
dataType: "xml",
data: soapMessage,
success: UCMDBData,
crossDomain: true,
contentType: "text/xml;"
});
alert("Sent2");
return false;
}
function UCMDBData(data, textStatus, jqXHR) {
alert("Came back1");
$(data).find('tns:CIs').each(function () {
alert("Came back2");
$(this).find("ns0:CI").each(function () {
alert("Came back3");
$("#output").append($(this).find("ns0:ID").text());
document.AppServerForm.outputtext.value = document.AppServerForm.outputtext.value + "http://localhost:8080/ucmdb/cms/directAppletLogin.do?objectId=" + $(this).find('ns0:ID').text() +"&infopane=VISIBLE&navigation=true&cmd=ShowRelatedCIs&interfaceVersion=8.0.0&ApplicationMode=ITU&customerID=1&userName=admin&userPassword=admin";
});
});
}
When I execute the only alert message i receive back is "Came back1" which means that the code is still not going through the xml properly with jquery. Any other suggestions?
The namespace-scoped names need to be handled a little differently. According to this answer:
jQuery XML parsing with namespaces
you would need to use an attribute selector [#nodeName=tns:CIs] instead.
You may need to drop the "#" for jQuery versions later than 1.3. Another suggestion is to escape the colon: .find('tns\:CIs'), which is hacky because it conflates the syntactic prefix with the semantic namespace (the uri). So if the prefix changed this method would break. A more correct answer will recognize the mapping of prefix to namespace uri. The jquery-xmlns plugin for namespace-aware selectors looks promising in that respect.
Your jQuery success function is of the wrong form. It needs to be of the form
function UCMDBData(data, textStatus, jqXHR) {
alert("Came back1");
$(data).find('tns:CIs').each(function () {
alert("Came back2");
$(this).find("ns0:CI").each(function () {
alert("Came back3");
$("#output").append($(this).find("ns0:ID").text());
});
});
}
In addition, in your $.ajax function, change the contentType line to be contentType: "text/xml" instead of what you have before (assuming that you're sending XML to the server).
See the jQuery.ajax() documentation for more information.
Based on your comment, why do something crazy with jQuery? Just use javascript itself!
var open = '<ns0:ID>';
var close = '</ns0:ID>';
var start = obj.indexOf(open) + open.length;
var end = obj.indexOf(close);
var result = obj.slice(start, end);
Here's a jsfiddle that shows it in action.
Probably the right syntax would be
success: function(xml) {
$(xml).find('tns:CIs').each(function() {
......

Categories

Resources