Returns undefined when attempting to run JQuery - javascript

$.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);
}
});

Related

jQuery ignores HTTP request method and appends weird URL parameters

I have a web service that expects POST requests carrying a JSON string in the body. I'm trying to use this web service using jQuery, but I have two problems :
1) jQuery seems to always use the GET method, no matter what I do ;
2) jQuery seems to append weird things into the URL.
The relevant pice of my code :
var WEB_SERVICE_URL = 'http://localhost/XXXX/';
// ...
$.post({
url: WEB_SERVICE_URL + 'GetConfigLabels/',
contentType: 'application/json; charset=utf-8',
dataType: 'jsonp',
data: JSON.stringify(data),
processData: false,
success: function(response) {
// Whatever
},
error: function(xhr, message) {
// Whatever
}
});
The developper tools of the browser (Firefox Quantum 60.0.2) shows me a weird URL :
http://localhost/XXXX/GetConfigLabels/?callback=jQuery331012146934861340841_1530707758905&{}&_=1530707758906
While the following was expected :
http://localhost/XXXX/GetConfigLabels/
Also the HTML file is openned as a file (using file:///) through the file system, hence the use of JSONP for cross domain.
I failed to find existing questions related to this issue. What could be causing this ? Thank you !
Please refer to the dataType : json section at http://api.jquery.com/jquery.ajax/ :
"json": Evaluates the response as JSON and returns a JavaScript
object. Cross-domain "json" requests that have a callback placeholder,
e.g. ?callback=?, are performed using JSONP unless the request
includes jsonp: false in its request options. The JSON data is parsed
in a strict manner; any malformed JSON is rejected and a parse error
is thrown. As of jQuery 1.9, an empty response is also rejected; the
server should return a response of null or {} instead. (See json.org
for more information on proper JSON format
overrding random name of callback using jsonpCallback :
jsonpCallback Type: String or Function() Specify the callback function
name for a JSONP request. This value will be used instead of the
random name automatically generated by jQuery. It is preferable to let
jQuery generate a unique name as it'll make it easier to manage the
requests and provide callbacks and error handling. You may want to
specify the callback when you want to enable better browser caching of
GET requests. As of jQuery 1.5, you can also use a function for this
setting, in which case the value of jsonpCallback is set to the return
value of that function.

How to get JSON Object from URL

I'm very new to web development.
When I input this link
https://api.locu.com/v1_0/venue/search/?name=jimmy%20johns&api_key=b1f51f4ae241770f72fca5924d045733c4135412
into my browser, I can see the JSON object.
What do I need to do so can I use this JSON object in my javascript? I've tried using JQuery's $.getJSON with no luck.
EDIT
Using JSONP worked! Appending &jsonp=readJSON&?callback=? to the URL gave me back the JSON I wanted. Thank you for all the informative answers.
$.getJSON( "https://api.locu.com/v1_0/venue/search/?name=jimmy%20johns&api_key=b1f51f4ae241770f72fca5924d045733c4135412&jsonp=readJSON&?callback=?", function() {
console.log( "success" );
})
function readJSON(response){
console.log (response);
}
The question is, is this domain (api.locu.com) the same from where you serve your files? I suppose it isn't. In this case, you have two options:
Your backend can proxy the request from this site
You have to use a JSONP object if it's supported by the API
I'm no clear about your question, but I think you can use a call ajax, something like:
$.ajax({
url: "https://api.locu.com/v1_0/venue/search/?name=jimmy%20johns&api_key=b1f51f4ae241770f72fca5924d045733c4135412",
type: 'get',
cache: false,
success: function (response) {
console.log(response);
}
});
This should get the concept across if you are using JQuery... but you can use just about anything.
var url = "https://api.locu.com/v1_0/venue/search/?name=jimmy%20johns&api_key=b1f51f4ae241770f72fca5924d045733c4135412";
var result;
var settings = {
success: function(data){
result = data;
//do anything else related to this data here as you need it fetched, and is not linear.
}
}
$.ajax(url, settings);
Now, I noticed you used getJSON, which is pretty much the exact same. I did not however see you use a success function, so if you did your way, have you tried:
$.getJSON(url, function(data){
result = data;
});
I may be mistaken, but you say: "With no luck" so i have a limited understanding as to what you tried with $.getJSON
Not directly from inside a web browser, no. You would need to use a proxy: another server that makes this request in your behalf and then gives you the result.
Why not?
Web browsers are pretty tight on security. One of the strategies for protecting users from malicious activity is restricting the domains your Javascript can make HTTP requests to.
An HTTP request from your domain (the origin) to another domain is called a cross-origin request. These are forbidden by default, and you won't be able to read the response body, unless the received HTTP response includes the header Access-Control-Allow-Origin.
How then?
By using a proxy as an intermediary. The proxy is not a web browser, it doesn't care about Access-Control-Allow-Origin, and will read the response anyway.
There are a number of proxies you can use. An easy one is YQL (the Yahoo Query Language). Here's an article on the topic, using jQuery: http://ajaxian.com/archives/using-yql-as-a-proxy-for-cross-domain-ajax

JavaScript ajax, JSONP, Callback function to do something with data

Fellas,
I'm trying to do an ajax call to get some JSON. I can get around the cross origin issues in Chrome very easily but in IE the only way I got it working without throwing an error is using JSONP. My problem is that i don't know how to process the response. I can see that the call executes and it returns JSON in fiddler but how do i catch it and play with it in my code that's below.
$.support.cors = true;
function callAjaxIE(){
$.ajax({
type: 'GET',
async: true,
url: usageUrl,
dataType: 'jsonp',
crossDomain: true,
jsonp: false,
jsonpCallback: processDataIE,
// cache: false,
success: function (data) {
alert('success');
//processData(data)
},
error: function (e){
console.log(e);
}
}).done(function (data) {
alert('done');
});
function processDataIE(){
alert('processing data ie');
}
It works when i run it, it displays a message box saying 'processing data ie' but so what. How do i play with the results?
UPDATE:
So I've updated the code as per Quentin. It doesn't go into the 'success' block. It errors out with the following.
When i look at fiddler. The JSON is there. How do i get it?
Don't force the function name. That's a recipe for race conditions. Remove jsonpCallback: processDataIE. Let jQuery determine the function name.
Don't remove the callback parameter from the URL. Make the server read callback from the query string to determine which function to call. Remove jsonp: false,.
Use the success function as normal. (Get rid of processDataIE, that's what success is for).
Asides:
crossDomain: true is pointless. It tells jQuery that when it is using XHR (which you aren't) and the URL is pointing to the same origin (which it isn't) then it should not add extra headers in case the server does an HTTP redirect to a different origin.
async: true is pointless. That's the default, and JSONP requests can't be anything other than async anyway.
$.support.cors = true; is pointless at best and can be harmful. Remove it.
Don't override jQuery's detection of support for CORS by the browser. You can't make ancient browsers support CORS by lying to jQuery. You're using JSONP anyway, so CORS is irrelevant.
The above is the sensible, standard, robust solution.
If you want the quick hack that maintains all the bad practises you have in play, then just look at the first argument to processDataIE.

jQuery AJAX request to remote API blocked

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.

How to use JSONP

I have the following code
function exista(word) {
alert(word);
var exists = 1;
jQuery.ajax({
async: false,
url: "http://api.wordreference.com/0.8/key/json/roen/" + word,
dataType: 'json',
method: "GET",
success: function(transport) {
if (transport.Error || transport.Response)
exists = 0;
}
});
return exists;
}
which verifies if a word exists or not in a dictionary. Problem is it gives an Access-Control-Allow-Origin error. From what I gathered it seems I must use JSONP but I can't really figure out how (sorry, I am just beginning to learn JavaScript and all that). So, got any idea on how to modify the above code?
Thank you.
Your dataType should be jsonp, not 'json`.
UPDATE
According to http://www.wordreference.com/docs/api.aspx:
Additionally, for JSPONp, the JSON API can take an optional callback
function in the query string; simply add "?callback={yourCallback}" to
the end of the URL.
so the API does support JSONP.
Additionally, JSONP means "JSON with padding", so you will get a JSON response. JSONP merely allows use of CORS.
By changing your dataType to jsonp:
"jsonp": Loads in a JSON block using JSONP. Adds an extra
"?callback=?" to the end of your URL to specify the callback. Disables
caching by appending a query string parameter, "_=[TIMESTAMP]", to the
URL unless the cache option is set to true.
You can override the default callback by specifying one with the jsonpCallback setting.
Finally, you should also add an error handler and set async to true:
jQuery.ajax({
"async": true, //cannot be false for JSONP
"url": "http://api.wordreference.com/0.8/key/json/roen/" + word,
"dataType": 'jsonp',
"method": "GET",
"error": function (jqXHR, textStatus, errorThrown) {
//included so you can see any errors
console.log(textStatus + ': ' + errorThrown);
},
"success": function (data, textStatus, jqXHR) {
//According to API documentation
//data will not likely contain either Error, or Response
//so, exists will likely not change to 0
if (data.Error || data.Response) {
exists = 0;
}
}
});
UPDATE:
The solution to both the error and the "need to be synchronous" is going to be what Pointy pointed out earlier. You'll have to create a server-side proxy that runs on the same domain as your script.
The server-side proxy can return JSONP, but frankly simply returning JSON or XML is simpler since CORS is not an issue, and the proxy can be synchronous. For a PHP example script, the Yahoo! Developer Network hosts source code for a simple proxy.
For anything else regarding a server-side web service proxy, you'd need to specify which server language you're using (and it would probably be better suited as a different question).
For JSONP to work, you not only have to code for it on your side, but the site you're targeting has to expect to be used that way as well, and respond to requests accordingly.
If the other site does not have a JSONP API already, and you have no control over it, then JSONP is not an answer. You'll have to create a server-side proxy of your own.
edit — according to the site, they do support JSONP. You just need to add "?callback=?" to the end of the URL.

Categories