I am trying to make XMLRPC connection between Server (C code) and Client (In Javascript). Client sends two numbers and server adds them and returns back.
Server(in C code) is supposed to get data in the following XML form:
<?xml version="1.0" encoding="UTF-8"?>
<methodCall>
<methodName>sample.add</methodName>
<params>
<param><value><i4>a</i4></value></param> // a and b are numbers to be added
<param><value><i4>b</i4></value></param> // a and b are numbers to be added
</params>
</methodCall>
I used mimic library for JS. So here is the client side script:
<title>Mimic - JavaScript XML-RPC Client</title>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<script src="mimic/mimic.js"language="javascript"></script>
....
<center>
<input type="text" id="n1"/>
<input type="text" id="n2"/>
<input type="button" onclick="Add_Request();" value="Request"/>
...
<script language="javascript">
function Add_Request() {
var method = "sample.add";
var request = new XmlRpcRequest("demos/calc.php", method);
request.addParam(document.getElementById("n1"));
request.addParam(document.getElementById("n2"));
var response = request.send();
alert(response.parseXML());
}
</script>
But client does not work.
Where did I make mistake or...?
In which form does Javascript send XML data to the server?
any advice would be appreciated
Thanks in advance!!!
P.S. Implementation of XMLRPC Client and Server in C code work fine.
You are not passing the correct url to the XmlRpcRequest function. You need to reference the mimic-sourceforge address. (This is assuming you are not running your own XML-RPC Server and just trying out this code)
...
<script language="javascript">
function Add_Request() {
var method = "sample.add";
var request = new XmlRpcRequest("http://mimic-xmlrpc.sourceforge.net/demos/calc.php", method);
request.addParam(document.getElementById("n1"));
request.addParam(document.getElementById("n2"));
var response = request.send();
alert(response.parseXML());
}
</script>
...
If you are running this on chrome from localhost, you will eventually get a CORS issue.
Follow this thread for help with that:
Response to preflight request doesn't pass access control check
Related
I saw this great API (http://www.dictionaryapi.com/products/api-collegiate-dictionary.htm) by merriam webster that returns an XML file with all the details in it including definitions and pronunciations.
This API requires a key so i registered and got a key for my account.
I am making the request using Javascript(XHR) but the status returned is zero.
Then i googled the error it said that it may be because my request is going from a "file:///" protocol instead of "http://", so i installed LAMP stack on my PC then hosted the file on my localhost server and even then no luck.
Another thread said that i cant make cross domain requests.
Please can you help me. Below is my HTML code from which i call function in my javascript file.
<html>
<head>
<script type="text/javascript" src="context-script.js">
</script>
</head>
<body>
<h1>Merriam Webster</h1>
<div>
<b>To:</b> <span id="to"></span><br />
<b>From:</b> <span id="from"></span><br />
<b>Message:</b> <span id="message"></span><br/>
<b>Sound:</b><span id="sound"></span><br />
</div>
<script>
callOtherDomain();
</script>
</body>
</html>
Below is my JAvascript file context-script.js code:
function callOtherDomain()
{
invocation = new XMLHttpRequest();
var url = 'http://www.dictionaryapi.com/api/v1/references/collegiate/xml/happy?key=8f394b2c-77e8-433d-b599-f3ca87660067';
//url="note.xml";
if(invocation)
{
invocation.open('GET', url, true);
invocation.withCredentials = "true";
invocation.onreadystatechange = handler;
invocation.send();
alert("ref");
}
}
function handler(evtXHR)
{
if (invocation.readyState == 4)
{
alert("erg");
if (invocation.status == 200)
{
var response = invocation.responseXML;
document.getElementById("to").innerHTML=
response.getElementsByTagName("dt")[0].childNodes[0].nodeValue;
document.getElementById("from").innerHTML=
response.getElementsByTagName("dt")[1].childNodes[0].nodeValue;
document.getElementById("message").innerHTML=
response.getElementsByTagName("dt")[2].childNodes[0].nodeValue;
}
else
alert(invocation.status);
}
else
dump("currently the application is at" + invocation.readyState);
}
But when i change the URL to "note.xml" which is locally stored on the localhost code works absolutely fine.
Thanks in advance.
While this question is several years old, I worked with dictionaryapi.com previously and the solution is two-fold:
Your first step to host on a local server was right on (localhost:8000 or http://127.0.0.1:8000). I prefer using the Python SimpleHTTPServer, started in the root directory of the page you're trying to host with whichever CLI tool you're most familiar/comfortable with, py -m http.server.
After that, just complete a jQuery call using ajax, get, or XMLHttpRequest—whichever you prefer. For example:
$.ajax({
url: 'http://www.dictionaryapi.com/api/v1/references/collegiate/xml/[YourWord]?key=[YourKeyHere],
method: "GET"
}).done(function(response){
console.log(response);
});
I am relatively new to JSON. I have read the tutorial and trying to implement it but no luck.
Basically I have an external URL that gives JSON data/feed. The data is in the form of array. Now I am trying to write a JavaScript Program (on my local) that would get the data out of this URL and would put in my html.
Here is the function. It includes the external link also.
But I am not getting any result. Just empty.
Am I missing something or what I am doing wrong?
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Index Page</title>
</head>
<body>
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://mpatrizio-001-site5.smarterasp.net/categoryList.php?D=B7ACEF70-4901-41C8-930F-D4D681D82DAA";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myArr = JSON.parse(xmlhttp.responseText);
myFunction(myArr);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
out += arr[i].CategoryID + '<br>';
}
document.getElementById("id01").innerHTML = out;
}
</script>
</body>
</html>
UPDATE:
After being pointed in the right direction by you guys (thank you very much for that), I have found that the request is being blocked by server due to some CORS error. I am studying it.
Please review the following image of the error I got in the console.
From it, can you specifically point out the solution?
Append --disable-web-security (at path C;...\chrome.exe) in chrome's exe properties preceded by a space.
More Elegant Solution:
Other solution will be on server side. Which is to create crossdomain.xml and clientaccesspolicy.xml file on server. It's structure is like:
crossdomain.xml:
<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
<allow-http-request-headers-from domain="*" headers="SOAPAction,Content-Type"/>
</cross-domain-policy>
clientaccesspolicy.xml:
<?xml version="1.0" encoding="utf-8"?>
<access-policy>
<cross-domain-access>
<policy>
<allow-from http-request-headers="SOAPAction">
<domain uri="*"/>
</allow-from>
<grant-to>
<resource path="/" include-subpaths="true"/>
</grant-to>
</policy>
</cross-domain-access>
</access-policy>
Some of the tutorials are:
http://help.adobe.com/en_US/AS2LCR/Flash_10.0/help.html?content=00000469.html
http://www.adobe.com/devnet/articles/crossdomain_policy_file_spec.html
Its specification is:
http://www.adobe.com/devnet-docs/acrobatetk/tools/AppSec/CrossDomain_PolicyFile_Specification.pdf
Other tutorials:
https://msdn.microsoft.com/en-us/library/cc197955(v=vs.95).aspx
What you are trying to do, Is a cross domain request. A cross domain request is also called a JSONP request amongst many more others and has two restrictions:
The first is that it restricts you only to "GET" requests, meaning you cannot issue a "POST" request to the cross domain server.
The second is that you are very limited by the server, meaning that if the server won't allow, you cannot get any data.
I would suggest you to read more about cross domain request before trying to go through this.
You are probably trying to execute an XMLHttpRequest to a domain that is different than your page is on, the browser will block this request. To allow the request you have to use CORS.
You can open the developer tools in Chrome (F12) and check for any error messages related to
"No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '[domainname]' is therefore not allowed access."
Thank to Muhammad Imran, Barr J and Luuk Moret, I am finally able to solve my problem.
It was the Cross domain request that's why it was not allowing me to get data.
So what I did,
I checked using test-cors.org the server to which I was sending request to see if CORS is configured or not. And the server was configured.
Then I installed this plugin for chrome, "Allow-Control-Allow-Origin: *" This plugin allows to you request any site with ajax from any source. Adds to response 'Allow-Control-Allow-Origin: *' header and Whola!. That solved my problem.
I hope this would help someone else.
I have the following Thrift client code in javascript:
<script language="javascript" type="text/javascript" src="thrift.js" />
<script language="javascript" type="text/javascript" src="QuantSvc_types.js" />
<script language="javascript" type="text/javascript" src="QuantSvc.js" />
<script language="javascript" type="text/javascript">
function calc() {
var transport = new Thrift.Transport("http://localhost:9997/QuantSvc/");
var protocol = new Thrift.Protocol(transport);
var client = new QuantSvcClient(protocol);
try {
result = client.ListAllVariables()
} catch(ouch) {
alert("An exception occurred!")
}
}
</script>
Which is triggered when I push a button on my HTML page. Then, I have the following server-side Scala code, running on localhost:9997:
object Application extends App {
val handler = new QuantSvcHandler()
val processor = new QuantSvc.Processor(handler)
val serverTransport = new TServerSocket(9997)
val server = new TThreadPoolServer(new TThreadPoolServer.Args(serverTransport).processor(processor))
}
Where the QuantSvcHandler's ListAllVariables function is (basically a skeleton function, just trying to get things to work):
override def ListAllVariables(): util.List[Attributes] =
{
var input = scala.collection.mutable.Buffer[Attributes]()
input
}
I put a breakpoint at the first line of ListAllVariables, and also a few places in the QuantSvcHandler processor. I run the server in debug in intellij IDEA, open my HTML page in Chrome, and push the button (the one that calls the javascript calc() function). The button stays stuck and I see no kind of response on the server, the breakpoints aren't being hit.
Any ideas about what I'm doing wrong?
You mix a HTTP client with a socket server.
Although HTTP uses sockets, the Thrift HTTP transport is not compatible with the Thrift Sockets transport. You need to set up the exact same protocol/transport stack on both ends. The only exception to that rule is that some server transports implicitly require an additional framed transport layer on the client side.
So the solution is to use a HTTP server. Depending on the version you use, you may also have to switch to the JSON protocol.
I'm porting a web app to Android (AppInventor AI2 created) to run in a WebViewer component.
I've got most things working but my AJAX calls to the API scripts on my webserver return null.
My guess is that the server is returning null because the origin of the request is an AJAX call from a standalone web page on my local machine (during dev) or a mobile device rather than coming from a page hosted on the same domain.
A bit of Googling around has turned up a lot of mentions of CORS...
Is this what is causing my problems?
If I call the api URL (it's a PHP script on my server that returns XML) direct from my browser I get the correct data returned.
I also have the same code running as part of the web app and that works fine.
The problem only seems to be when I am calling the HTML and JavaScript files from a local directory on my machine. (All other JavaScript function are working correctly, it's just those with AJAX calls that are getting null responses from the webserver that are causing me problems.
I have tried uploading the JS file to my webserver and calling that from the html but that didn't work either (It was a long shot as I guess the AJAX call is still actually being made from the local html file essentially).
Here is a full setup that can be used to test...
HTML file with JavaScript included:
<html>
<head>
<title>Test BBP App AJAX Error</title>
<script>
function getDataViaAJAX(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function () {
if (request.readyState == 4) {
alert("ready state of ajax changed to 4");
alert("request/data responseText=" + request.responseText);
alert("request=" + request);
// request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doTheLocalTest() {
getDataViaAJAX("./sample.xml", function (data) {
var xml = data.responseXML;
alert("Response is: '"+xml+"'")
});
}
function doTheWebTest() {
getDataViaAJAX("http://www.bluebadgeparking.com/sample.xml", function (data) {
var xml = data.responseXML;
alert("Response is: '"+xml+"'")
});
}
</script>
</head>
<body>
<input type="button" value="Click To Get XML from a local file" onClick="doTheLocalTest();">
<br />
<input type="button" value="Click To Get XML from the web" onClick="doTheWebTest();">
</body>
</html>
And a sample XML content (sample.xml):
<markers>
<marker id="1" descr="Whitefriars Street: One way street. Space on left." lat="51.5140241200000" lng="-0.1074814800000"/>
<marker id="1898" descr="Southern General Hospital, Surgical / Orthopaedic 1 Bay" lat="55.8635700800000" lng="-4.3390578030000"/>
</markers>
Save those to a local directory and try it.
When reading the XML from a local file it works, when loading the file from my webserver it fails with an empty response being returned.
(As an aside, I'm assuming I would have the same issues if I was developing a FireFox add-on that pulled data in via AJAX from my web server - something else I've been considering recently...)
I want to read the JSONP data from an external domain in raw JavaScript (no jQuery).
So let's say https://www.domain.com/abc.php?foo=bar
contains: {"error":false,"data_a":"abcabc","data_b":"123-456"}
I couldn't really find much about this on google. But if I understood it correctly it should work about like this:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script>
script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://www.domain.com/abc.php?foo=bar&callback=DataCallback";
</script>
</head>
<body>
<script>
function DataCallback(data) {
for (var key in data) {
var value = data[key];
alert(key+' = '+value);
}
}
</script>
</body>
</html>
I don't get an error, but I also don't get any alerts popping up.
Btw, I noticed that
https://www.domain.com/abc.php?foo=bar
and
https://www.domain.com/abc.php?foo=bar&callback=DataCallback
both show {"error":false,"data_a":"abcabc","data_b":"123-456"} in the browser.
Could that be the problem? Because I thought that the second link should show:
DataCallback({"error":false,"data_a":"abcabc","data_b":"123-456"})
?
You have two problems.
You are never sending the request
You have to add the script element to the document before it will be executed.
document.body.appendChild(script);
(Don't try doing that before the body exists or before you have defined your callback function)
The server is not responding with JSONP
You can't process plain JSON as if it were JSONP. The server is responding with JSON (well, when I try it, it responds with an advert for buying domains … perhaps you meant example.com?)
I have complete pure javascript jsonp example...
You can have a look if you want
https://github.com/toosha01/ajax-javascript