Hello,
1. Iam trying to fetch some data from external website/source via JQuery Ajax request.
Here is an example:
$(document).ready(function() {$.ajax({type: "GET",url: "https://stage.csrhub.com/number",headers: {'Authorization': "Basic " + btoa("myusername" + ":" + "mypassword")},success: function (data, status){console.log(data);alert('Thanks!'); },error: function(jqXhr, textStatus, errorMessage){console.log(textStatus);console.log(errorMessage);}});});
I am getting the following log in the console:
Is it possible at all to request outer domains from HS CMS?
2. In case it is posible, how can I assign HubL-variable with the response of the request?
Hey @rikotech,
If you have access to the server of the external site the best option here would be to setup CORS to allow the access. Cross-Origin Resource Sharing (CORS) - HTTP | MDN
If you don’t have access then you can kind of ‘hack’ it by adding a datatype of JSONP to your ajax request like so:
<script>
$(document).ready(function() {
$.ajax ({
type: "GET",
url: "https://stage.csrhub.com/number",
dataType: 'jsonp', <!----- JSONP ADDITION ----->
headers: {
'Authorization': "Basic " + btoa("myusername" + ":" + "mypassword")
},
success: function (data, status){
console.log(data);
alert('Thanks!');
},
error: function(jqXhr, textStatus, errorMessage){
console.log(textStatus);
console.log(errorMessage);
}
});
});
</script>
For adding HubL, as long as you are adding the code somewhere that allows HubL (an HTML/HubL file or the HTML/HubL section of a custom module) you can use the variables like you would in HTML.
<script>
$(document).ready(function() {
$.ajax ({
type: "GET",
url: "https://stage.csrhub.com/number",
dataType: 'jsonp', <!----- JSONP ADDITION ----->
headers: {
'Authorization': "Basic " + btoa("myusername" + ":" + "mypassword")
},
success: function (data, status){
console.log(data);
alert('Thanks!');
},
error: function(jqXhr, textStatus, errorMessage){
console.log(textStatus);
console.log({{ module.error_message }}); <!---- EXAMPLE HUBL --->
}
});
});
</script>