Cant retrieve an XML list from a web service - javascript

I have a server running OTRS 5 and I would like to retrieve a list in XML format. I'm running a JavaScript code that should display the list, but instead I get an error.
My local server is https://labcentos3/otrs/mds.pl?Action=ServiceList.
I think its a Perl script that runs on the server side and then displays a list in XML format.
This is what I get if I browse the local link: it gives me the list I want
I wrote HTML and JavaScript to try to do the same for working with the retrieved data later, but I can't get past an error.
HTML
<html>
<head>
<title>XML read</title>
<script src="reader.js" type="text/javascript"></script>
</head>
<body>
<h1>XML File</h1><br/>
</body>
</html>
reader.js
var user = "bla bla bla";
var pass = "bla bla bla"
var getXMLFile = function(path, callback) {
var request = new XMLHttpRequest();
request.open("POST", path);
request.setRequestHeader("Content-Type", "text/plain");
//request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.setRequestHeader('Authorization', 'Basic ' + btoa(user + ":" + pass));
request.onreadystatechange = function() {
if(request.readyState === 4 && request.status === 200) {
callback(request.responseXML);
}
};
request.send();
};
getXMLFile("https://labcentos3/otrs/mds.pl?Action=ServiceList", function(xml) {
console.log(xml);
});
The error I get in the Chrome console is this:
XMLHttpRequest cannot load https://labcentos3/otrs/mds.pl?Action=ServiceList. The request was redirected to 'https://labcentos3/otrs/index.pl', which is disallowed for cross-origin requests that require preflight.

Related

Javascript output sent to PHP for adding into database

I have wrote a HTML/Javascript code generator but instead of outputting the code to a HTML site i would like the code to be send to php to be added to a database but i cant work out how to get the out put of the javascript into PHP
there is also another javascript doc to go with this if you need it to make it work ..
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script src="../voucher_codes.js"></script>
</head>
<body>
<h1>pattern codes</h1>
<ul id="pattern-codes"></ul>
<script>
var patternCodes = voucher_codes.generate({
prefix: "BREAK-",
postfix: "-2019",
length:5,
count: 5,
charset: "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
});
function fillList(listId, items) {
var list = document.getElementById(listId);
items.forEach(function(item) {
list.innerHTML += "<li>" + item + "</li>";
});
}
fillList("pattern-codes", patternCodes);
</script>
</body>
</html>
i am wanting the output of the function "fillList" to send the output to PHP if this is possible....
You would have to look into using AJAX or the Axios library to send requests to a server page such as PHP.
Here is a simple AJAX POST server request in Javascript:
`
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = this.responseText;
}
};
xhttp.open("POST", "request_page.php", true); // set method and page
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); // set content type that we are sending POST data
xhttp.send("key=VALUE&key=VALUE"); // POST values
}
</script>
`
On the PHP page if you want to give a response of data to use back in Javascript, make sure to
json_encode($array_values)
the data array before echoing it out and set the headers to
header("Content-Type: application/json")
so you can grab the response data in Javascript and it can be turned into a Javascript {Object} or [Array]

multipart HTTP request with microsoft graph javascript sdk

I'm trying to use the Microsoft Graph JavaScript SDK to create a page in OneNote with images, which OneNote requires a multipart request for. I've created a FormData object with all the data I'm trying to send.
The request goes through when I send it up myself as follows:
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader("Authorization", "Bearer" + token);
xhr.onreadystatechange = function() {
//Call a function when the state changes
if (xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
// Request finished. Do processing here.
} else {
// handle case
}
};
// dataToSend = FormData object containing data
// (as Blobs), including the page HTML in a
// "Presentation" part as specified
xhr.send(dataToSend);
However, since I'm using the Graph SDK to make all my other requests, I'm wondering if there's a way to do the multipart request with the SDK as well. So far, this is what I've tried:
this.client
.api(pagesURL)
.version("beta")
.header("Content-Type", "text/html")
.post(dataToSend);
Investigating the request in Fiddler shows that the request body contains [object, Object], not the data formatted as a multipart request. Any help on how to get the FormData object into the request properly using the SDK/ guidance on whether this is possible would be greatly appreciated!
I believe this is what you're looking for:
this.client
.api("https://graph.microsoft.com/beta/me/notes/sections/{Section ID}/pages")
.header("Content-Type", "application/xhtml+xml")
.header("boundary", "MyPartBoundary")
.post(dataToSend);
This snippet was adapted from the multi-part unit test used by the SDK itself. You can find that test at https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/spec/types/OneNote.ts
Update the microsoft-graph-client to latest version and try something like this.
const HTMLPageContent =
`<!DOCTYPE html>
<html>
<head>
<title>A page with rendered images</title>
</head>
<body>
<p>Here is an image uploaded as <b>binary data</b>:</p>
<img src="name:imageBlock1" alt="an image on the page" />
</body>
</html>`;
let sectionId = "<Your_OneNote_Page_Section_Id>";
let formData = new FormData();
let htmlBlob = new Blob([HTMLPageContent], {
type: "text/html"
});
formData.append("Presentation", htmlBlob);
formData.append("imageBlock1", file);
client
.api(`/me/onenote/sections/${sectionId}/pages`)
.post(formData)
.then((json) => {
console.log(json);
return Promise.resolve();
});

how to grab JSON Data from url using JavaScript? (new to JSON)

<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript - read JSON from URL</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
<body>
<script>
function setup() {
loadJSON("https://www.westelm.com/services/catalog/v4/category/shop/new/all-new/index.json", gotData, 'jsonp');
}
function gotData(data){
alert(data);
}
</script>
</body>
</html>
I am new to the developer role, please help. First it kept giving me Access denial to the url ERROR!. Then i learned about jsonp and added it. Now i don't see anything showing up, when i should be getting the json data. !JSON data from the url is correct ran it in JSONLINT!
var xmlhttp = new XMLHttpRequest();
var url = "https://www.westelm.com/services/catalog/v4/category/shop/new/all-new/index.json";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
console.log(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
That code will normally work, but for this you should be getting this error:
Failed to load
https://www.westelm.com/services/catalog/v4/category/shop/new/all-
new/index.json: No 'Access-Control-Allow-Origin' header is present on
the requested resource. Origin 'null' is therefore not allowed access.
The response had HTTP status code 403.
That's because this server doesn't allow JSON Reqs, and will not allow you access. You could try using CORS (https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) but I'm not sure how much that will help you

SoundCloud API gives "Uncaught SyntaxError: Unexpected token : " error

In the console it's giving me the error "Uncaught SyntaxError: Unexpected token : ", but if I access direct SoundCloud URL in my browser then it's giving valid JSON. Earlier this code was working fine and today this issue started.
<html>
<head>
<script src="https://api.soundcloud.com/resolve.json?url=https://api.soundcloud.com/tracks/251912676/?secret_token=s-EkyTy&client_id=08f79801a998c381762ec5b15e4914d5"></script>
</head>
<body>
<h2>hellooo</h2>
</body>
</html>
Update:
Below is the actual code for which I am asking the question, above html I just created for example.
SoundCloud.prototype._jsonp = function (url, callback) {
var target = document.getElementsByTagName('script')[0] || document.head;
var script = document.createElement('script');
var id = 'jsonp_callback_' + Math.round(100000 * Math.random());
window[id] = function (data) {
if (script.parentNode) {
script.parentNode.removeChild(script);
}
window[id] = function () {};
callback(data);
};
script.src = url + (url.indexOf('?') >= 0 ? '&' : '?') + 'callback=' + id;
target.parentNode.insertBefore(script, target);
};
I got the reason of issue, earlier soundcloud were responding response in jsonp but now they are providing JSON even I passed JsonP callback function. I had to make ajax request to fix it.
I used following code to fix it.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
callback( JSON.parse(this.responseText) );
}
};
xhttp.open("GET", url, true);
xhttp.send();
The following script tag expects JavaScript code in the source and not JSON.
<script src="file.js"></script>
I suppose that you want to use this externally produced json...
A way to "get" it is using an asynchronous ajax request like $.get(url,callback);
Calling it as a script will sure fail...
Because it's not a script.
Try to run the snippet!
var url = "https://api.soundcloud.com/resolve.json?url=https://api.soundcloud.com/tracks/251912676/?secret_token=s-EkyTy&client_id=08f79801a998c381762ec5b15e4914d5"
var json;
$.get(url,function(result){
json = result;
// show in console
console.log(JSON.stringify(json));
// Now using it...
$("#json_usage").html(json.tag_list+" and all the "+json.permalink);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<!--script src="https://api.soundcloud.com/resolve.json?url=https://api.soundcloud.com/tracks/251912676/?secret_token=s-EkyTy&client_id=08f79801a998c381762ec5b15e4914d5"></script-->
</head>
<body>
<h2>hellooo <span id="json_usage"></span> !</h2>
</body>
</html>
In the above, the resulting json is placed in the json variable and then console logged.
Sorry you've been having trouble with JSONP responses from the SoundCloud API. This was due to a bug that made it into production in the last few days. We've just deployed a fix, and so this endpoint will now be returning valid JSONP responses rather than just JSON, if you specify a callback parameter. Sorry for the confusion!

Ajax data parameter to php file on external domain

In this file called like this :
/fichier_clients/fiche_client.html?id=4870
It used "id" value and make a request to external file (php).
Data doesn't pass to php file (external domain).
Distant php file execute fine with no error and resend extract.
Data from database with test id,
but not with value received via ajax -> params: {"term": id},
<link href="jquery-mobile/jquery.mobile.theme-1.0.min.css" rel="stylesheet" type="text/css"/>
<link href="jquery-mobile/jquery.mobile.structure-1.0.min.css" rel="stylesheet" type="text/css"/>
<script src="jquery-mobile/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="jquery-mobile/jquery.mobile-1.0.min.js" type="text/javascript"></script>
<script type='text/javascript' language='javascript'>
function fiche0()
{
var id = location.search;
var id = id.split('=');
var id = id[1];
alert (id);
var encoded = encodeURIComponent('http://www.mydomain.fr/connexion.php');
$.ajax({
url: 'http://whateverorigin.org/get?url='+encoded,
type:'POST',
contentType:"application/json",
dataType: 'jsonp',
crossDomain:true,
params: {"term": id},
timeout: 4000
}).done(function(reponse){
a=reponse.contents.split(';');
document.getElementById("client").innerHTML = a[0] ;
document.getElementById("adresse1").innerHTML = a[1] ;
})
}
window.onload = fiche;
</script>
You cannot POST to an external domain, only GET requests pass data to external.
I would suggest using $_REQUEST in your php script as opposed to $_POST, this way you can see all data coming in regardless of how it was sent.
in this case I can send data, but no return
<script type="text/javascript">
function get_XmlHttp() {
// create the variable that will contain the instance of the XMLHttpRequest object (initially with null value)
var xmlHttp = null;
if(window.XMLHttpRequest) { // for Forefox, IE7+, Opera, Safari, ...
xmlHttp = new XMLHttpRequest();
}
else if(window.ActiveXObject) { // for Internet Explorer 5 or 6
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp;
}
// sends data to a php file, via GET, and displays the received answer
function ajaxrequest(pid) {
var request = get_XmlHttp(); // call the function for the XMLHttpRequest instance
// create the URL with data that will be sent to the server (a pair index=value)
var url = 'http://www.mydomain.fr/connexion.php?term=3334';
request.open("GET", url, true); // define the request
request.send(null); // sends data
// Check request status
// If the response is received completely, will be transferred to the HTML tag with tagID
request.onreadystatechange = function() {
if (request.readyState == 4) {
alert ("toto");
document.getElementById("context").innerHTML = request.responseText;
}
}
}
window.onload = ajaxrequest;
</script>
<div id="context"></div>

Categories