I have tried various methods for this but I didn't get this one, can anyone give a proper solution for this? Actually, I know how to call a web service by using ajax calls, but whenever I try to pass my url as below, it gives me the following error:
onInit: function() {
$.ajax({
url:"http://SERVER_IP/SAP_DEMO/register.php",
type: "POST",
datatype:"json",
accepts:{ text:"application/json" },
success: function(oResData){
if(!oResData) {
sap.m.MessageToast.show("No Success");
}
else { sap.m.MessageToast.show(" Success"); }
},
error: function() { sap.m.MessageToast.show("unsuccessful json call"); }
});
var oModel=new sap.ui.model.json.JSONModel();
sap.ui.getCore().setModel(oModel);
}
The above code gives me this error:
error: Fiori Architectural guidelines: ESLint(sap-no-hardcoded-url): Hardcoded (non relative) url found.
In the docu here it says:
“sap-no-hardcoded-url:
Use of hardcoded URLs is not allowed.
SAP Fiori guidelines do not allow usage of hardcoded URLs to internal or external systems.
Rule Details:
Instead of references to internal systems in your URLs, you should only reference the path to the resource.”
You need to define the destination in a separate step as seen in this blog.
Related
I have been successfully accessing data from an external weather data service API for some time now using PHP cURL. Sometimes it takes a few seconds, sometimes up to 15 seconds for this web service to process my request. Therefore, I would like to perform this operation asynchronously.
I am trying jQuery AJAX to send this GET request now. However, it keeps throwing the following error:
"No Access-Control-Allow-Origin header is present on the requested resource".
I'm aware of the "same origin policy" restrictions, and have been researching it extensively here on stackoverflow and the jQuery docs. The docs say that JSONP requests are not subject to this restriction. When I try to designate JSONP as the dataType, I get an "unexpected token" syntax error.
I have the user entering in their zip code into a form text box, then click the button to submit. This sends the GET request to the web service. I'm very comfortable with PHP, but a newbie with jQuery and AJAX. I appreciate the help with this, and look forward to the day when I can help others as I've been helped here.
Here is the jQuery code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"> </script>
<script type="text/javascript">
$(document).ready(function () {
$('#btnGetETo').click(function () {
var resultElement = $('#resultDiv');
var requestData = $('#txtZip').val();
$.ajax({
url: 'http://et.water.ca.gov/api/data?appKey=B51CF64B-C37B-406A-83F1-1DBD8CE40EEF&targets=94805&startDate=2015-07-01&endDate=2015-07-01&dataItems=day-asce-eto,day-eto,day-precip&unitOfMeasure=E;prioritizeSCS=Y',
method: 'get',
data: { q: requestData },
dataType: 'json',
success: function (response) {
if (response.message != null) {
resultElement.html(response.message);
}
else {
resultElement.html('ETo: ' + response.DayAsceEto[0].value);
}
},
error: function (err) {
alert(err);
}
});
});
});
</script>
Unfortunately, it seems that the API in question does not support JSONP. In fact, they seem to have gone out of their way to make it difficult to query via JavaScript.
Here's how to test for JSONP (not foolproof, but most mainstream JSONP-enabled services will respond correctly). Take whatever URL you were planning to send, and add &callback=foo to the end of it. (If there are no other query string parameters of course, use ? instead of &.)
If the server supports JSONP, the response should look like:
foo({
...
});
If not, it'll look like:
{
...
}
As you can see, the only difference is that JSONP-enabled servers can wrap the JSON in a function of arbitrary name. Some servers will insert a little extra code for safety/convenience. For example, the following output was generated by the JSONplaceholder API using the URL http://jsonplaceholder.typicode.com/users/1?callback=foo:
/**/ typeof foo === 'function' && foo({
"id": 1,
"name": "Leanne Graham"
...
});
The upshot of all this is that it's the API provider's fault, not yours. If I were giving them feedback I'd make the following suggestions:
Handle cross-origin requests correctly.
Allow fallback to JSONP.
$.getJSON('http://robloxplus.com:2052/inventory?username=itracking', function(data){
$.each(data, function(item){
console.log(item['id'])
});
});`
returns undefined when attempting to run it on an external website. It is supposed to output each id of every item in that list (http://robloxplus.com:2052/inventory?username=itracking)
How do I fix this?
Edits>
I want to iterate over each individual id, each of these numbers "168167114": and "135470963": etc. etc. and fetch the data that follows that (i.e. the name:"", totalSerial:"")
is the request being made on the same domain as robloxplus.com ?
I'm new to this.. I don't understand much about JavaScript and/or
JQuery. #Pedro Lobito no, it's not. –
Explanation:
HTTP requests from Javascript are traditionally bound by the Same
Origin Policy, which means that your ajax requests must have the same
domain and port. The common ways to get around this are JSON-P,
Proxying and message passing via s. These all have their
quirks, but the thing they generally have in common is legacy browser
support.
Solution
1 - If robloxplus.com is yours, you can enable CORS
2 - If not, you can use YQL (Yahoo! Query Language) to bypass CORS
When one of the above options is fulfilled, you can make your json request, i.e.:
$.ajax({
url: 'http://robloxplus.com:2052/inventory?username=itracking',
type: 'get',
dataType: 'json',
success: function(data) {
$.each(data.id, function(item) {
console.log(item);
});
},
error: function(e) {
console.log(e.message);
}
});
I am playing with Google API in javascript. I managed to get a list of my contact with the following code :
$.ajax({
url: 'https://www.google.com/m8/feeds/contacts/default/full?access_token=' + access_token + '&alt=json',
method: 'GET',
error: function(error) {
alert('An error has occured during contact creation.');
},
success: function(data, status){
console.log(data);
}
});
I tried to add a contact by changing GET to POST and adding my contact data in the request body. But as soon as I add a data attribute, or change GET to POST, the server answers me the really annoying "No 'Access-Control-Allow-Origin" error.
Any idea?
I am following this documentation : https://developers.google.com/google-apps/contacts/v3/?csw=1#creating_contacts
Thanks a lot
It is possible to do this from the browser, although not obvious at all.
Based on this SO answer, we learn that there is method called gapi.client.request that can be used for this (instead of jQuery's $.ajax).
Accordingly, for editing we can do:
gapi.client.request({
method : 'PUT',
path:'m8/feeds/contacts/default/full/<contactId>/<editRevisionFromGET>',
body : {"version":"1.0","encoding":"UTF-8","entry": ...},
callback : function(data) {
console.log(data);
}
});
The important parts for editing in here are:
send back the entire entry you got before from a read
use the current ID given at the end of the URL in the entry.link element with relation type edit (or you'll get a HTTP Status 409 - Conflict)
Side note:
Notice that these requests actually are done to https://content.googleapis.com/ ...
From some quick tests, it seems you can do ?all? requests just to that URL instead of google.com, and then CORS issues disappear.
I've created a custom object, called 'Opinion' to build custom stories around it.
I'm trying to add some app-owned objects from my website using the javascript sdk.
The sample code facebook gives me is:
FB.api(
'me/objects/[namespace]:opinion',
'post',
{
app_id: xxxxxxxx,
type: "[namespace]:opinion",
url: "http://samples.ogp.me/331257847005141",
title: "Sample Opinion",
image: "https://fbstatic-a.akamaihd.net/images/devsite/attachment_blank.png",
description: ""
},
function(response) {
// handle the response
}
);
The reponse is an error (OAuth Exception):
2500: Cannot specify type in both the path and query parameter.
If i remove the type parameter, i get another error:
(#100) The parameter object is required
Same if I remove [namespace]:opinion from the path.
I don't understand why, and there's no reference about this after googling it.
Why this? Any resource i can refer to solve that?
The object is a JSON-encoded version of an object, the sample code generated for you was incorrect. Also remove type from the parameter list.
So something like,
FB.api(
'me/objects/[namespace]:opinion',
'post',
{
object: {"app_id":xxx,"url":"http:\/\/samples.ogp.me\/331257847005141","title":"\"Sample Opinion\"","image":"https:\/\/s-static.ak.fbcdn.net\/images\/devsite\/attachment_blank.png","description":"\"\""}
},
function(response) {
// handle the response
}
);
An example of how it looks can be seen at http://philippeharewood.com/facebook/objectify.html and it was based off the curl example given at https://developers.facebook.com/docs/opengraph/using-object-api/
For anyone struggling with a similar problem on iOS, the sample code again appears to be wrong, however the following seems to work:
NSMutableDictionary<FBOpenGraphObject> *object =
[FBGraphObject openGraphObjectForPostWithType:#"<appnamespace>:<objecttype>"
title:#"..."
image:[result objectForKey:#"uri"]
url:nil
description:#"..."];
[FBRequestConnection startForPostOpenGraphObject:object completionHandler:^(FBRequestConnection *connection, id result, NSError *error)
{
// handle the result
if ( error ) {
DLog(#"error %# creating object", error);
} else {
...
}
}];
I'm trying to display the follow count of a twitter account, but when I hook into the API using this code:
$.getJSON("https://api.twitter.com/1/users/show.json?screen_name=uswitchTech&include_entities=true", function(data) {
console.log(data);
if (!data.error) {
$("#followers").html(data.followers_count);
}
});
I get a 200 ok report but with Data is null message.
But if I download the json file to my local machine and change the getJSON call accordingly, it works straight away.
Has anyone got any ideas on what could be causing this?
Thanks
Also just to add, if I put the Twitter API url into my browser it displays all the data, which makes it even weirder.
Maybe the problem lies with jsonP, since you are calling a remote server and you must specify you should use jsonP. Have you tried adding callback=? as a parameter
$.getJSON("https://api.twitter.com/1/users/show.json?screen_name=uswitchTech&include_entities=true&callback=?", function(data) {
if (!data.error) {
$("#followers").html(data.followers_count);
}
});
Taken from jQuery docs
JSONP
If the URL includes the string "callback=?" (or similar, as
defined by the server-side API), the request is treated as JSONP
instead. See the discussion of the jsonp data type in $.ajax() for
more details.
$.ajax({
url: 'https://api.twitter.com/1/users/show.json?screen_name=uswitchTech&include_entities=true',
dataType: 'jsonp',
success: function(data){
console.log(data.followers_count);
}
});