How to send XML request in JavaScript - javascript

I have an eye tracker (mirametrix) running as a server in localhost. In order to capture data from this I should send a xml request as given below;
SEND:<GET ID="TIME_TICK_FREQUENCY" />
I have a web-app running as the client and I need to make a request to this server through that. I wrote the following code but it doesn't seem to send the request properly to the server.
var request = $.ajax({
url: "http://127.0.0.1:4242",
type: "GET",
dataType: "xml",
data: {
data:'<GET ID="TIME_TICK_FREQUENCY" />'
},
});
Can someone please help me with this ?
Thanks in advance

$.ajax({
url: ajaxurl,
data: "<root><blah><blah></root>",
type: 'POST',
contentType: "text/xml",
dataType: "text",
success : parse,
error : function (xhr, ajaxOptions, thrownError){
console.log(xhr.status);
console.log(thrownError);
}
});
I think you need to post it.

this is not plain javascript.. looks more like jquery.. also what do you mean with 'properly'. It's kind sending it, but not really? Aside from that, I see the following problems
The url is wrong, and although your browser may handle it, your url should end with a slash.
Your xml is invalid. Needs to start with <?xml version="1.0"?>.
If you accessed this script through a different host than 127.0.0.1., or if the script is running on a different port than 4242, this will not work without CORS headers on the server.

Related

Long polling with ajax and servlets

I'm doing a project using javascript for client side and servlets for server side. I'm trying to implement a way to update client info real time. i.e when a client update some info in the web application, other clients will also see the update. I found that long polling is a good technique for this. This is the code I tried to get to work.
function poll() {
setTimeout(function() {
$.ajax({
type: "GET",
url: "server",
contentType: "application/json",
data: {
type: "update",
card: "string"
},
success: function(data) {
alert(data);
},
error: function(data) {
alert('eroor');
},
dataType: "json",
complete: poll });
}, 5000);
}
I'm trying to send a request to the server every 5 seconds and get the response with new updates. But in all the skeleton codes I saw in the web, data: is not set. Without setting it, how would the sever know the type of request it received since there are other types of requests too. But when I set data: no requests are sent from the client. But without setting data: requests are sent to the server. Is it wrong to set data: ? Without it how would I let the servlet know the type of the request?
I understand that like mentioned in here long polling is not what I'm trying to do. But can anyone explain what I should do and where I'm doing wrong.
Since you make a GET request, the data values are appended to the URL as URL parameters. Your servlet must then use request.getParameter("type") and request.getParameter("card") to extract the information from the request.
If you think that no request is sent, first check your console for errors and look at the net communications panel in the developer tools of your browser.
data:
issue is how you set the data. If you want to send json object, you have to stringify before you send it, like below.
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
contentType: "application/json",
complete: callback
});
Without it how would I let the servlet know the type of the request?
What you mean by this? to know the contentType? If so, send contentType parameter as above.
I understand that like mentioned in here long polling is not what I'm trying to do. But can anyone explain what I should do and where I'm doing wrong.
Yes. This is not exactly a long polling. This is how you send a request to the server in every 5 seconds. Anyway server should support to long polling.

Cross domain ajax causing issues to render data

I trying to capture data from an HTML form which will be placed on another website. From that form I need to capture data into my website. But when I tried jQuery Ajax call for cross domain it shows me 302 error with no response.
I've tried this
$('button[type="button"]').on('click', function(){
var data = $('.data-capture-form').serialize();
$.ajax({
type : 'POST',
url: 'http://prospectbank.co.uk/leads/test',
dataType: 'jsonp',
crossDomain : true,
data : data,
contentType: 'application/jsonp'
}).done(function(res){
var resp = $.parseJSON(res);
console.log(resp);
});
});
Where is problem with this code? Any help?
Fiddle Code
If you have access to the server, add the following header:
Access-Control-Allow-Origin: *
And then make JSONP calls
$.ajax({
type: "POST",
dataType: 'jsonp',
...... etc ....
If you do not have access to the external server, you have to direct the request to your server and then make a proxied call to the external server.

How to get a json response from yaler

I create an account with yaler, to comunicate with my arduino yun. It works fine, and i'm able to switch on and off my leds.
Then i created a web page, with a button that calls an ajax function with GET method to yaler (yaler web server accept REST style on the URL)
$.ajax({
url: "http://RELAY_DOMAIN.try.yaler.net/arduino/digital/13/1",
dataType: "json",
success: function(msg){
var jsonStr = msg;
},
error: function(err){
alert(err.responseText);
}
});
This code seem to work fine, infact the led switches off and on, but i expect a json response in success function (msg) like this:
{
"command":"digital",
"pin":13,
"value":1,
"action":"write"
}
But i get an error (error function). I also tried to alert the err.responseText, but it is undefined....
How could i solve the issue? Any suggestions???
Thanks in advance....
If the Web page containing the above Ajax request is served from a different origin, you'll have to work around the same origin policy of your Web browser.
There are two ways to do this (based on http://forum.arduino.cc/index.php?topic=304804):
CORS, i.e. adding the header Access-Control-Allow-Origin: * to the Yun Web service
JSONP, i.e. getting the Yun to serve an additional JS function if requested by the Ajax call with a query parameter ?callback=?
CORS can probably be configured in the OpenWRT part of the Yun, while JSONP could be added to the Brige.ino code (which you seem to be using).
I had the same problem. I used JSONP to solve it. JSONP is JSON with padding. Basically means you send the JSON data with a sort of wrapper.
Instead of just the data you have to send a Java Script function and this is allowed by the internet.
So instead of your response being :
{"command":"digital","pin":13,"value":0,"action":"write"}
It should be:
showResult({command:"analog",pin:13,value:0,action:"write"});
I changed the yunYaler.ino to do this.
So for the html :
var url = 'http://try.yaler.net/realy-domain/analog/13/210';
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'showResult',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
console.dir(json.action);
},
error: function(e) {
console.log(e.message);
}
});
};
function showResult(show)
{
var str = "command = "+show.command;// you can do the others the same way.
alert (str);
}
My JSON is wrapped with a showResult() so its made JSONP and its the function I called in the callback.
Hope this helps. If CORS worked for you. Could you please put up how it worked here.

Ajax request failing?

I am trying to retrieve json data from an api.
It keeps failing, but when I look in the Net tab of Firebug I can see that the GET request executed and returned the correct data. Am I doing something wrong or does anyone have tips on how to debug this?
Edit: Have changed to dataType json and error status code is 0
Thanks
$.ajax({
url: 'http://localhost:55894/api/Test/All',
data: {
format: 'json'
},
error: function () {
alert('Error');
},
dataType: 'jsonp',
success: function (data) {
alert('Ok');
},
type: 'GET'
});
From the info you provided the reason it is failing is because you dont have a cross domain access policy setup. Because you are using different ports to host the website and the API you are running into this issue. You can either setup a crossdomain.xml with the proper security settings or you can move both the API and the webserver to the same port.
Have a look at this for more info: http://en.wikipedia.org/wiki/Same-origin_policy
u can try this way:
$.ajax({
type: 'GET',
url: 'url api here',
beforeSend: function() {
},
success: function(data) {
},
error: function(xhr) { // if error occured
},
complete: function() {
},
dataType: 'json'
});
JSON and JSONP are different. If you are using JSONP, the server side must be prepared to support it. Doesn't look like you are using JSONP.
So just change dataType to 'json', as you are "trying to retrieve json data".

Sending data to server using get request header

I use jQuery to contact my REST service on server side. The URL looks like this:
http://bla.com/?userid=1,2,3,4,5,6...
The userid string could be very long and it could happen that the max url size will be exceeded.
I can't do a post request, so my question is, whether it would be a good solution to send the userid data within the header? Something like this:
$.ajax({
url: 'someurl',
headers:{'foo':'bar'},
complete: function() {
alert(this.headers.foo);
}
});
Would this be possible?
Thanks
Yes you can send header using Ajax request
$.ajax({
type: "GET",
beforeSend: function(request) {
request.setRequestHeader("Authority", authorizationToken);
},
url: "entities",
data: "json=" + escape(JSON.stringify(createRequestObject)),
processData: false,
success: function(msg) {
$("#results").append("The result =" + StringifyPretty(msg));
}
});
you can read more about header on jQuery AJAX page
Also check this example here
This is totally possible, alhough it would be advisable to just use POST, because it was meant to transfer lots of data.
Using headers is a workaround which results in the same results as POST; losing the ability to navigate forward and back without re-submitting (or re-sending headers in this case, will be impossible if the data is gone).

Categories

Resources