WFS-T call to Geoserver using dojo.request.xhr - javascript

I am using dojo.request.xhr to make a post reqeust to geoserver.
But the problem is when i'm using XMLHttpRequest to make the post request , it is working fine on the other hand when i'm using dojo.reqeust.xhr for the same thing its giving the following error.
*
org.xmlpull.v1.XmlPullParserException: only whitespace content allowed
before start tag and not i (position: START_DOCUMENT seen i... #1:1)
only whitespace content allowed before start tag and not i (position:
START_DOCUMENT seen i... #1:1)
*
dojo.request.xhr code -
xhr(url, {
handleAs : "xml",
data : postData,
method : "POST",
headers : {
'Content-Type' : 'text/xml',
},
}).then(function(data){
console.log(data);
}, function(err){
console.log("Error : " + err);
});
above code is not working and giving the above mentioned error.
This is same post request using the XMLHttpRequest :-
var req = new XMLHttpRequest();
req.open("POST", url, true);
req.setRequestHeader('Content-type', 'text/xml');
req.onreadystatechange = function () {
if (req.readyState != 4) return;
if (req.status != 200 && req.status != 304) {
alert("Error");
return;
}
var xml = req.responseXML;
console.log(xml);
}
if (req.readyState == 4) return;
req.send(postData);
To check the XML(that i'm sending as postData) whether it is valid or not i used GeoServer's demo request tool to build the WFS request and its working fine.
UPDATE :- This is the link of XML file that i'm sending as a postData.
post_XML_File
Can anyone have any idea what i'm doing wrong?? Thanks in advance.

Related

Data not displaying in JavaScript API

I am making a Pokedex API as a side project and I can not display the data needed to display in the different text boxes. I am using a GET request to request the height, weight, type, and ability.
<script>
$("button").click( function(){
var pokemonName = $('pokemon').val(pokemon);
event.preventDefault();
getPokemonData(pokemonName);
})
function getPokemonData(pokemonName){
var request = new XMLHttpRequest()
//GET request with link
request.open('GET','https://pokeapi.co/api/v2/pokemon/' + pokemonName, true);
// request for data
request.onload =function(){
var data = JSON.parse(this.response)
if(request.status >= 200 && request.status <= 400)
{
// outputs data
$(pokemonheight).val(response.height)
$(pokemonweight).val(response.weight)
$(pokemonAblity).val(response.ability)
$(pokemonType).val(response.type)
}
else
{
alert ("Error");
}
request.send();
}
}
</script>
</html>
I have tried setting a variable that would be equal to the response JSON element and then input that into the value of the textbox.
I do not have anything returned as expected or input displayed in the console if declared.
Issue(s)
There were a few issues with your code:
var pokemonName = $('pokemon').val(pokemon); you are setting the value of some element named pokemon (not valid) here
var data = JSON.parse(this.response); where is this.response being set? Shouldn't we be receiving response in the callback?
request.send(); is inside of the onload event, so the request never gets sent
Critiques
My main critique here is that you included a fairly large library (jQuery), and didn't utilize it to make the request. $.ajax is well documented and cleans up a lot of the intricacies of XMLHttpRequest.
The solution
$("button").click(function() {
var pokemonName = $('#pokemon').val();
//event.preventDefault();
getPokemonData(pokemonName);
})
function getPokemonData(pokemonName) {
var request = new XMLHttpRequest()
//GET request with link
request.open('GET', 'https://pokeapi.co/api/v2/pokemon/' + pokemonName, true);
// request for data
request.onload = function(response) {
var data = JSON.parse(response.currentTarget.response)
if (request.status >= 200 && request.status <= 400) {
// outputs data
console.log(data)
} else {
alert("Error");
}
}
request.send();
}
<input id="pokemon" value="12" />
<button>search</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Taking all the above issues into account, I was able to get a working example of what it should ultimately look like.
Hope this helps!

how to programmatically enable data sources across domains in browser.?

I am using $.ajax() function in my script which is calling web service from other domain. but I am getting error in IE. Then after doing research, I came to know error was coming due to Internet Explorer by default set "Access data sources across domains" to "prompt". How to set it "Enable" using script..?
Code:
var serviceURL = "https://www.other-domain.com/webservice/showbills?billID=12458";
if ($.browser.msie && window.XDomainRequest) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
var data = xhr.responseText;
var xmlDoc = $.parseXML(data); // then parse into xml
var xml = $(xmlDoc); // create doc
console.log(xml);
// show bill here in table.
}
}
xhr.open('POST', serviceURL, true);
xhr.send();
} else {
$.ajax({
type: "POST",
url: serviceURL,
dataType: "text",
crossOrigin: true,
crossDomain: true,
success: function (data) {
var xmlDoc = $.parseXML(data); // then parse into xml
var xml = $(xmlDoc);// create doc
console.log(xml);
// show bill here in table.
}
});
}
This giving error in browser.
I am getting SEC7120: Origin http://localhost:8080 not found in Access-Control-Allow-Origin header and SCRIPT7002: XMLHttpRequest: Network Error 0x80070005, Access is denied
Microsoft has created its own solution for cross domain AJAX requests in Internet Explorer, called XDomainRequest.
There is a plugin for jQuery to support this: https://github.com/MoonScript/jQuery-ajaxTransport-XDomainRequest
You just have to include this script after including jQuery and then it should work.

XMLHttpRequest does not send file

I want to upload a file trough a XMLHttpRequest. i have looked everywhere for examples and found quite a few. But i cant figer out what it is i am doing wrong. This is my code. The function is triggerd when a button is pressed. It not wrapped in from tags
function upl_kost() {
var url = "proces_data.php?ref=upload_kost";
var hr;
var file = document.getElementById("file_kost");
var formData = new FormData();
formData.append("upload", file.files[0]);
if (window.XMLHttpRequest) {
hr=new XMLHttpRequest();
} else {
hr=new ActiveXObject("Microsoft.XMLHTTP");
}
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "multipart/form-data");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
alert(return_data);
}
}
hr.send(formData);
}
and this function catches it.
if($_GET['ref'] == 'upload_kost') {
var_dump($_FILES);
}
My problem is that the $_FILES stays empty. When i look at the file.files variable in the js its loaded with the data from the file that i am trying to upload.
Thanks!
Reduce your JavaScript down to minimum required for this, then add in some helpful messages you can look in your console for
function upl_kost() {
var xhr = new XMLHttpRequest(),
url = 'proces_data.php?ref=upload_kost',
fd = new FormData(),
elm = document.getElementById('file_kost');
// debug <input>
if (!elm)
console.warn('Element not found');
else if (!(elm instanceof HTMLInputElement))
console.warn('Element not an <input>');
else if (!elm.files || elm.files.length === 0)
console.warn('<input> has no files');
else
console.info('<input> looks okay');
// end debug <input>
fd.append('upload', elm.files[0]);
xhr.addEventListener('load', function () {
console.log('Response:', this.responseText);
});
xhr.open('POST', url);
xhr.send(fd);
}
If you're still having a problem, it may be server-side, e.g. are you performing a redirect before trying to access $_FILES?
Your problem is that you're setting the content type of the request
hr.setRequestHeader("Content-type", "multipart/form-data");
If you ever saw a multipart/formdata post you'll notice the content type header has a boundary
Content-Type: multipart/form-data; boundary=----webko2354645675756
which is missing from your code.
If you do not set the content type header the browser will correctly set it and the required boundary. This will allow the server to properly parse the request body.

JavaScript Ajax request not working in Firefox and Google Chrome, but it is okay in Safari

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.

JavaScript - How to set request header for a browser GET

If we do window.location = "http://MyApi.com/Pdf";, browser does a GET of the URL http://MyApi.com/Pdf. But if we want to set authentication header of the request before doing GET of the URL because the server is a REST server and it doesn't support cookies. How to do this?
In all of the cases, I'm using $.ajax to call service but this time I need to show the response in a new window. Response is a PDF file content.
Thanks in advance.
In more recent browsers, you might be able to use blobs:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button onclick="tryit();">PDF</button>
<script>
function tryit() {
var win = window.open('_blank');
downloadFile('/pdf', function(blob) {
var url = URL.createObjectURL(blob);
win.location = url;
});
}
function downloadFile(url, success) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.setRequestHeader("Authorization", "Basic " + btoa("username:password"));
xhr.responseType = "blob";
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (success) success(xhr.response);
}
};
xhr.send(null);
}
</script>
</body>
</html>
In IE, ask the user:
window.navigator.msSaveOrOpenBlob(blob, 'readme.pdf');
P.S.
You can test the backend in Node:
router.get('/pdf', function(req, res) {
if(req.headers.authorization !== 'Basic dXNlcm5hbWU6cGFzc3dvcmQ=') return res.status(403).send('Not allowed');
res.sendFile(path.join(__dirname, 'public', 'render.pdf'));
});
router.get('/', function(req, res) {
res.render('index');
});
I think this is what you are looking for... Or correct me if i am wrong.
https://developer.mozilla.org/en/docs/Setting_HTTP_request_headers
If you don't care about hiding or obfuscating the user credentials then just use plain GET authentification:
use http://username:password#MyApi.com/ instead of http://MyApi.com/
Does it have to be a GET?
The reason I am asking is that you could just have a POST form (to a target="_BLANK") that posts whatever but shows an embedded file in a new window. Of course this wouldn't solve the issue with your custom headers, but then since you can also POST using jquery.ajax - which does allow you to set your own headers - you'd have the best of both worlds.
Here's a jQuery plugin that creates such a form dynamically in order to download whichever file. You could use this as a reference...
Hope this helps
You may consider setting the header in beforeunload or onunload event handler
You should configure $.ajax using beforeSend. Below an example, but of course I don't know if the exact setup will work for you without any code to look at.
$.ajax( {
url : '/model/user.json',
dataType : 'json',
'beforeSend' : function(xhr) {
var bytes = Crypto.charenc.Binary.stringToBytes(username + ":" + password);
var base64 = Crypto.util.bytesToBase64(bytes);
xhr.setRequestHeader("Authorization", "Basic " + base64);
},
error : function(xhr, ajaxOptions, thrownError) {
reset();
onError('Invalid username or password. Please try again.');
$('#loginform #user_login').focus();
},
success : function(model) {
cookies();
...
}
});
For this to work you need crypto-js.

Categories