We are three developers working on a web-app project with Django.
Some communications client-server use an API. One particular request is not sending on one of the developer's computer. We use the same Browser (Firefox quantum 64.0 (64 bits)), same OS (Ubuntu 18.04).
Here is the JS snippet:
function requestHandler(url){
let xhttp = new XMLHttpRequest();
xhttp.open('POST', url, true);
xhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhttp.setRequestHeader('X-CSRFToken', getCookie('csrftoken'));
xhttp.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200) {
drawLogTable();
}
else if (this.readyState == 4){
console.log(this);
new PNotify({
title: 'Échec!',
text: "Opération impossible: " + this.statusText,
type: 'error'
});
}
}
xhttp.send();
}
Note that url is '../../api/log?action=accept&id=1'
On all the working computers and browsers, the request posts and does a 404 since server-side has no implementation yet. On the non-working computer, chromium works, but under Firefox, the request is not even sent (server log is empty) and the request object is completely empty (no status, no text).
We have other AJAX requests in the same type that are working fine.
Can you try this:
xhttp.onload = function(){
if (this.status == 200) {
drawLogTable();
}
I'm using some JavaScript to send an Ajax request to an Arduino webserver and change the HTML on a webpage.
In Safari this has been working great, but when I try to load it in Firefox and Google Chrome the document elements never update. In the debugger consoles I can see the requests and responses coming back so I'm guessing that there is an issue with parsing the response to an array?
Here is the code:
function GetSwitchState()
{
nocache = "&nocache=" + Math.random() * 1000000;
var request = new XMLHttpRequest();
request.onreadystatechange = function()
{
if (this.readyState == 4) {
if (this.status == 200) {
if (this.responseText != null) {
var response = this.responseText;
var comma = ",";
var inputArray = response.split(comma);
var green = inputArray[0];
var red = inputArray[1];
var fault = inputArray[2];
var counter = inputArray[3];
document.getElementById('green').innerHTML = green;
document.getElementById("red").innerHTML = red;
document.getElementById("status").innerHTML = fault;
document.getElementById("cars").innerHTML = counter;
}
}
}
}
request.open("GET", "url" + nocache, true);
request.send(null);
setTimeout('GetSwitchState()', 1000);
}
The response from the Arduino webserver is four comma-separated values.
Okay it looks like the issue was actually getting past the
{
if (this.readyState == 4) {
if (this.status == 200) {
arguments. When I changed it to:
{
if(response.readState == 4) {
I was able to move past that statement in firefox. To get the status to 200 instead of 0 I needed to modify the response header on the arduino side to include:
Access-Control-Allow-Origin: *
To allow Cross Origin Domain Requests in FireFox. Once I made these changes the code works great, I guess I was barking up the wrong tree with my array assumption.
Thanks for the help!
What I did today was pretty much the same!
When I ran an Ajax request to a PHP file and wanted to return an array I needed to specify the return-datatype as "json". In my PHP file I then returned my values like this:
return json_encode(array(
'success' => false,
'error' => $_POST['password_hashed']
));
I was acctually using jQuery to run the request. That looks like this:
$.ajax({
type: 'POST',
url: 'script.php',
data: 'password_hashed=' + hex_sha512(str_password) + '&email=' + str_email, //Clientside password hashing
cache: false,
dataType: 'json',
success: function(value){
//Ajax successfully ran
alert(value.success + '_' + value.error); //=false_[hash]
},
error: function(){
//Ajax error occured -> Display error message in specified element
alert('error with request');
}
});
I just started with Ajax two days ago, and this may not help a lot, but it is worth trying.
I wrote a cgi-script with c++ to return the query-string back to the requesting ajax object.
I also write the query-string in a file in order to see if the cgi script works correctly.
But when I ask in the html document for the response Text to be shown in a messagebox i get a blank message.
here is my code:
js:
<script type = "text/javascript">
var XMLHttp;
if(navigator.appName == "Microsoft Internet Explorer") {
XMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
} else {
XMLHttp = new XMLHttpRequest();
}
function getresponse () {
XMLHttp.open
("GET", "http://localhost/cgi-bin/AJAXTest?" + "fname=" +
document.getElementById('fname').value + "&sname=" +
document.getElementById('sname').value,true);
XMLHttp.send(null);
}
XMLHttp.onreadystatechange=function(){
if(XMLHttp.readyState == 4)
{
document.getElementById('response_area').innerHTML += XMLHttp.readyState;
var x= XMLHttp.responseText
alert(x)
}
}
</script>
First Names(s)<input onkeydown = "javascript: getresponse ()"
id="fname" name="name"> <br>
Surname<input onkeydown = "javascript: getresponse();" id="sname">
<div id = "response_area">
</div>
C++:
int main() {
QFile log("log.txt");
if(!log.open(QIODevice::WriteOnly | QIODevice::Text))
{
return 1;
}
QTextStream outLog(&log);
QString QUERY_STRING= getenv("QUERY_STRING");
//if(QUERY_STRING!=NULL)
//{
cout<<"Content-type: text/plain\n\n"
<<"The Query String is: "
<< QUERY_STRING.toStdString()<< "\n";
outLog<<"Content-type: text/plain\n\n"
<<"The Query String is: "
<<QUERY_STRING<<endl;
//}
return 0;
}
I'm happy about every advice what to do!
EDIT: the output to my logfile works just fine:
Content-type: text/plain
The Query String is: fname=hello&sname=world
I just noticed that if i open it with IE8 i get the query-string. But only on the first "keydown" after that IE does nothing.
You don't have to use javascript: in on___ handler, just onkeydown="getresponse();" is enough;
IE>=7 supports XMLHttpRequest object, so directly checking if XMLHttpRequest exists is better than checking whether navigator is IE. Example:
if(XMLHttpRequest) XMLHttp=new XMLHttpRequest();
else if(window.ActiveXObject) XMLHttp=new ActiveXObject("Microsoft.XMLHTTP");
inside your getresponse() function, try to add below code at the beginning (before open):
try{XMLHTTP.abort();}catch(e){}
Because you're using a global object, you may want to "close" it before opening another connection.
Edit:
Some browser (maybe Firefox itself?) do not handle non-"text/xml" response very well in default state, so to ensure things and stuffs, try this:
function getresponse () {
try{XMLHttp.abort();}catch(e){}
XMLHttp.open("GET", "http://localhost/cgi-bin/AJAXTest?" + "fname=" +
document.getElementById('fname').value + "&sname=" +
document.getElementById('sname').value,true);
if(XMLHttp.overrideMimeType) XMLHttp.overrideMimeType("text/plain");
XMLHttp.send(null);
}
My problem had nothing to do with the code...
I was testing my script on the local IIS7 and I opened the html-page with double-clicking on the file. But you have to open the webpage via browser (localhost/mypage.htm) because otherwise for the browser the html and the executable have different origins. which is not allowed.
When I use hardcoded JSON string, my UI comes OK
But when I use string from Web Service, no css style runs !!!
//jsonData = '{.....}';
//extractData(jsonData); //THIS CODE WORKS
var request = new XMLHttpRequest();
request.open("GET",url);
request.onload = function(){
if(request.status == 200){
jsonData = new String(request.responseText);
alert("RESPONSE : "+jsonData);
extractData(jsonData); //THIS WON'T WORK :(
}
else
alert("Connection Issue : "+request.status);
};
request.send(null);
Can anyone point out the root cause ???
I am running this code in phoneGap for Android.
What is the simplest SOAP example using Javascript?
To be as useful as possible, the answer should:
Be functional (in other words actually work)
Send at least one parameter that can be set elsewhere in the code
Process at least one result value that can be read elsewhere in the code
Work with most modern browser versions
Be as clear and as short as possible, without using an external library
This is the simplest JavaScript SOAP Client I can create.
<html>
<head>
<title>SOAP JavaScript Client Test</title>
<script type="text/javascript">
function soap() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', 'https://somesoapurl.com/', true);
// build SOAP request
var sr =
'<?xml version="1.0" encoding="utf-8"?>' +
'<soapenv:Envelope ' +
'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' +
'xmlns:api="http://127.0.0.1/Integrics/Enswitch/API" ' +
'xmlns:xsd="http://www.w3.org/2001/XMLSchema" ' +
'xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">' +
'<soapenv:Body>' +
'<api:some_api_call soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">' +
'<username xsi:type="xsd:string">login_username</username>' +
'<password xsi:type="xsd:string">password</password>' +
'</api:some_api_call>' +
'</soapenv:Body>' +
'</soapenv:Envelope>';
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
alert(xmlhttp.responseText);
// alert('done. use firebug/console to see network response');
}
}
}
// Send the POST request
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.send(sr);
// send request
// ...
}
</script>
</head>
<body>
<form name="Demo" action="" method="post">
<div>
<input type="button" value="Soap" onclick="soap();" />
</div>
</form>
</body>
</html> <!-- typo -->
There are many quirks in the way browsers handle XMLHttpRequest, this JS code will work across all browsers:
https://github.com/ilinsky/xmlhttprequest
This JS code converts XML into easy to use JavaScript objects:
http://www.terracoder.com/index.php/xml-objectifier
The JS code above can be included in the page to meet your no external library requirement.
var symbol = "MSFT";
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "http://www.webservicex.net/stockquote.asmx?op=GetQuote",true);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4) {
alert(xmlhttp.responseText);
// http://www.terracoder.com convert XML to JSON
var json = XMLObjectifier.xmlToJSON(xmlhttp.responseXML);
var result = json.Body[0].GetQuoteResponse[0].GetQuoteResult[0].Text;
// Result text is escaped XML string, convert string to XML object then convert to JSON object
json = XMLObjectifier.xmlToJSON(XMLObjectifier.textToXML(result));
alert(symbol + ' Stock Quote: $' + json.Stock[0].Last[0].Text);
}
}
xmlhttp.setRequestHeader("SOAPAction", "http://www.webserviceX.NET/GetQuote");
xmlhttp.setRequestHeader("Content-Type", "text/xml");
var xml = '<?xml version="1.0" encoding="utf-8"?>' +
'<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' +
'xmlns:xsd="http://www.w3.org/2001/XMLSchema" ' +
'xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">' +
'<soap:Body> ' +
'<GetQuote xmlns="http://www.webserviceX.NET/"> ' +
'<symbol>' + symbol + '</symbol> ' +
'</GetQuote> ' +
'</soap:Body> ' +
'</soap:Envelope>';
xmlhttp.send(xml);
// ...Include Google and Terracoder JS code here...
Two other options:
JavaScript SOAP client:
http://www.guru4.net/articoli/javascript-soap-client/en/
Generate JavaScript from a WSDL:
https://cwiki.apache.org/confluence/display/CXF20DOC/WSDL+to+Javascript
This cannot be done with straight JavaScript unless the web service is on the same domain as your page. Edit: In 2008 and in IE<10 this cannot be done with straight javascript unless the service is on the same domain as your page.
If the web service is on another domain [and you have to support IE<10] then you will have to use a proxy page on your own domain that will retrieve the results and return them to you. If you do not need old IE support then you need to add CORS support to your service. In either case, you should use something like the lib that timyates suggested because you do not want to have to parse the results yourself.
If the web service is on your own domain then don't use SOAP. There is no good reason to do so. If the web service is on your own domain then modify it so that it can return JSON and save yourself the trouble of dealing with all the hassles that come with SOAP.
Short answer is: Don't make SOAP requests from javascript. Use a web service to request data from another domain, and if you do that then parse the results on the server-side and return them in a js friendly form.
You can use the jquery.soap plugin to do the work for you.
This script uses $.ajax to send a SOAPEnvelope. It can take XML DOM, XML string or JSON as input and the response can be returned as either XML DOM, XML string or JSON too.
Example usage from the site:
$.soap({
url: 'http://my.server.com/soapservices/',
method: 'helloWorld',
data: {
name: 'Remy Blom',
msg: 'Hi!'
},
success: function (soapResponse) {
// do stuff with soapResponse
// if you want to have the response as JSON use soapResponse.toJSON();
// or soapResponse.toString() to get XML string
// or soapResponse.toXML() to get XML DOM
},
error: function (SOAPResponse) {
// show error
}
});
Has anyone tried this? https://github.com/doedje/jquery.soap
Seems very easy to implement.
Example:
$.soap({
url: 'http://my.server.com/soapservices/',
method: 'helloWorld',
data: {
name: 'Remy Blom',
msg: 'Hi!'
},
success: function (soapResponse) {
// do stuff with soapResponse
// if you want to have the response as JSON use soapResponse.toJSON();
// or soapResponse.toString() to get XML string
// or soapResponse.toXML() to get XML DOM
},
error: function (SOAPResponse) {
// show error
}
});
will result in
<soap:Envelope
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<helloWorld>
<name>Remy Blom</name>
<msg>Hi!</msg>
</helloWorld>
</soap:Body>
</soap:Envelope>
Thomas:
JSON is preferred for front end use because we have easy lookups. Therefore you have no XML to deal with. SOAP is a pain without using a library because of this. Somebody mentioned SOAPClient, which is a good library, we started with it for our project. However it had some limitations and we had to rewrite large chunks of it. It's been released as SOAPjs and supports passing complex objects to the server, and includes some sample proxy code to consume services from other domains.
<html>
<head>
<title>Calling Web Service from jQuery</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#btnCallWebService").click(function (event) {
var wsUrl = "http://abc.com/services/soap/server1.php";
var soapRequest ='<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <getQuote xmlns:impl="http://abc.com/services/soap/server1.php"> <symbol>' + $("#txtName").val() + '</symbol> </getQuote> </soap:Body></soap:Envelope>';
alert(soapRequest)
$.ajax({
type: "POST",
url: wsUrl,
contentType: "text/xml",
dataType: "xml",
data: soapRequest,
success: processSuccess,
error: processError
});
});
});
function processSuccess(data, status, req) { alert('success');
if (status == "success")
$("#response").text($(req.responseXML).find("Result").text());
alert(req.responseXML);
}
function processError(data, status, req) {
alert('err'+data.state);
//alert(req.responseText + " " + status);
}
</script>
</head>
<body>
<h3>
Calling Web Services with jQuery/AJAX
</h3>
Enter your name:
<input id="txtName" type="text" />
<input id="btnCallWebService" value="Call web service" type="button" />
<div id="response" ></div>
</body>
</html>
Hear is best JavaScript with SOAP tutorial with example.
http://www.codeproject.com/Articles/12816/JavaScript-SOAP-Client
Easily consume SOAP Web services with JavaScript -> Listing B
function fncAddTwoIntegers(a, b)
{
varoXmlHttp = new XMLHttpRequest();
oXmlHttp.open("POST",
"http://localhost/Develop.NET/Home.Develop.WebServices/SimpleService.asmx'",
false);
oXmlHttp.setRequestHeader("Content-Type", "text/xml");
oXmlHttp.setRequestHeader("SOAPAction", "http://tempuri.org/AddTwoIntegers");
oXmlHttp.send(" \
<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' \
xmlns:xsd='http://www.w3.org/2001/XMLSchema' \
xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'> \
<soap:Body> \
<AddTwoIntegers xmlns='http://tempuri.org/'> \
<IntegerOne>" + a + "</IntegerOne> \
<IntegerTwo>" + b + "</IntegerTwo> \
</AddTwoIntegers> \
</soap:Body> \
</soap:Envelope> \
");
return oXmlHttp.responseXML.selectSingleNode("//AddTwoIntegersResult").text;
}
This may not meet all your requirements but it is a start at actually answering your question. (I switched XMLHttpRequest() for ActiveXObject("MSXML2.XMLHTTP")).
Some great examples (and a ready-made JavaScript SOAP client!) here:
http://plugins.jquery.com/soap/
Check the readme, and beware the same-origin browser restriction.
The question is 'What is the simplest SOAP example using Javascript?'
This answer is of an example in the Node.js environment, rather than a browser. (Let's name the script soap-node.js) And we will use the public SOAP web service from Europe PMC as an example to get the reference list of an article.
const XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
const DOMParser = require('xmldom').DOMParser;
function parseXml(text) {
let parser = new DOMParser();
let xmlDoc = parser.parseFromString(text, "text/xml");
Array.from(xmlDoc.getElementsByTagName("reference")).forEach(function (item) {
console.log('Title: ', item.childNodes[3].childNodes[0].nodeValue);
});
}
function soapRequest(url, payload) {
let xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', url, true);
// build SOAP request
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
parseXml(xmlhttp.responseText);
}
}
}
// Send the POST request
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.send(payload);
}
soapRequest('https://www.ebi.ac.uk/europepmc/webservices/soap',
`<?xml version="1.0" encoding="UTF-8"?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Header />
<S:Body>
<ns4:getReferences xmlns:ns4="http://webservice.cdb.ebi.ac.uk/"
xmlns:ns2="http://www.scholix.org"
xmlns:ns3="https://www.europepmc.org/data">
<id>C7886</id>
<source>CTX</source>
<offSet>0</offSet>
<pageSize>25</pageSize>
<email>ukpmc-phase3-wp2b---do-not-reply#europepmc.org</email>
</ns4:getReferences>
</S:Body>
</S:Envelope>`);
Before running the code, you need to install two packages:
npm install xmlhttprequest
npm install xmldom
Now you can run the code:
node soap-node.js
And you'll see the output as below:
Title: Perspective: Sustaining the big-data ecosystem.
Title: Making proteomics data accessible and reusable: current state of proteomics databases and repositories.
Title: ProteomeXchange provides globally coordinated proteomics data submission and dissemination.
Title: Toward effective software solutions for big biology.
Title: The NIH Big Data to Knowledge (BD2K) initiative.
Title: Database resources of the National Center for Biotechnology Information.
Title: Europe PMC: a full-text literature database for the life sciences and platform for innovation.
Title: Bio-ontologies-fast and furious.
Title: BioPortal: ontologies and integrated data resources at the click of a mouse.
Title: PubMed related articles: a probabilistic topic-based model for content similarity.
Title: High-Impact Articles-Citations, Downloads, and Altmetric Score.
Simplest example would consist of:
Getting user input.
Composing XML SOAP message similar to this
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<GetInfoByZIP xmlns="http://www.webserviceX.NET">
<USZip>string</USZip>
</GetInfoByZIP>
</soap:Body>
</soap:Envelope>
POSTing message to webservice url using XHR
Parsing webservice's XML SOAP response similar to this
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<GetInfoByZIPResponse xmlns="http://www.webserviceX.NET">
<GetInfoByZIPResult>
<NewDataSet xmlns="">
<Table>
<CITY>...</CITY>
<STATE>...</STATE>
<ZIP>...</ZIP>
<AREA_CODE>...</AREA_CODE>
<TIME_ZONE>...</TIME_ZONE>
</Table>
</NewDataSet>
</GetInfoByZIPResult>
</GetInfoByZIPResponse>
</soap:Body>
</soap:Envelope>
Presenting results to user.
But it's a lot of hassle without external JavaScript libraries.
function SoapQuery(){
var namespace = "http://tempuri.org/";
var site = "http://server.com/Service.asmx";
var xmlhttp = new ActiveXObject("Msxml2.ServerXMLHTTP.6.0");
xmlhttp.setOption(2, 13056 ); /* if use standard proxy */
var args,fname = arguments.callee.caller.toString().match(/ ([^\(]+)/)[1]; /*Имя вызвавшей ф-ции*/
try { args = arguments.callee.caller.arguments.callee.toString().match(/\(([^\)]+)/)[1].split(",");
} catch (e) { args = Array();};
xmlhttp.open('POST',site,true);
var i, ret = "", q = '<?xml version="1.0" encoding="utf-8"?>'+
'<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">'+
'<soap:Body><'+fname+ ' xmlns="'+namespace+'">';
for (i=0;i<args.length;i++) q += "<" + args[i] + ">" + arguments.callee.caller.arguments[i] + "</" + args[i] + ">";
q += '</'+fname+'></soap:Body></soap:Envelope>';
// Send the POST request
xmlhttp.setRequestHeader("MessageType","CALL");
xmlhttp.setRequestHeader("SOAPAction",namespace + fname);
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
//WScript.Echo("Запрос XML:" + q);
xmlhttp.send(q);
if (xmlhttp.waitForResponse(5000)) ret = xmlhttp.responseText;
return ret;
};
function GetForm(prefix,post_vars){return SoapQuery();};
function SendOrder2(guid,order,fio,phone,mail){return SoapQuery();};
function SendOrder(guid,post_vars){return SoapQuery();};
Angularjs $http wrap base on XMLHttpRequest. As long as at the header content set following code will do.
"Content-Type": "text/xml; charset=utf-8"
For example:
function callSoap(){
var url = "http://www.webservicex.com/stockquote.asmx";
var soapXml = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://www.webserviceX.NET/\"> "+
"<soapenv:Header/> "+
"<soapenv:Body> "+
"<web:GetQuote> "+
"<web:symbol></web:symbol> "+
"</web:GetQuote> "+
"</soapenv:Body> "+
"</soapenv:Envelope> ";
return $http({
url: url,
method: "POST",
data: soapXml,
headers: {
"Content-Type": "text/xml; charset=utf-8"
}
})
.then(callSoapComplete)
.catch(function(message){
return message;
});
function callSoapComplete(data, status, headers, config) {
// Convert to JSON Ojbect from xml
// var x2js = new X2JS();
// var str2json = x2js.xml_str2json(data.data);
// return str2json;
return data.data;
}
}