js working in console but not from function - javascript

I'm calling the below function after the data from an ajax call is returned. It performs the first console.log() which contains the data from the ajax call. But the each() loop iterating through - response, does not console.log anything.
primaSaveOrder.prototype = {
start: function(response){
console.log(response)
$j('#primaId').val('');
$j('#dialog').closest('.ui-dialog-content').dialog('close');
$j.each(response['billing'], function(i, val) {
console.log(response['billing'][i])
});
},
}
I don't think my code is too wrong though because if I manually create a variable in the console equal to the output of - console.log(response) and then run the -
$j.each(response['billing'], function(i, val) {
console.log(response['billing'][i])
});
it works. What I would prefer to run is $j('#' + i).val(response['billing'][i]) instead of console.log(response['billing'][i].
This also works if I do it directly in the browser but not in the file. I assume it's related but I can't figure out how to fix it.
this is an example of what i am iterating with some data changed for privacy
{"billing":{"order-billing_address_firstname":"test","order-billing_address_lastname":"test","order-billing_address_street0":"6 test","order-billing_address_street1":"test","order-billing_address_city":"","order-billing_address_country_id":"GB","order-billing_address_region":"","order-billing_address_postcode":"16","order-billing_address_telephone":"","order-billing_address_vat_id":"","order-billing_address_prima_address_code":"0"},"shipping":{"order-shipping_address_firstname":"test","order-shipping_address_lastname":"test","order-shipping_address_street0":"6 test","order-shipping_address_street1":"test","order-shipping_address_city":"","order-shipping_address_country_id":"GB","order-shipping_address_region":"","order-shipping_address_postcode":"16","order-shipping_address_telephone":"","order-shipping_address_vat_id":"","order-shipping_address_prima_address_code":"0"}}

May be the type of response is String. In that case convert the response into json using
response = JSON.parse(response);
before using response for iteration.

I don't say, it will help, but there are several things that should be checked for issue root:
Check whether the elements exist and they are really unique (since ids are used). console.log(i, $j('#' + i).size()) may do the trick. I believe that there may be no elements to set values.
Use val argument directly instead of referencing it through response['billing'][i]. Though I don't see how the response var may be overridden or hidden, but let's use the value directly since it's passed into callback.

Related

getJSON not outputting the html data into a div

If I try to output that getJSON in console.log(data) is fine, i see it, yet it doesn't go into the div as I am expecting to.
Trying this:
$.getJSON("http://en.wikipedia.org/w/api.php?action=parse&format=json&callback=?",
{
page:"Football", prop:"text"
}, function(data) {
$(".modal-content").html(data);
});
<div class="modal-content"></div>
NOTE: console gives no error and div is empty
You have to access the text property of the returned object correctly. Just trying to set .html(.. by passing the returned object will not work, because jquerys .html() method expects a function or a string as the parameter.
According to wikis API:JSON version 2 you can add the following property to the options object passed to $.getJSON.
formatversion:2
Eliminate useless indirection, e.g. {"text":"..."} instead of {"text":{"*":"..."}} and {"key1":"value1","key2":"value2"} instead of [{"name":"key1","*":"value1"},{"name":"key2","*":"value2"}].
So here is the correct anwser.
var location = "https://en.wikipedia.org/w/api.php?action=parse&format=json&callback=?";
$.getJSON(location, {
page:"Football",
prop:"text",
formatversion: 2
}, function(data) {
$(".modal-content").html(data.parse.text);
//console.log(data.parse.text)
});

What is wrong with this Jquery Ajax request in Chrome?

I am using the following code to make a request to a PHP script:
$.ajax({
method: "POST",
url: "myAPI.php",
data: {
orderById: 2,
action: 'returnStuff',
},
success: function(data){
$.each(data.data, function(key, value) {
var $targetToMove = $('.shape.'+value.attr_name);
//if element already exists on page, move it to the end of the container
if($('.'+value.xml_name).length){
$('.container').append($targetToMove);
}
});
}
});
Here is a simplified example of my return data
{"data":{"0":{"id":"1","name":"This","color":"blue"},
"1":{"id":"2","name":"That","color":"red"},
"2":{"id":"3","name":"whatever","color":"blue"}}}
If the orderById equals 1, the data is returned numerically from lowest to highest by the id. If it equals 2 it is returned numerically from highest to lowest like this:
{"data":{"0":{"id":"3","name":"whatever","color":"blue"},
"1":{"id":"2","name":"That","color":"red"},
"2":{"id":"1","name":"This","color":"blue"}}}
The idea is that the API returns the data in the order I want, then on success in the ajax call, the elements are re-arranged on the page in the order of the returned data object.
This works how I intend in Firefox, but in Chrome, whenever I console log the data on success, the order is always the same, despite the console indicating the response from my API is in the correct order.
What am I missing? I can't tell if this is a caching issue or if I am just overlooking something in my javascript.
Object properties order is not guaranteed in JavaScript. You would rather use Array for that
Format you json to look like this:
{"data":[{"id":"3","name":"whatever","color":"blue"},{"id":"2","name":"That","color":"red"},{"id":"1","name":"This","color":"blue"}]}

$.getjson not working / json storage

I'm trying to do a getJSON call to a page within my domain that is simply a json array, which is not returning anything given the script in my webpage:
<script>
$('#genButton').click(function() {
console.log("click");
$.getJSON("http://mygithub.github.io/repository/quotedb.json", function(data){
console.log("executing");
var entry = data[Math.floor(Math.random()*data.length)];
console.log(entry);
$("#quoteDisplay").text(entry);
}).fail(function() {
console.log( "error" );
});
})
</script>
When the button is clicked, the console logs the "click", but never logs "executing", but also doesn't log any errors related to the getJSON. The debugger also never pauses within the getJSON function.
My question is, 1. Is it valid for quotedb.json to be literally a webpage with just a single json array? Or does the page need to be annotated in some way so that the getJSON request knows where to pick up the json from? 2. If (1) is fine, then are there any other reasons you can see why nothing from the getJSON return function would appear?
The json is again one array of json objects, in the form:
{
"character": ""
"quote": ""
}
EDITS
With the edited code, it now outputs "click" followed by "error" from the .fail() method of the $.getJSON call now.
I tried removing the ?callback? section of the url as suggested below, which did not work.
The /repository/ section of my url seems to be necessary to access the file.
Try without ?callback=? at end of url, see jQuery.getJSON()
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.

How can I pass data read from a JSON file to the rest of my Javascript code?

I'm new in the scripting and web world and have been trying to work through an issue I've been having. I am reading data from a local JSON file, and have been able to use jQuery.getJSON and jQuery.parseJSON successfully, but I am trying to use the data outside of the getJSON callback function and am having issues. I think it comes down to me not fully understanding the correct way to do this, and that's where I'm looking for your help. Here's my code:
var names = new Array();
$.getJSON('ferries.json', function(data) {
var jsondata = $.parseJSON(JSON.stringify(data));
var length = jsondata.nodes.length;
for (var i = 0; i < length; i++) {
names[i] = String(jsondata.nodes[i].name);
}
});
console.log('Names: ' + names[0]);
The final line returns undefined. If I were to write that line right after the for loop, it would return the desired value. Here's how the JSON file is structured:
{
"nodes":[
{
"name":"John"
},
...
{
"name":"Joe"
}
]
}
Any help would be appreciated - thanks!
Edit: One last thing, it seems that the final line (console.log(...)) executes before the $.getJSON bit, which confuses me as well.
$.getJSON runs asynchronously. The function that you pass to it is a "callback", which means that it gets called when getJSON comes back from doing its thing.
If you want to do something with the JSON data that you get back, you must wait for the callback to execute.
Also, on a side note, $.parseJSON(JSON.stringify(data)) is redundant. The data object is already a perfectly usable object with your data in it, but you're turning that object back into a JSON string and then immediately back into an object. Just use data as is. For more information, check out the jQuery API docs for getJSON.

Callback function being skipped on jQueries .getJSON command

I have the following snippet of code:
$('input#teamName').live('blur', function() {
var value = $(this).val();
if (value) {
$.getJSON('api/event_company/'+value, function(data) {
console.log('why does this not want to work?');
});
}
});
Basically all it's doing is requesting some data from the server when a form field changes. My problem is that nothing in the callback function every gets called even though I can see using firebug that it has successfully sent a request to the server and received a valid JSON response.
If I change the getJSON parameters to:
$.getJSON('api/event_company/'+value, alert('Blah'));
Then the alert pops up as expected. Any ideas what might be causing this behavior?
If the JSON is invalid, the parsing will fail and the handler won't be called. From getJSON docs:
Important: As of jQuery 1.4, if the JSON file contains a syntax error, the request will usually fail silently. Avoid frequent hand-editing of JSON data for this reason. JSON is a data-interchange format with syntax rules that are stricter than those of JavaScript's object literal notation. For example, all strings represented in JSON, whether they are properties or values, must be enclosed in double-quotes. For details on the JSON format, see http://json.org/.
See if your JSON validates.
Your second example is not correct. It should instead be,
$.getJSON('api/event_company/'+value, function() {
alert('Blah');
});

Categories

Resources