Getting certain items with get - javascript

Sorry if my title is a little confusing I don't know really how to explain it.
API: http://mcping.net/api/162.223.8.210:25567
So I have this code that goes to an API, and I only want it to get the 'variables' online, and max. How would I do this?
Code:
$.get('http://mcping.net/api/162.223.8.210:25567', function(data){
$.each(data, function(index, item){
console.log(index + " ; " + item)
});
});

Try this
$.get('http://mcping.net/api/162.223.8.210:25567', function(data){
console.log(data.online);
console.log(data.max);
});
If your data is already a Javascript object, so you can call its variables properties like in the snippet code.
Just in case I tested it in this fiddle http://jsfiddle.net/js18ykj1/

Related

Add JSON to option values

I've been working with PHP for a while. I just started learning how to work with JSON.
I was able to create a PHP file that returns JSON. In my main file, I reference the PHP file and get the JSON objects.
I can display the objects in a dropdown select menu like this:
$.getJSON( "folder/services.php", function( data )
{
$.each(data, function(index, item)
{
$('#service').append($("<option>" + item.SERVICE + "</option>"));
});
});
The above code works fine. I can display the SERVICE values in the dropdown SELECT options.
What I am trying to figure out is how to get the SERVICE into the VALUE of the OPTION. I hope I am saying that correctly.
Typically, the OPTION tag would look like this:
<option value="SERVICE_A">Service A</option>
<option value="SERVICE_B">Service B</option>
...
But since I'm using JSON, I am not sure how to get the value into the OPTION.
I attempted to use PHP inside of the JQuery, but was unsuccessful. I'll show you what I attempted:
$('#service').append($("<option value='".+ item.SERVICE +."'>" + item.SERVICE + "</option>"));
****** EDIT ******
I attempted this piece of code submitted by LShetty below:
$.getJSON( "folder/services.php", function( data )
{
var strToAppend = "";
$.each(data, function(index, item)
{
strToAppend += $("<option/>",
{
'value': item.SERVICE,
'text': item.SERVICE
});
});
$('#service').append(strToAppend);
});
I only came up blank with this code. Does anyone see what I did wrong?
You're on the right track. Don't try to use . for concatentation in JS, though; it's a PHP thing. And .+ doesn't work in either language.
A safer, more jQuery-ish way to do this (it will work when ", ', <, etc. are present in the SERVICE value):
$('<option>').
attr('value', item.SERVICE).
text(item.SERVICE).
appendTo($('#service'));
Paul has the answer above. This is more of an optimization take. Modifying DOM in a loop is costly! it may be okay in this specific question as I only see 2 items. Hence, always construct your string outside of the loop and append all at once when you are ready.
var strToAppend = "";
$.each(data, function(index, item) {
strToAppend += $("<option/>", {
'value': item.SERVICE,
'text': item.SERVICE
});
});
$('#service').append(strToAppend);
Hope that helps :)

JavaScript function undefined from console no visible response

I've got this function in the body of my jQuery Mobile page:
<script>
function theManufacturers(inputSearch){
var qryString = 0;
//set up string for adding <li/>
var li = "";
var jqxhr = $.getJSON("http://someurl.com/page.aspx?sumvar=hello&callback=?",
function(data){
$.each(data.items, function(i,item){
li += '<li>' + item.Manufacturer + '</li>';
});
$("#manufacturer-list").append(li);
$("#manufacturer-list").listview("refresh");
});
//jqxhr.done(function() {
// console.log( "second success" );
//});
};
</script>
I've tried calling it form the console in Firebug and the command just turn blue and then the line underneath in grey says "undefined". And obviously the function doesn't appear to be doing anything.
As pointed out by T.J.Crowder & Bill Crisswell, the undefined response was to be expected and is doesn't actually suggest anything wrong with my JS function.
The actual problem was that I'd copied the code across from another page in the project and hadn't updated the references to the correct listview in my JS. Hence the listview on the page wasn't being populated with the resultant data pulled in by the function.
At least I learned that the undefined console response was the correct output for my JS, and I now know why. Thanks to everyone who pointed this out.

Using jQuery getJSON and fire a function AFTER the results have been processed... should work... but doesn't

I have a series of functions which populate a series of drop down boxes.
This is a product data page, and serves both to add a new item, or edit an existing one. In the latter case, once all the drop down boxes are populated, it grabs an item data from a database as a JSON string and selects the appropriate values in the drop down bozes using $('#elem').val('value')
This all works fine, except I can't get it to things in the right order.
1. function loadBrands() {
2. $('#brand').empty().append('<option value="">Select...</option>').addClass('centreLoader');
3. $.getJSON('/jsonData/brands.txt', function (data) {
4. $.each(data, function (i, item) {
5. $('#brand').append('<option value="' + data[i].label + '">' + data[i].brandName+ '</option>');
6. });
7. $('#brand').removeClass('centreLoader');
8. loadSavedItem();
9. });
10. };
I've added line numbers to explain simply (although you'll all know what this does!)
Line 3 gets the JSON data from my file (this is valid data as it populates fine), then line 4 begins looping the data returned and populating the drop down.
Line 8 is where things go wrong, this calls the function loadSavedItem which looks a bit like this:
1. function loadSavedItem(thisItemId) {
2. $.getJSON('/jsonData/QUERY_DB_FOR_THIS_PRODUCT (thisItemId)', function (data) {
3. $('#brand').val(data[0].brand);
4. });
5. };
Again, pretty simple, line 2 gets the JSON output (which is again valid, it populates other fields fine) and sets the field values as applicable (this is obviously a shortened version of the code)
The problem appears to be that loadSavedItem() is being called too soon, before #brands is fully populated, so it cannot set the value correctly. If I put a time delay in, then it works.
BUT... I thought that anything after the $(each... jQuery statement should not happen until $(each) has finished?
How can I ensure that this is the case?
In my experience, $(each) can loop while the rest of the script is running, if that makes sense (in Chrome, at least). Maybe it's something to do with "optimisation".
I've solved this problem before by checking data.length, setting a counter that increments by one and then firing the code off if the counter equals the length.
function loadBrands() {
$('#brand').empty().append('<option value="">Select...</option>').addClass('centreLoader');
$.getJSON('/jsonData/brands.txt', function (data) {
var dataNum = data.length;
var counter = 1;
$.each(data, function (i, item) {
$('#brand').append('<option value="' + data[i].label + '">' + data[i].brandName+ '</option>');
if (dataNum == counter) {
$('#brand').removeClass('centreLoader');
loadSavedItem();
}
counter ++;
});
});
}
My suggestion would be to add the method "loadSavedItem()" in the Success function something like below. This should solve the problem.
$.ajax({
url: url,
dataType: 'json',
async: true,
data: myData,
success: function(data) { // loadSavedItem(); }
});
Hope this Helps!!
I believe the clue is async setting for jQuery.ajax().
http://api.jquery.com/jQuery.ajax/

Value of html from jquery get

I want to retrieve the value of a text field on a another page on my website (prices.html)
Using http://api.jquery.com/jQuery.get/, how can I accomplish this?
How can I do this?
var price = $('input:price').val(); <- the value of price from prices.html (i'm not on this page so i need to request it)
How can I do this?
Thanks in advance.
You could try .load().
.load('price.html input[name="price"]', function(data) {
alert(data);
});
I didn't try it out myself, but it should work.
One of the last examples on the jQuery get page provides you a clue:
$.get("test.cgi", { name: "John", time: "2pm" },
function(data){
alert("Data Loaded: " + data);
});
Assuming that you get your page correctly, you should get a data payload, which you can then parse to get the price information that you're looking for. Using another example, if you have your data processed as JSON, you can extract data like so:
$.get("test.php",
function(data){
$('body').append( "Name: " + data.name ) // John
.append( "Time: " + data.time ); // 2pm
}, "json");
Without more information, it'll be hard to put together a working example.
Before you live prices.html page, will be good to store/transfer (post/get) input:price in hidden textfield in new page and than read hidden textfield with jquery

need direction regarding jquery and json

I have this url which is JSON webservice
http://ws.geonames.org/weatherJSON?north=90&south=-9.9&east=-22.4&west=55.2
I need to write a jquery function to access the JSON object from the above url.
I am not sure how to proceed with this task. Could someone help me out with starting out the jquery code?
Thanks
Inorder that the HTML appear I removed the "<" for each tag.
What I tried doing below is iterate over the items returned via the JSON object. However, I don't seem to get any result. Could some one point out my error in this regard.
body>
div id="para">
/div>
script>
$.getJSON('http://ws.geonames.org/weatherJSON?north=90&south=-9.9&east=-22.4&west=55.2',function(data) {
$.each(data.weatherObservations, function(i,item){
$("<p/>").attr("src", item.temperature).appendTo("#para");
if ( i == 3 ) return false;
});
});
/script>
/body>
Thank you.
Hi,
I now need to access another web service. I typed out the code on the exact same lines as above but I don't get any output. Could some one help in pointing my mistake?
jQuery(document).ready(function() {
var url = 'http://www.worldweatheronline.com/feed/weather.ashx?q=75080&format=json&num_of_days=5&key=ac9c073a8e025308101307';
jQuery.getJSON(url, function(data) {
$.each(data.data.weather, function(i, item){
$("body").append("<p>"+item.date+"</p>");
if ( i == 3 ) return false;
});
});
});
Thanks!
It should be as easy as this:
<script type="text/javascript">
jQuery.getJSON('http://ws.geonames.org/weatherJSON?north=90&south=-9.9&east=-22.4&west=55.2', function(data) {
// The JSON object is now in the data variable --
// process it here; for example:
alert(data.weatherObservations[0].clouds);
});
</script>
Keep in mind, however, that your AJAX call must come from the same domain (ws.geonames.org), since most modern browsers do not allow cross-domain requests. The workaround is to use the JSON-P format instead of pure JSON.
... In response to rookie's edits to his original question, here is a more complete solution:
<html><head></head><body>
<div id="para"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
jQuery.getJSON('http://ws.geonames.org/weatherJSON?north=90&south=-9.9&east=-22.4&west=55.2', function(data) {
jQuery.each(data.weatherObservations, function(i,item){
jQuery("<p/>").html(item.temperature).appendTo("#para");
});
});
</script>
</body></html>
To help you read the content that's comes back, put it into http://jsbeautifier.org/ and it will format it so it is readable.
In addition to Mark's answer, you should verify the textStatus
http://jsfiddle.net/VC5c2/
var url = "http://ws.geonames.org/weatherJSON?north=90&south=-9.9&east=-22.4&west=55.2";
​jQuery.getJSON(url,function(data, textStatus) {
if (textStatus == "success") {
for (idx in data.weatherObservations) {
var wo = data.weatherObservations[idx];
console.log("Temperature at " + wo.stationName + ": " + wo.temperature);
}
}
});​
Searching for jquery json turned up this page first, which seems to be exactly what you need: jQuery.getJSON()

Categories

Resources