I am accessing the media wiki api using javascript and returning a JSON, but when parsing/accessing the returned data and inserting the datastr variable into an existing div, I receive undefined. Here is my script code:
$.getJSON("http://bulbapedia.bulbagarden.net/w/api.php?action=parse&format=json&page=Bulbasaur_%28Pok%C3%A9mon%29&prop=images", function(data) {
var datax = $.parseJSON(data);
var datastr = datax.images[2];
console.log(datastr); //prints nothing to the web console
});
The link itself is working appropriately I believe, returning a JSON:
http://bulbapedia.bulbagarden.net/w/api.php?action=parse&format=json&page=Bulbasaur_%28Pok%C3%A9mon%29&prop=images
This may be a problem with either the way I am accessing the API, or just receiving/parsing the JSON.Ultimately, I need the image "001Bulbasaur.png". Thanks!
**Changing datax.images[2] to datax.parse.images[2] returns the same undefined.
Change
var datastr = datax.images[2];
To:
var datastr = datax.parse.images[2];
Update: Seems you are having cross-origin problems, its not making the request. This should work:
$.ajax({
dataType: "jsonp",
url: "http://bulbapedia.bulbagarden.net/w/api.php?action=parse&format=json&page=Bulbasaur_%28Pok%C3%A9mon%29&prop=images",
success: success
});
function success(datax){
var datastr = datax.parse.images[2];
console.log(datastr); //prints 001Bulbasaur.png
}
Fiddle: http://jsfiddle.net/mRU3M/
Related
I'm making a function to get a xml file and edit it. I've never done that before so I searched a good way to get an xml file. I decided to use ajax, but the file is never returned because the url is undefined.
EDIT :
I edited the code and made the treatment in the success function. Now there is no problem with this file.
Here is the update of the ajax part :
$.ajax({
type: 'GET',
url: 'allrtp.xml',
dataType: 'xml',
success: function(xml) {
//file = $.parseXML(xml);
// Editing the file to have the good dates
$(xml).find('StartDateTime').text(start);
$(xml).find('EndDateTime').text(end);
var strFile;
if (window.ActiveXObject) {
strFile = xml.xml;
} else {
strFile = (new XMLSerializer()).serializeToString(xml);
}
var encoded64 = Base64.encode(strFile); // Encoded in base64
var encodeURL = encodeURIComponent(encoded64); // Encoded URL
var AR = urlAR + encodeURL; // The URL to open
window.open(AR, '_blank');
}
})
Now all is working well about the xml file, I have a little problem with the window.open, which open my url but with %31 at the beggining, but it's another problem.
Thank you for your help !
file is undefined because you are declaring it inside a ajax success function
function openRecords(start, end) {
// Extraction of the xml file
var file;
$.ajax({
type: 'GET',
url: 'allrtp.xml',
dataType: 'xml',
success: function(xml) {
file = $.parseXML(xml);
},
error: function(ex) {
console.log(ex);
}
})
// Test
var start = '2016-02-15T12:57:00+01:00';
var end = '2019-02-16T13:57:00+01:00';
setTimeout(function(){
// Editing the file to have the good dates
file.find('StartDateTime').text(start);
file.find('EndDateTime').text(end);},1500);
}
Add an error callback:
error: function (ex) {}
Many things can be happening, you will get more info with the error callback. Probably you are querying an incorrect url. Do not trust that undefined upon url, see what returns your jquery ajax function. Maybe you should be querying something like '\files\xxx.xml'.
can you give me a picture of Network in your broswer? I want to know the URL is send or not:
1. F12 open your console
2. select the Network tab
3. refresh the broswer
4. check the request is send or not
Challenge:
While on URL1(random wikipedia page), make an ajax request to URL2(100 most common words wikipedia page), format a list out of the returned data to be used later.
I have to run this from the console while on "URL1"
example:
Navigate to URL1
Open Console
paste code
hit enter
So far I have been able to grab the entire html source while on URL1 with the following:
$.ajax({
url: 'https://en.wikipedia.org/wiki/Most_common_words_in_English',
type: 'GET',
dataType: 'html',
success: function (response) {
console.log(response); // works as expected (returns all html)
}
});
I can see in the console the entire HTML source -- I then went to URL2 to figure out how to grab and format what I needed, which I was able to do with:
var array = $.map($('.wikitable tr'),function(val,i){
var obj = {};
obj[$(val).find('td:first').text()] = $(val).find('td:last').text();
return obj;
});
console.log(JSON.stringify(array));
Now this is where my issue is -- combining the two
$.ajax({
url:'https://en.wikipedia.org/wiki/Most_common_words_in_English',
type:'GET',
dataType:'html',
success: function(data){
// returns correct table data from URL2 while on URL2 -- issue while running from URL1
var array = $.map($('.wikitable tr'),function(val,i){
var obj = {};
obj[$(val).find('td:first').text()] = $(val).find('td:last').text();
return obj;
});
console.log(JSON.stringify(array));
};
});
Im guessing this is due to the HTML I want to map is now a string, and my array is looking for HTML elements on the current page which it of course would not find.
Thanks
Simple fix here! You're exactly right, it's not parsing the html you return, so just tell jQuery to convert it into an object it can use $(data) and use that to find what you need.
In essence, your 'document' now becomes $(data) which you will use as the source of all your queries.
$.ajax({
url: 'https://en.wikipedia.org/wiki/Most_common_words_in_English',
type: 'GET',
dataType: 'html',
success: function(data) {
var myVar = data;
Names = $.map($(myVar).find('.wikitable tr'), function(el, index) {
return $(el).find('td:last').text()
});
console.log(Names);
}
});
I got some code off a tutorial a couple of months ago that I am now changing and using in my site. I have already coded alot so do not want to go another route.
Basically I need to retrieve all posts from a database and display on screen dynamically without refreshing the page. now I have the XML that is generated from the PHP file - all is good. Where I am stuck is reading that XML o the ajax side. here is what I have so far:
function getAllPosts() {
alert('hi');
var count = 0;
var tlu = getUrlVars()["user"]; // tlu stands for time line user
var data = 'user='+tlu;
$.ajax({
url: 'getAllPosts.php',
type: 'POST',
data: data,
success: function(response){
var xml = response.responseXML;
var posts = xml.documentElement.getElementsByTagName("post_item");
for (var i = 0; i < posts.length; i++) {
var id = posts[i].getAttribute("id");
var account_name = posts[i].getAttribute("account_name");
var author = posts[i].getAttribute("author");
var type = posts[i].getAttribute("type");
var data = posts[i].getAttribute("data");
var postdate = posts[i].getAttribute("post_date");
categoryPost(id, account_name, author, type, data, postdate);
}
}
});
}
function categoryPost(id, account_name, author, type, data, pastdate){
if(type === 'write'){
alert("hello");
}
}
It is running the alert("hi"); test but not the rest of the code.
My console gives me this: Uncaught TypeError: Cannot read property 'documentElement' of undefined
How can I read the elements from the xml? Everywhere I look has that XMLHTTP stuff and I don't, so I am pretty confused...
Thanks in Advance
If you are expecting an XML response, try setting data type: 'xml'. In your $.ajax parameters. If you're still having issues. Log the response object by using console.log(response) to examine what is actually being returned or you can use Chrome's postman extension. Comes in handy ;-).
I'm trying to send JSON data to my web server via jQuery and I'm running into an error.
Uncaught TypeError: Cannot use 'in' operator to search for 'context' in {"id":45,"isRead":true}
code I am testing:
var obj = {};
obj.id = 45;
obj.isRead = true;
var data = JSON.stringify(obj);
var url = "/notification/read"
$.ajax(url, data, 'application/json', function() {
// code remove notification from the DOM
});
});
Is there a better or more correct way to do this? Not sure if I'm getting the params right on the $.ajax call either.
UPDATE
code I got to work
var obj = {
id: 45,
isRead: true
};
var json = JSON.stringify(obj);
var url = "/notification/read"
$.ajax({ url: url,
type:'POST',
contentType: 'application/json',
data: json,
success: function(data, textStatus) {
// do stuff
}
});
My server was expecting JSON data POSTed as application/json. So was I wrong in thinking I needed all these variables? without these it was sent as a GET and was application/x-www-form-urlencoded. Without the stringify it also didn't work.
You are passing too many arguments to the ajax function: http://api.jquery.com/jQuery.ajax/
Also, the JSON.stringify call is not necessary, jQuery will take care of that for you.
var obj = {
'id':45,
'isRead':true
};
$.ajax({
url: "/notification/read",
data: obj,
success: function(data, textStatus){
/* code here */
}
});
$.ajax(url, obj);
You need to send an object as second param
{success: success, data: data}
Documentation is here:
http://api.jquery.com/jQuery.ajax/
You have to pass parameters as one object, not multiple ones
I want to pass a javascript array to a php page using ajax POST request .How to achieve this.please help..Thanks in advance
Have a look into JSON encoding.
In PHP you can decode it using json_decode, not quite sure how you'll encode it in Javascript but it is possible
http://en.wikipedia.org/wiki/JSON
using jQuery
$.post("test.php", { 'choices[]': ["Jon", "Susan"] });
Edit
if you are creating ajax object and using it then I'll suggest to convert your data in query string send it through ajax object.
like :
var userdetails = [1,2,3,4];
var queryString = "";
for(i=0; i<userdetails.length; i++){
queryString = queryString + 'userdetails[]='+userdetails[i]+'&';
}
connect.send(queryString)
example posting with json
var array = [1,2,3,4,5,6];
$.ajax({
url: "mydomain.com/url",
type: "POST",
dataType: "json",
data: {arrayName: array},
complete: function() {
//called when complete
},
success: function() {
//called when successful
},
error: function() {
//called when there is an error
},
});
Then the json could be parsed server side.
arrays can also be sent using application/x-www-form-urlencoded - this is the default format for submitting.