Uncaught ReferenceError: set_metadata is not defined - javascript

I'm using the Yummly API (https://developer.yummly.com/documentation) and I am trying to parse a JSONP list of courses to use in a drop-down box. The format of the file I am requesting (located at http://api.yummly.com/v1/api/metadata/course?_app_id=[My App ID]&_app_key=[My App Key]) is:
set_metadata('course', [{"id":"course-Main Dishes","type":"course","description":"Main Dishes","searchValue":"course^course-Main Dishes"},....................}])
The request seems to work fine, and I can view the results in the Network tab in Chrome. However, in the console I get the error "Uncaught ReferenceError: set_metadata is not defined" I've done a lot of looking around, and have found people with similar but different errors, but I have not understood the cause or why the fixes for their errors work. I am fairly new to jQuery, so I'm guessing I'm doing something wrong with my request, which is:
var coursesURL = 'http://api.yummly.com/v1/api/metadata/course?_app_id=' + appID + '&_app_key=' + appKey;
var courses = [];
//Query for the list
$.getJSON(coursesURL + '?callback=?', null, function(data) {
console.log(data);
//Go through each result object found
$.each(data.course, function(i, course) {
courses.push(course.description);
});
console.log(courses);
});
Any help is greatly appreciated. I would also really appreciate an explanation of what I am missing, not just the fix. Thank you.

The reasons I'm adding this as an answer and not a comment are because i don't have enough reputation to comment and this is the only thing i can find on the yummly api returning jsonp.
I was able to get past the "uncaught referenceError" problem but now its only returning the word 'allergy', which is in the response, and I'm not getting the rest of the data.
here is my code:
$.ajax({
url:"//api.yummly.com/v1/api/metadata/allergy?_app_id=[APP_ID]&_app_key=[APP_KEY]?callback=",
dataType:"jsonp",
jsonpCallback:"set_metadata",
beforeSend:function(){
console.log("sending");
},
success: function (data){
console.log(data);
},
error: function(data){
console.log("send error and returned:");
console.log(data);
}
});
here is the response:
set_metadata('allergy', [
{"id":"392","shortDescription":"Wheat-Free","longDescription":"Wheat-Free","searchValue":"392^Wheat-Free","type":"allergy","localesAvailableIn":["en-US","en-GB"]},
{"id":"393","shortDescription":"Gluten-Free","longDescription":"Gluten-Free","searchValue":"393^Gluten-Free","type":"allergy","localesAvailableIn":["en-US","en-GB"]},
{"id":"394","shortDescription":"Peanut-Free","longDescription":"Peanut-Free","searchValue":"394^Peanut-Free","type":"allergy","localesAvailableIn":["en-US","en-GB"]},
{"id":"395","shortDescription":"Tree Nut-Free","longDescription":"Tree Nut-Free","searchValue":"395^Tree Nut-Free","type":"allergy","localesAvailableIn":["en-US","en-GB"]},
{"id":"396","shortDescription":"Dairy-Free","longDescription":"Dairy-Free","searchValue":"396^Dairy-Free","type":"allergy","localesAvailableIn":["en-US","en-GB"]},
{"id":"397","shortDescription":"Egg-Free","longDescription":"Egg-Free","searchValue":"397^Egg-Free","type":"allergy","localesAvailableIn":["en-US","en-GB"]},
{"id":"398","shortDescription":"Seafood-Free","longDescription":"Seafood-Free","searchValue":"398^Seafood-Free","type":"allergy","localesAvailableIn":["en-US","en-GB"]},
{"id":"399","shortDescription":"Sesame-Free","longDescription":"Sesame-Free","searchValue":"399^Sesame-Free","type":"allergy","localesAvailableIn":["en-US","en-GB"]},
{"id":"400","shortDescription":"Soy-Free","longDescription":"Soy-Free","searchValue":"400^Soy-Free","type":"allergy","localesAvailableIn":["en-US","en-GB"]},
{"id":"401","shortDescription":"Sulfite-Free","longDescription":"Sulfite-Free","searchValue":"401^Sulfite-Free","type":"allergy","localesAvailableIn":["en-US","en-GB"]}
]);
the line of code that says:
jsonpCallback:"set_metadata",
in the ajax call gets me past the reference error but im not getting the rest of the data that's in the response.
please help?
Finbar

I figured out the problem.
JSONP is returning not JSON text, but a function to the callback. Thus, I needed a function in my code called "set_metadata" that is used upon success of the json/ajax call.
Specifically, I defined function
function set_metadata(course, data) {
//Do stuff here
};
I tested it and that correctly captures the data I am trying to get.

Related

AJAX + jQuery confusion?

So right now I'm trying to understand this piece of code:
VADER.ATTRACTION = {};
VADER.servicebaseurl = './services/'
var scriptLocation = VADER.servicebaseurl + 'attraction?callback=?';
$.ajax(scriptLocation, {
dataType: 'jsonp',
error: function (jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
},
success: function (data) {
VADER.ATTRACTION.data = data;
}
});
I can understand the gist of most of it, it basically uses jQuery 's .ajax() method to get data. My question is on the line right here:
VADER.servicebaseurl = './services/'
var scriptLocation = VADER.servicebaseurl + 'attraction?callback=?';
What does ./services/ and attraction?callback=? come from?? Especially the attraction?callback=? part, is that ajax? I'm pretty sure that attraction is the table name in the database..... I just can't figured out what that is the syntax, and I've googled callback=? to no avail so....
Maybe this is a dumb question, but I'm really confused since I'm new to ajax,jQuery, and javascript in general..... any help would be greatly appreciated, thank you!!
attraction?callback=? are just extra bits of the URL that are processed by the server. You'd need to go and examine the server side code to find out what it does.
All ajax does is send a request to a URL and gathers whatever is returned to it. The URL itself doesn't need any special bits that are ajax specific, so in the above example, you could put anything into scriptLocation and if it was a valid, error-free URL that returned something, you'd get that in your success function.
In your case data is returned, then assigned to the javascript object VADER.ATTRACTION - the URL queried by ajax only has to create a successful request for this code to be executed and any code could be executed on success.

AJAX and JSON error handling

I have a form which submits data via AJAX to an external server.
The data which gets sent is then validated and if correct the user can then advance onto the next step of the form.
If the data is not valid, then the server returns an error which is outputted as a JSON object.
I can see the JSON object in FIDDLER.
My aim is to grab that JSON data and output it on the page and notify the user.
Ideally, i would do this as part of an error handler on the AJAX request(found below).
Is this achievable?
PS:
Unfortunately, I can't set up a demo because the link that the data is posted to is only available on my network.
It is also worth pointing out that the error that the back-end script outputs is actually stored in the link that the data is posted to.
AJAX REQUEST:
var setUpVrmData = function() {
$("#getvrmdata").click(function () {
var p_vrm = $('#p_vrm').val();
$.ajax({
dataType: "JSON",
type: "POST",
url: "http://217.35.33.226:8888/l4_site/public/api/v1/BC8F9D383321AACD64C4BD638897A/vdata",
data: {
vrm: p_vrm,
},
success: function(data) {
//Empty the dropdown box first.
$("#p_model").empty();
appendString = "<option value='none'>-- Select your model --</option>";
$.each(data['vehiclemodel'], function (k, v) {
// += concatenate the string
appendString += "<option value='" + k + "'>" + v + "</option>";
});
$("#p_model, #ent_mileage").show();
$('.js-find-my-car').hide();
$('.js-get-price').show();
$("#p_model").append(appendString);
$("#p_model").prop("disabled", false);
$('#skey').val(data['skey']);
},
error: function() {
console.log("We return error!");
}
});
});
The Error function will return an XHR object that you may be able to parse to get the message you want. I don't know what is serving the data so depending on how that's setup your mileage may vary. I've done this using PHP as well as C# and writing to Console, but in both cases I was able to control the returned data.
I used this article : http://encosia.com/use-jquery-to-catch-and-display-aspnet-ajax-service-errors/ as a starting point.
You'll need to update:
error: function() {
console.log("We return error!");
}
to
error: function(xhr, status, error) {
console.log("We return error!");
}
Set a break point there in Firebug to check if an XHR object is passed, if not you'll need to find a way to get it.. You mention you can see the JSON in fiddler, it should be available to you. If it is, just use the eval posed in the article and you should be okay. If not you'll have to go and figure out how to get it, depending on your platform difficulty will vary.
A few things to note, eval is messy and can get you into trouble. In the cases I've done this, I removed the eval in production.
Also as of jQuery 1.8 success error and complete are deprecated. Use done fail and always if you plan on updating jQuery in the future.
jQuery API reference, for reference.
http://api.jquery.com/jquery.ajax/

jQuery ajax request to Flickr sporadically fails

Occasionally, an ajax request to Flickr's api will fail. I'm not sure if I'm doing something wrong here - or if I'm just not handling things correctly - but the code works over 90% of the time. When it doesn't work, I get the following error message from Firefox's console:
TypeError: jQuery19109306644694293944_1362865216185 is not a function
(I am letting jquery generate the callback, which is why the callback is named like that.)
This is the code that sometimes fails:
function getAppropriateSize(photo){
console.log("In getAppropriateSize");
/** stuff. query is defined here **/
$.ajax({
url: 'http://api.flickr.com/services/rest/?method=flickr.photos.getSizes&format=json&api_key='+flickrKey+'&photo_id='+query.id,
dataType:'jsonp',
jsonp:'jsoncallback',
timeout:3000,
success: function(sizes){
console.log("In success - getAppropriateSize");
/**determine the correct size**/
flickrURL = sizes.sizes.size[currVal].source;
},
error: function(xmlhttprequest,textstatus,msg){
console.log("In error - getAppropriateSize");
/* handle error*/
}
});
}
I've checked what's returned when this happens and JSLint says it's valid javascript. flickrURL also gets set to a valid URL. I'm pretty mystified about what's causing this error - any help would be appreciated.
Edit: I was messing around and this time getAppropriateSize just received two separate messages from flickr for one call. The first one was
({stat:"fail", code:1, message:"Photo not found"})
The second one was the a full response from the server that also produced the TypeError mentioned above. However, the second response found the photo and gave me the sizes.

404 error with Ajax request

I need to grab some data from a JSP page that does a select on a database and then put inside a div. I need to do this with ajax.
Here is my code:
$(function() {
teste();
});
function teste() {
var v1 = document.getElementById("selCodigo").value;
alert(v1);
$.ajax({
type : "GET",
data : "turma="+v1,
url : "busca-notas.jsp",
success : function(resposta){
alert("DEU CERTO");
},
error : function(xhr, ajaxOptions, thrownError){
alert(xhr.status);
alert(thrownError);
document.getElementById("notas").innerHTML = "ERRO";
}
});
}
I tested the variable v1 and the value that it receives necessary, and in my JSP page, I do this:
String turmaSelecionada = request.getParameter("turma");
the problem is that the ajax content that does not feed into the div need, beyond what the xhr.status presents thrownError and a 404 error not found
Can anyone help me?
Either, busca-notas.jsp does not exist, or it is on a different server or path as the HTML calling the Ajax request.
Example: If your HTML and JavaScript is here:
http://www.example.com/somepath/page.html
and your PHP code is here:
http://www.example.com/otherpath/busca-notas.jsp
then you'll Need to use url: "../otherpath/busca-notas.jps". There is an easy way to check: Open your HTML in the browser, remove the last bit of the path, and replace it with "busca-notas.jpg", and see what you're getting.
A 404 also means, your JSP code never gets executed.
This is saying the resource you are trying to do a GET to is not there. The path you are doing a GET to is probably incorrect. Can you tell the structure of your files (javascript/service files etc...). I would suggest using the browser developer tools or fiddler to debug what is going on.
Use F12 (windows) with browsers to get to the developer tools. Also the fiddler tool is great! http://www.fiddler2.com/fiddler2/
On a side note if you use console.log for debugging you will never go back to alerts :)

variables showing as undefined in firebug when they are defined

here is my site http://iadprint.com/products?product=Business%20Card
when i select a value for quantity a price is supposed to show in the pricing div on the top right.
this used to work but for some reason today in firebug under dom i can see that a few variables show undefined. when i do the ajax call iadprint.com/ajax.php?id=1 the data shows correctly and the variables in the js are all defined. what can be wrong? here are the variables that i am seeing undefined.
woCoating_price
woColor_price
woDesign_price
woJob_Name_price
woPDF_Proof_price
woQuantity_price
woRound_Corners_price
woTurnaround_price
I replaced your $.get() call with a full $.ajax() call that includes an error: callback.
The result is that you're getting a parse error because your JSON response is invalid.
"parsererror" "Invalid JSON: {"price":"15.00"}<br/>"
You need to get rid of that <br/> tag.
If this isn't it, then you'll need to provide specific detail on how to reproduce the problem, and in which part of your code you expect to see a defined value.
EDIT: Here's the change handler I used after removing yours:
$("#Quantity").change(function () {
hash = $("#Quantity").val();
console.log('hash',hash);
$.ajax({
url:"ajax.php",
data: { id: hash },
dataType:'json',
success:function (out,b,c) {
woQuantity_price = out.price;
displayPrice();
console.log(out,woQuantity_price,b,c);
},
error:function(a,b,c){
console.log('error:',a,b,c);
}
});
});

Categories

Resources