Let suppose i have a json file
and i can read this file in my script like this
$(document).ready(function () {
$.ajax({
type: "GET",
url: "Package.html",
dataType: "json",
success: function (data) {
var t = '';
for (var i = 0; i < data.yearData.length; i++) {
var mainStoryTitle = data.yearData[i].players;
for (var j = 0; j < mainStoryTitle.length; j++) {
var storyTitle = mainStoryTitle[j].name;
var topStoryContent = mainStoryTitle[j].description;
var storyImage = mainStoryTitle[j].image;
t = t + '<div class="content">';
t = t + '<article class="topcontent">';
t = t + '<header class="top" id="top1"><h2>' + storyTitle + '</h2></header>';
t = t + '<header class="bottom">';
t = t + '<h6><img src="' + storyImage + '" height=150 width=200>' + '</h6></header>';
t = t + '<content class="hide" id="content_' + j + '"><p>' + topStoryContent + '</p></content>';
t = t + '</article>';
t = t + '</div>';
}
}
$(".content").html(t);
},
error: function (e, ts, et) { alert(ts) }
})
});
and then i put this script in my html file.
So when i run this, it works properly but the problem is when i click on view source then inside it shows the path of json instead of exact data.
Hope you got the problem and please revert me asap.thanx
Instead of using alert, use console.log(ts) this will post the JSON file into your console. From there you can easily look around and see the JSON file by clicking the down arrow.
console.log(data); shows as:
> Object {Data: Array[2], ResponseMessage: "", Success: true}
console.log(JSON.stringify(data)); shows as:
{"Data":[{"ControllerID":2,"Description":"Aeon Power Monitor","DevType":1,"ID":1,"Name":"Power Monitor"},{"ControllerID":2,"Description":"Aeon Power Switch","DevType":2,"ID":2,"Name":"Switch"}],"ResponseMessage":"","Success":true}
Related
I hope you are fine!
I'm new in coding so I'm facing of something without results.
I have this type of code here in JS.
key: 'generateChart2',
value: function generateChart2() {
var self = this;
var Jahr1 = [];
var years1 = "";
for (var i = 0; i < $('#mf123_select_jahr').val().length; i++) {
if (i > 0) years1 += ","
years1 += $('#mf123_select_jahr').val()[i];
}
var postedData1 = {};
postedData1.years1 = years1;
console.log(postedData1);
$.ajax({
url: "data/json.dashboard.php?call=chart2",
data: postedData1,
dataType: 'json',
type: 'POST',
success: function (dataGraph2) {
var trHTML='';
$.each(dataGraph2, function (key, value) {
for (var i in postedData1) {
Jahr1.push(postedData1[i].years1);
}
console.log(postedData1.years1);
trHTML +=
'<tr><td >' + value.Mandant +
'</td><td >' + thousandSepNeu(value.Jahr1, 2) + " €" +
'</td><td >' + value.Growth +
'</td></tr>';
});
$('#dataGraph2').append(trHTML);
}
});
}
The value.Mandant and the value.Growth are doing well. The problem that I have is that the for loop does not work. I need to thr postedData1 to choose whenever the user choose the year to show him the results.
The output of console.log(postedData1); is:
Am I making a mistake? I know that the problem is on the for loop.
Please any advice i would appreciate it.
:)
I'm trying to iterate a nested API response and display them inside a html. I managed to do single image because the response only have single value.
**API response **
{"result":{"totalResults":5861511,"products":[{"productTitle":"S-XL Plus Size Tunic Autumn <font><b>Women</b></font> Dresses Casual Cartoon Print Christmas Dress Casual Loose Long Sleeve Party Dress Vestidos","originalPrice":"US $7.98","imageUrl":"https://ae01.alicdn.com/kf/H3ba2899c892d4a88a5f704453c39942ae/S-XL-Plus-Size-Tunic-Autumn-font-b-Women-b-font-Dresses-Casual-Cartoon-Print-Christmas.jpg","productUrl":"https://www.aliexpress.com/item/S-XL-Plus-Size-Tunic-Autumn-Women-Dresses-Casual-Cartoon-Print-Christmas-Dress-Casual-Loose-Long/4000353066650.html","allImageUrls":"https://ae01.alicdn.com/kf/H3ba2899c892d4a88a5f704453c39942ae/S-XL-Plus-Size-Tunic-Autumn-font-b-Women-b-font-Dresses-Casual-Cartoon-Print-Christmas.jpg,https://ae01.alicdn.com/kf/H218b19ee8bfc4f6ebe74b4297ca8395f5/S-XL-Plus-Size-Tunic-Autumn-font-b-Women-b-font-Dresses-Casual-Cartoon-Print-Christmas.jpg,https://ae01.alicdn.com/kf/H14b48746d6eb4d5788a7a9f6ce37195c7/S-XL-Plus-Size-Tunic-Autumn-font-b-Women-b-font-Dresses-Casual-Cartoon-Print-Christmas.jpg,https://ae01.alicdn.com/kf/Hb4b1f8b6223d4e7c88208751bfa681886/S-XL-Plus-Size-Tunic-Autumn-font-b-Women-b-font-Dresses-Casual-Cartoon-Print-Christmas.jpg,https://ae01.alicdn.com/kf/Hcfd17f95ac85470d9550d13f3683adc1I/S-XL-Plus-Size-Tunic-Autumn-font-b-Women-b-font-Dresses-Casual-Cartoon-Print-Christmas.jpg}]},"errorCode":20010000,"currentPageNum":0,"totalPageNum":0}
main.js
$(function (){
var $orders = $('#orders');
var $productimage = $('#productimage');
var $output = $('#output');
$.ajax({
type: 'GET',
url: 'http://gw.api.alibaba.com/openapi/param2/2/portals.open/api.listPromotionProduct/9420?fields=productUrl,allImageUrls,imageUrl,originalPrice,productTitle&keywords=women',
success: function(orders){
$.each(orders, function(i, order){
$orders.append('' + order.products[0].productTitle + '');
$output.append(order.products[0].allImageUrls[1]);
// $productimage.append('<img class="pic-1" src="' + order.products[0].imageUrl + '">'); // single image
});
}
});
});
Result generated
"t"
How do you create a loop for $output from allImageUrls ?
You need to split the allImageUrls and then run them in a loop as follows:
var result ={
"result": {
"totalResults": 5861511,
"products": [
{
"productTitle": "S-XL Plus Size Tunic Autumn <font><b>Women</b></font> Dresses Casual Cartoon Print Christmas Dress Casual Loose Long Sleeve Party Dress Vestidos",
"originalPrice": "US $7.98",
"imageUrl": "https://ae01.alicdn.com/kf/H3ba2899c892d4a88a5f704453c39942ae/S-XL-Plus-Size-Tunic-Autumn-font-b-Women-b-font-Dresses-Casual-Cartoon-Print-Christmas.jpg",
"productUrl": "https://www.aliexpress.com/item/S-XL-Plus-Size-Tunic-Autumn-Women-Dresses-Casual-Cartoon-Print-Christmas-Dress-Casual-Loose-Long/4000353066650.html",
"allImageUrls": "https://ae01.alicdn.com/kf/H3ba2899c892d4a88a5f704453c39942ae/S-XL-Plus-Size-Tunic-Autumn-font-b-Women-b-font-Dresses-Casual-Cartoon-Print-Christmas.jpg,https://ae01.alicdn.com/kf/H218b19ee8bfc4f6ebe74b4297ca8395f5/S-XL-Plus-Size-Tunic-Autumn-font-b-Women-b-font-Dresses-Casual-Cartoon-Print-Christmas.jpg,https://ae01.alicdn.com/kf/H14b48746d6eb4d5788a7a9f6ce37195c7/S-XL-Plus-Size-Tunic-Autumn-font-b-Women-b-font-Dresses-Casual-Cartoon-Print-Christmas.jpg,https://ae01.alicdn.com/kf/Hb4b1f8b6223d4e7c88208751bfa681886/S-XL-Plus-Size-Tunic-Autumn-font-b-Women-b-font-Dresses-Casual-Cartoon-Print-Christmas.jpg,https://ae01.alicdn.com/kf/Hcfd17f95ac85470d9550d13f3683adc1I/S-XL-Plus-Size-Tunic-Autumn-font-b-Women-b-font-Dresses-Casual-Cartoon-Print-Christmas.jpg"
}
]
},
"errorCode": 20010000,
"currentPageNum": 0,
"totalPageNum": 0
}
var allImagesList = result.result.products[0].allImageUrls.split(',');
allImagesList.forEach((imageUrl)=>{
console.log(imageUrl);
})
And your code will look like something as below:
$(function (){
var $orders = $('#orders');
var $productimage = $('#productimage');
var $output = $('#output');
$.ajax({
type: 'GET',
url: 'http://gw.api.alibaba.com/openapi/param2/2/portals.open/api.listPromotionProduct/9420?fields=productUrl,allImageUrls,imageUrl,originalPrice,productTitle&keywords=women',
success: function(orders){
$.each(orders, function(i, order){
$orders.append('' + order.products[0].productTitle + '');
$output.append(order.products[0].allImageUrls[1]);
var allImagesList = order.products[0].allImageUrls.split(',');
allImagesList.forEach((imageUrl)=>{
$productimage.append('<img class="pic-1" src="' + imageUrl + '">'); // single image
})
});
}
});
});
$.each(orders, function(i, order) {
$orders.append('' + order.products[0].productTitle + '');
//------------------------Start
var allImageUrlsArray = []; // Create array;
//split with comma, assign to varaible and loop it.
allImageUrlsArray = order.products[0].allImageUrls.split(',');
for (var i = 0; i < allImageUrlsArray.length; i++) {
$output.append(allImageUrlsArray[i]);
}
//---------------------------End
});
You did some mistakes in iterate JSON Object, and allImageUrls contain multiple images with comma(,) so you should convert this into array. Let's check the below example
LN: 21 you can loop the allImageUrls
for([k, v] of Object.entries(value.allImageUrls)){
console.log(k, v);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="orders"></div>
<script>
$(function() {
var $orders = $('#orders');
var $productimage = $('#productimage');
var $output = $('#output');
$.ajax({
type: 'GET',
url: 'https://gw.api.alibaba.com/openapi/param2/2/portals.open/api.listPromotionProduct/9420?fields=productUrl,allImageUrls,imageUrl,originalPrice,productTitle&keywords=women',
success: function(item) {
let orders = item.result.products;
orders = orders.map(product => {
product.allImageUrls = product.allImageUrls.split(',');
return product;
});
var con = '';
for ([key, value] of Object.entries(orders)) {
con += "<li><a href='" + value.productUrl + "'><img style='width: 30px;' src='" + value.allImageUrls[0] + "'/>" + value.productTitle + "</a></li>";
// Loop all images
for ([k, v] of Object.entries(value.allImageUrls)) {
console.log(k, v);
}
}
$orders.append("<ul>" + con + "</ul>");
}
});
});
</script>
$(function() {
var $orders = $('#orders');
var $productimage = $('#productimage');
var $output = $('#output');
$.ajax({
type: 'GET',
url: 'http://gw.api.alibaba.com/openapi/param2/2/portals.open/api.listPromotionProduct/9420?fields=productUrl,allImageUrls,imageUrl,originalPrice,productTitle&keywords=women',
success: function(orders) {
$.each(orders.result.products, function(i, order) {
console.log(order)
$div = $('<div id = "' + "order_" + i + '"></div>');
$imageDiv = $('<div id = "' + "image_" + i + '"></div>');
// = $('#order_' + i);
console.log($div)
$div.append('' + order.productTitle + '');
//;
var array = order.allImageUrls.split(',');
for (var j = 0; j < array.length; j++) {
//$output.append(order.allImageUrls[j]);
$imageDiv.append('<img style="width:50px;height:50px" class="pic-1" src="' + array[j] + '">'); // single image
}
$div.append($imageDiv);
$orders.append($div);
});
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="output">
<div id="orders">
</div>
</div>
Hope this helps. :)
I have a little issue and I don't overcome to solve it. I have a list of Django objects generated in my views.py file and I would like to display these variables in my Javascript part.
I get the list in my Javascript code, but each variable are 'undefined'.
In my views.py file, I have :
context['results2'] = SubMethod.objects.values_list('name', flat=True).all()
with this model :
class SubMethod(EdqmTable):
name = models.CharField(verbose_name=_('name'), max_length=80, unique=True)
def __str__(self):
return self.name
Then, in my HTML/JS part :
function get_sub_method_options(keep_cur) {
var sel_option = $('select#id_method-group').find("option:selected");
var sel_val = sel_option.val();
if (!sel_val) {
$("select#id_method-sub_method").empty();
var all_sub_methods = "{{ results2 }}";
console.log(all_sub_methods.name);
for (var i = 0; i < all_sub_methods.length; i++) {
$("select#id_method-sub_method").append('<option value="' + all_sub_methods[i].id + '">' + all_sub_methods[i].name + '</option>'); //here add list of all submethods
}
return;
}
data = {
'test_method': $('select#id_method-test_method').find("option:selected").val(),
'group': sel_val
};
$.ajax({
method: "GET",
url: '{% url 'ajax_method_submethod' %}',
data: data
}).done(function (result) {
reset_select('id_method-sub_method');
for (var i = 0; i < result['results'].length; i++) {
if (keep_cur > 0 & keep_cur == result['results'][i].id)
$("select#id_method-sub_method").append('<option value="' + result['results'][i].id + '" selected>' + result['results'][i].text + '</option>');
else
$("select#id_method-sub_method").append('<option value="' + result['results'][i].id + '">' + result['results'][i].text + '</option>');
}
;
});
}
As you can see, I pick up my context variable result2 in this part :
if (!sel_val) {
$("select#id_method-sub_method").empty();
var all_sub_methods = "{{ results2 }}";
console.log(all_sub_methods.name);
for (var i = 0; i < all_sub_methods.length; i++) {
$("select#id_method-sub_method").append('<option value="' + all_sub_methods[i].id + '">' + all_sub_methods[i].name + '</option>'); //here add list of all submethods
}
return;
}
In my terminal I get :
<QuerySet ['50% cell culture infective dose (CCID50)', 'Acetic acid in synthetic peptides', 'Acid value', 'Adenylate cyclase', ...]>
But in my Javascript part, it displays this :
Do you have any idea why ?
EDIT :
In my django code, count() displays 450
In my JS code : length display 684
In my database : I have 450 elements
You need to convert your queryset to a list first. JS does not read querysets.
context['results2'] = list(SubMethod.objects.values_list('name', flat=True).all())
and you may want to skip wrapping results2 in quotes on the JS side and ass safe` to prevent escaping characters:
var all_sub_methods = {{ results2|safe }};
This is my response from AJAX call
{"screen":[{"screen_name":"SCR1","screen_id":"1"},{"screen_name":"SCR2","screen_id":"2"},{"screen_name":"SCR3","screen_id":"3"},{"screen_name":"SCR4","screen_id":"4"},{"screen_name":"SCR5","screen_id":"5"},{"screen_name":"BIGSCR","screen_id":"6"}]}
success: function(response) {
var jsondata = JSON.stringify(response);
console.log(jsondata);
var html = '';
for (var i = 0; i < jsondata.screen.length; i++) {
var screenName = jsondata.screen[i].screen_name;
var screenId = jsondata.screen[i].screen_id;
html += '<option value="' + screenName + '">' + screenId + '</option>';
}
$('#SCname').append(html);
}
But I keep on getting
Uncaught TypeError: Cannot read property 'length' of undefined at for loop
Try this: It Works. As smooth as silk: (See comment for explanation)
<select id="SCname"></select>
<script>
$.ajax({
dataType: 'json',
//This JSON datatype returns a json encoded response
url:"api/test.php",
//This is the URL From where you fetch the JSON Data
success: function(response){
//Since the response array object has a single array element "screen", we make it myArray
myArray = response["screen"];
console.log(myArray);
//We get six Objects in myArray.
//Thsese are Arrays of your six screens . Now Using Loops
var html = '';
for (var i = 0; i < myArray.length; i++) {
// Each element is inside DOuble Array like: myArray[0]["screen_name"]
var screenName = myArray[i]["screen_name"];
var screenId = myArray[i]["screen_id"];
html += '<option value="' + screenName + '">' + screenId + '</option>';
}
$('#SCname').append(html);
//Check your console ouput
console.log(html);
}
});
</script>
JSON.stringify(object) returns a string. You want a JSON.parse(string) – which returns an object. Alternatively, if your response is already an object, then you don't have to parse it at all:
success: function(jsonData) {
var html = '';
for (var i = 0; i < jsonData.screen.length; i++) {
var screenName = jsonData.screen[i].screen_name;
var screenId = jsonData.screen[i].screen_id;
html += '<option value="' + screenName + '">' + screenId + '</option>';
}
$('#SCname').append(html);
You don't want to stringifybut to parse. Correct it must be:
var jsondata = JSON.parse(response);
But keep in mind that jQuery possibly is already parsing the JSON for you.
I am new to javascript. I have worked on twitter API. In twitter API i used jQuery.ajax function to get json data from twitter servers. But when i use the same option with google maps server, my app isn't giving any response the moment it enters the jQuery.ajax. I tried to debug it using jslint, but it came out clean. I used debugging using alert, and it stops when it enters jQuery.ajax function. Is meathod to retrieve data varies with the source ?
If not why isn't my code responding ?
Twitter running function ::
var twitterapi = "http://search.twitter.com/search.json?";
jQuery.ajax(
{
type: "GET",
url: twitterapi,
data:
{
"q": hashtag,
"rpp": 1000
},
dataType: 'jsonp'
}).done(function (response)
{
var results = response.results;
for (var i = 0; i < results.length; i++)
{
$("#tweet").prepend("<li class='tweet'>" +
"<img src='" +
results[i].profile_image_url +
"'/>" +
"<span class='username'>" +
results[i].from_user +
"</span> <span class='tweet_content'> " +
results[i].text +
"</span></li>");
}
});
My google maps API(not working)
var j = 2;
var friends = [];
var distance =[];
$(document).ready(function () {
alert("function started");
$('#button').click(function () {
if (j < 11) {
$('#friends').append('Friend' + j + ':<input type="text" id="friend' + j + '"/><br/><br/>');
j++;
}
else {
alert("Limit reached");
}
});
$('button').click(function(){
var a =[];
alert("button clickede");
for(i=1;i<=j;i++)
{
a[i] = $("#friend" + i).val();
}
var gurl = "http://maps.googleapis.com/maps/api/distancematrix/json?"+
"origins=" +
a.join('|').replace(/ /g,'+') +
"&destinations=" +
a.join('|').replace(/ /g,'+') +
"&sensor=false";
alert("making request to" +gurl);
jQuery.ajax(
{
type: "GET",
url: gurl,
dataType: 'jsonp'
}).done(function (response)
{
alert("request made to"+gurl);
var rows = response.rows;
alert(row[0].elements[0].value);
for(var i=0;i<rows.length;i++)
{
for(var j=0;j<elements.length;j++)
{
distance[i][j] = row[i].elements[j].distance.value;
}
}
alert(distance[0][0]);
});
});
});
I don't know what error are you getting so i can't be of much help.
But the code you posted has three issues:
1- Since a is undefined, i couldn't get past the first two lines.
2- Removing the a calls in the code, then it threw a Syntax Error. I fixed this by removing the last }); line.
3- It made the request, but it threw another error (probably because the URL was malformed).