Grabbing title of page from an API is alerting undefined? - javascript

This bit of code below scans an API on Wikipedia, and then is supposed to alert the title of it by getting the JSON property "title". However, it just alerts undefined, and for some reason, it alerts it twice. What am I doing wrong?
$.get('https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=Twitter', function(data){
for (var Object in data){
var Info = data[Object]
var Title = Info["title"]
alert(Title)
}
})

This will work:
$.get('https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=Twitter', function(data) {
$.each(data.query.pages, function( index, value ) {
var title = value.title;
alert(title);
});
})
The query returns a data object, which has a query object within it, and one/multiple pages within that. Iterate over each page, and grab the title string.
JSFiddle
Note: You may want to learn to use your browser's debugging tools, and read up on the JSON format.

Related

How do I serialize a parameter incoming from my controller?

So I am sending a list of objects from my ASP.NET MVC controller back to my ajax success response:
...
success: function (data) {
var predefinedData = data.serialize();
...
When I debug from browser, I see that the data parameter is reading as an array, which is ok, but the following error occurs:
Uncaught TypeError: data.serialize is not a function
I've read that I have to convert the "vanilla" parameter into jQuery so I did the following:
var makeJqueryArray = $.makeArray(data) //this passes ok
var predefinedData = $.param(makeJqueryArray).serialize(); //but then this reports the same error as before
Upon further inspection I see that $.makeArray(data) literally doesn't do anything since it stays exactly the same as before, an array with n number of elements.
Doing JSON.stringify(data); works however, but it is out of the question since that gives me a completely different format than what I need here.
So does anyone have any suggestions?
EDIT 1:
So here is the data I am receiving (as seen from the browser debugger watch):
data: Array[3]
0:Object
_int:false
avg:false
max:false
min:false
sensorID:5
sum:false
val:true
__proto__: Object
1:Object
2:Object
length:3
__proto__:Array[0]
And here is how i want to format it (the values don't match because I'm using different samples, but you get the point):
"SensorID=1&val=false&min=false&avg=false&max=false&sum=false&_int=false&SensorID=2&val=false&min=false&avg=false&max=false&sum=false&_int=false&SensorID=3&val=false&min=false&avg=false&max=false&sum=false&_int=false&SensorID=4&val=true&val=false&min=true&min=false&avg=true&avg=false&max=true&max=false&sum=true&sum=false&_int=true&_int=false&SensorID=5&val=true&val=false&min=true&min=false&avg=true&avg=false&max=true&max=false&sum=true&sum=false&_int=true&_int=false&SensorID=6&val=false&min=false&avg=false&max=false&sum=false&_int=false&SensorID=7&val=false&min=false&avg=false&max=false&sum=false&_int=false&SensorID=9&val=false&min=false&avg=false&max=false&sum=false&_int=false"
If you have an array and you want to make a request where the parameters are the key-value pairs of it, you can use simply $.param(yourArray);.
It will return a string ready to be used in your URL.
For example (taken from the jQuery.param page) :
var params = { width:1680, height:1050 };
var str = jQuery.param( params ); // str = "width=1680&height=1050"
This should the same in your case. So, try this :
var makeJqueryArray = $.makeArray(data) //this passes ok
var finalString = $.param(makeJqueryArray); // Should contain the string you want

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.

Pulling DOM content as jQuery object from $.get()

As part of a jQuery plugin, a strange object format is pulled using $.get(), meaning that DOM traversal isn't possible in any of the post-function hooks:
$.get($href)
.done(function(){
$linkClicked.addClass('active')
})
.fail(function(){
$.get(settings.errorUrl, function(){
$('.main-navigation .active').removeClass('active')
})
})
.always(function(data){
// The below line does not work correctly
$(settings.target).hide().html( $(data).children(settings.target).html() ).fadeIn('fast')
})
If somebody could lend a hand, that'd be great. Many thanks.
I guess you can do like this:
$.get('ajax/test.html', function(data) {
var container = $('<div />').html(data);
var contentYouNeed = container.find('#ajaxID').html();
});
As you can see on the document here (
http://api.jquery.com/jQuery.get/), The returned data by
jQuery.get() is a PlainObject or a String.
data
Type: PlainObject or String
A plain object or string that is sent to the server with the request.
To retrieve the contents from this object, you put this data in a <div> object like this.
var container = $('<div />').html(data);
And you can use find() to get the content.
var contentYouNeed = container.find('#ajaxID').html();
No no no no. You don't use regex for parsing HTML please read this.
Also, to solve you problem use jQuery selectors: $("#yourID").html()
So the response is always one div element? In that case it's just a matter of grabbing the contents of it. No matter what the ID and attributes are.
$.get('ajax/call.php', function(data) {
var contents = $(data).html();
});

how do you parse out the output of script javascript

I am having a difficult time figuring out a javascript problem. I have script that I does an ajax call via a php script get data. This data is in this format "[12300000,13]"
when I do alert on data, I will exactly get that. I am interested in the values inside the bracket. So this is what I did:
var myObj = JSON.parse(data);
var temp = new Array();
temp=myObj.split(',');
when I try to do this;
alert(temp[0]);
I dont get anything back. Is there an easy way to do this in javascript. My whole script is below:
$.ajax({
url: 'get_data.php',
success: function(data) {
//when I do alert(data), I will get this format [123000000,45]//
var myObj = JSON.parse(data);
alert(myObj);//this will display this without the brackets123000000,45
//but when I do this
var temp = new Array();
temp=myObj.split(',');
alert(temp[0]); //does not return anything
},
cache: false
});
}
myObj is an array; JSON.parse will parse JSON into the corresponding Javascript objects.
You don't need to do anything
You already parsed the string into an array. Just get the first element:
> var arr = JSON.parse("[12300000,13]")
> arr[0]
12300000
Your problem here is actually alert(). Don't use it as a debugging tool. Use console.log() and open up your JS console, which will display objects in a friendly manner.

backbone model fetch JSON element by ID

I am using backbone for the first time and I am really struggling to get it to function correctly with a JSON data file.
I have a model Like so:
window.Test = Backbone.Model.extend({
defaults: {
id: null,
name: null,
},
url: function() {
return 'json/test.json/this.id';
},
initialize: function(){
}
});
When a test item is clicked I then try to bring up the details of the pacific model that was clicked by doing
testDetails: function (id) {
var test = new Test();
test.id = id;
test.fetch({ success: function(data) { alert(JSON.stringify(data))}});
},
However this does not work, I am unable to correctly say "get the JSON element with the passed ID"
Can anyone please show me how to correctly structure the models URL to pull the element with the ID.
Thanks
The problem here is that you're treating your JSON data file like a call to a server. That won't work and it's the reason you're getting a 404. If you're accessing a file locally, you have to load the file first. You can do this with jQuery using the .getJSON() method, or if the file's static, just load it into memory with a script block (though you'll probably need to assign a var in the file). Most likely, you'll use jQuery. An example of this can be found here:
Using Jquery to get JSON objects from local file.
If this is an array of JSON, you can load the array into a collection, and use the "at" method to access the particular element by id. If it's entirely JSON, you'll have to create a custom parser.
your url is incorrect for one. you are returning the literal string 'this.id'. you probably want to do something more along the lines of
url: function () {
return 'json/test.json/' + this.id;
}
I would start by fixing your url function:
url: function() {
return 'json/test.json/' + this.get('id');
}
The way you have it now, every fetch request, regardless of the model's id, is going to /json/test.json/test.id

Categories

Resources