Get random Wikipedia extract with Ajax - javascript

I'm trying to get the extract of a random Wikipedia page using Ajax. I've got as far as getting the data, but I'm having trouble outputting it.
Here's my code:
$.ajax({
type: "GET",
url: "https://simple.wikipedia.org/w/api.php?action=query&generator=random&grnnamespace=0&prop=extracts&exsentences=10&format=json&callback=?",
contentType: "application/json; charset=utf-8",
async: false,
dataType: "json",
success: function (data) {
console.log(data);
var text = data.parse;
document.getElementById('div_text').innerHTML = text;
},
error: function (errorMessage) {
}
});
The console logs the data fine, but the output in the browser is simply undefined.
Clearly, the problem is this line:
var text = data.parse;
Where am I going wrong?

The data is not in data.parse but in data.query.pages and in there the first object.
So change you success method to
success: function (data) {
var pages = data.query.pages;
var text = pages[ Object.keys(pages)[0] ].extract;
document.getElementById('div_text').innerHTML = text;
}

Related

Cant browse through Dictionary in Javascript

I am using Ajax to send data and as a success, it sends some data back.
$.ajax({
method: "POST",
url: "{% url 'upload-prop-images' %}",
processData: false,
contentType: false,
mimeType: "multipart/form-data",
data: fileData,
success: function (data) {
console.log(data);
console.log(data.newCard);
console.log(data.newCard.prop_name);
}
}
})
views.py :
def uploadPropImages(request):
prop_obj = list(Property.objects.filter(user=request.user).values())
new_card = {}
for obj in prop_obj:
if obj['prop_name'] == prop_name:
new_card['prop_name'] = obj['prop_name']
new_card['prop_address'] = obj['prop_address']
new_card['prop_type'] = obj['prop_type']
new_card['prop_images'] = '/media/' + obj['prop_images']
return JsonResponse({'status': 'Done', 'newCard': new_card})
In the first code block where success: function(data) {}, console.log(data) prints the data I am sending, that is {'status': 'Done', 'newCard': new_card}, but when I print, console.log(data.status) or console.log(data.newCard), I get undefined value. I cant understand why it prints undefined because I used AJAX may times earlier and It seem to work. It is how we can browser through the value of a dictionary in JAVASCRIPT, which in PYTHON is print(data['status']). Is the error anything related to the keys defined inside the AJAX function: processData, mimeType, contentType?
you need to call this
$.parseJSON();
Like this
success: function (response) {
var data= $.parseJSON(response);
console.log(data);
console.log(data.newCard);
console.log(data.newCard.prop_name);
}

Ajax code working in some parts and not working in others

I have a problem with my Ajax request to download some data from a database.
There are two codes down below: one that works and one that doesn't, even though they are basically the same. I've also set up later down my code to display the variable (console.log(location)) but it just reads undefined.
I know the php part of it is working because I also do another console.log(data) on success of the ajax call and that returns with the data I entered on my database. What's going on and how do I fix it?
Code that doesn't work:
var location;
function downloadCoords() {
$.ajax({
type: 'GET',
url: 'transformerthing.php',
dataType: "json",
success: function(data) {
console.log(data);
location = data.location;
},
error: function(data) {
console.log(data);
}
});
}
Code that does work:
var mapCode;
var used;
var active;
function downloadCode() {
$.ajax({
type: 'GET',
url: 'getMapCode.php',
dataType: "json",
success: function(data) {
console.log(data);
mapCode = data.mapCode;
used = data.used;
active = data.active;
},
error: function(data) {
console.log(data);
}
});
}
//shorthand deferred way
$.getJSON( "transformerthing.php")
.done(function(data){
console.log(data);
}).fail(function(msg){
console.log(msg)
});
var location;
function downloadCoords() {
$.ajax({
type: 'GET',
url: 'transformerthing.php',
dataType: "json",
success: function(data) {
console.log(data);
location = data.location;
console.log(location);
},
error: function(data) {
console.log(data);
}
});
}
Try it again.

Jquery ajax call works when applied breakpoint to ajax call else it show no result

I have the following ajax call to web service in asp.net.When I simply run the program, it won't work. In console, it shows
'http://mywebservice.asmx/add' in red color for a second and dissapear.
function btn_add1()
{
var aData = [];
aData[0] = $("#tb_a").val();
aData[1] = $("#tb_b").val();
aData[2] = $("#tb_c").val();
var jsonData = JSON.stringify({ aData: aData });
$.ajax({
type: "POST",
url: "mywebservice.asmx/add",
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json", // dataType is json format
cache:false,
success: OnSuccess,
error: OnErrorCall
});
function OnSuccess(response) {
alert("success");
alert(response.d);
console.log(response.d);
}
function OnErrorCall(response) {
console.log(response.d);
}
}
But when I apply breakpoint and run the program it gives the desired result.
I am really confused and frustrated by this behavior.
Here's my webservice code
[WebMethod, ScriptMethod]
public int add(List<string> aData)
{
int cal = Convert.ToInt32(aData[0]) + Convert.ToInt32(aData[1]) + Convert.ToInt32(aData[2]);
return cal;
}

Ajax on success of another ajax doesn't work in ie

I do an ajax call to get a list of all elements, say Products and populate them in a table with checkboxes. Then I make another ajax call to get which products were already selected and select them. This works in all browsers except ie. Am I doing something wrong?
$.ajax({
url : "${product_category_url}",
data : {"orgID":"${globalOrganisation.id}"},
dataType : "html",
statusCode: {
401: function() {
$('.ui-tabs-panel:visible').html("${ajax_session_expired}");
}
},
success : function(data) {
$("#productCategoryContainer").html(data);
$.ajax({
url: "${get_taggedProd_url}",
data: {"questionnaireId":_questionnaireId},
dataType: "json",
success: function(data){
var productIds = data.products;
$.each(productIds,function(index,value){
var obj = $('input[name="'+value+'"]');
obj[0].checked = true
selectRow(obj[0]);
});
}
});
}
});
This is due to caching by IE.
Please try this
$.ajax({
url : "${product_category_url}",
data : {"orgID":"${globalOrganisation.id}"},
dataType : "html",
statusCode: {
401: function() {
$('.ui-tabs-panel:visible').html("${ajax_session_expired}");
}
},
success : function(data) {
$("#productCategoryContainer").html(data);
$.ajaxSetup ({
// Disable caching of AJAX responses
cache: false
});
$.ajax({
url: "${get_taggedProd_url}",
data: {"questionnaireId":_questionnaireId},
dataType: "json",
success: function(data){
var productIds = data.products;
$.each(productIds,function(index,value){
var obj = $('input[name="'+value+'"]');
obj[0].checked = true
selectRow(obj[0]);
});
}
});
}
});
and if you need more details please look into this
The thing in this code that always screws me up is trying to get the check box selected. Make sure obj[0].checked = true actually works.

Can't query JSON using jQuery

I'm using jQuery to grab some JSON data. I've stored it in a variable called "ajaxResponse". I cant pull data points out of it; I'm getting ajaxResponse.blah is not defined. typeof is a string. Thought it should be an object.
var getData = function (url) {
var ajaxResponse = "";
$.ajax({
url: url,
type: "post",
async: false,
success: function (data) {
ajaxResponse = data;
}
});
return ajaxResponse;
},
...
typeof ajaxResponse; // string
ajaxResponse.blah[0].name // ajaxResponse.blah is not defined
make sure you specify option dataType = json
$.ajax({
url: url,
type: "post",
dataType: "json",
async: false,
success: function (data) {
ajaxResponse = data;
}
});
Q8-coder has the right of it, but to give you some details: your server is really passing back a string that you've formatted into JSON. You'll need to tell jQuery what to expect, otherwise it just assumes it received a string.
Add the following to your $.ajax options:
dataType: "json"
Also, refer to the jQuery API for examples and documentation for these options.

Categories