How do I iterate nested API response in AJAX? - javascript

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. :)

Related

How to convert the values in an array to strings and send to php?

I have a javascript file here.What it does is,when a user selects seats accordings to his preference in a theater layout,the selected seats are stored in an array named "seat".This code works fine until function where the selected seats are shown in a window alert.But from there onwards,the code doesn't seem to do anything.
After the above window alert, I've tried to serialize the above array and send it to the "confirm.php" file.But it does not show anything when echoed the seats.
Here is the js code.
<script type="text/javascript">
$(function () {
var settings = {
rows: 6,
cols: 15,
rowCssPrefix: 'row-',
colCssPrefix: 'col-',
seatWidth: 80,
seatHeight: 80,
seatCss: 'seat',
selectedSeatCss: 'selectedSeat',
selectingSeatCss: 'selectingSeat'
};
var init = function (reservedSeat) {
var seat = [], seatNo, className;
for (i = 0; i < settings.rows; i++) {
for (j = 0; j < settings.cols; j++) {
seatNo = (i + j * settings.rows + 1);
className = settings.seatCss + ' ' + settings.rowCssPrefix + i.toString() + ' ' + settings.colCssPrefix + j.toString();
if ($.isArray(reservedSeat) && $.inArray(seatNo, reservedSeat) != -1) {
className += ' ' + settings.selectedSeatCss;
}
seat.push('<li class="' + className + '"' +
'style="top:' + (i * settings.seatHeight).toString() + 'px;left:' + (j * settings.seatWidth).toString() + 'px">' +
'<a title="' + seatNo + '">' + seatNo + '</a>' +
'</li>');
}
}
$('#place').html(seat.join(''));
};
var jArray = <?= json_encode($seats) ?>;
init(jArray);
$('.' + settings.seatCss).click(function () {
if ($(this).hasClass(settings.selectedSeatCss)) {
alert('This seat is already reserved!');
} else {
$(this).toggleClass(settings.selectingSeatCss);
}
});
$('#btnShowNew').click(function () {
var seat = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
seat.push(item);
});
window.alert(seat);
});
$('#btnsubmit').click(function () {
var seat = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
seat.push(item);
var seatar = JSON.stringify(seat);
$.ajax({
method: "POST",
url: "confirm.php",
data: {data: seatar}
});
});
});
});
</script>
Can somebody help me figure it out what's wrong in here?
Please Add content type as json.
$.ajax({
method: "POST",
url: "confirm.php",
contentType: "application/json"
data: {data: seatar}
});
For testing you can print file_get_contents('php://input') as this works regardless of content type.

Categorising SharePoint list items on a HTML using Javascript and JSON

I have a JavaScript page which is querying a SharePoint list. The information on the list regards IT hardware, Lap Tops, Tablets etc. The user inputs the specific type, and I have a drop down of more general hardware types.
This is what I've got:
and this is what I need:
So under the hardware headings the specifics get categorised. What's the best way to do this? JavaScript below:
function getDeviceDetails() {
var txtTitle = "";
var txtOverview = "";
var txtAccessories = "";
var txtDevicetype = "";
var txtTypicalDeviceUsage ="";
var txtKnownSystemIssues ="";
var txtLifeCycles = "";
var txtTrafficlight = "";
var imgDevicePicture = "";
var tempLCS2 = "";
var query = "http://collaboration-dev.norgine.com/sites/it/SystemInventory/_vti_bin/listdata.svc/Devices?$expand=Priority&$filter=Id eq " + window.DeviceId + "";
var call = $.ajax({
url: query,
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
});
call.done(function (data,textStatus, jqXHR){
$.each(data.d.results, function(index, item) {
var tempID = item.Id;
var tempTitle = item.Title;
var DeviceOverView = item.Description;
var AccessDetails = item.Accessories;
var DeviceKind = item.DevicetypeValue;
var Usage = item.TypicalUsage;
var DevicePriority = item.PriorityValue;
var DeviceImage = item.DeviceImage;
txtTitle = "<p>"; //+ LifeCycleStart + "</p><p>" + LifeCycleStatus + "</p>";
txtOverview = "<p>" + DeviceOverView + "</p>";
txtAccessories = "<p>" + AccessDetails + "</p>";
txtDevicetype = "<p>" + DeviceKind + "</p>";
txtTypicalDeviceUsage = "<p>" + Usage + "</p>";
txtTrafficlight = "<p>" + DevicePriority + "</p>";
imgDevicePicture = "<img src='" + DeviceImage + "'>";
});
$('#devicedetails').append($(txtTitle));
$('#deviceoverview').append($(txtOverview));
$('#devicekind').append(txtDevicetype);
$('#deviceacc').append(txtAccessories);
$('#deviceuse').append(txtTypicalDeviceUsage);
$('#devicestatus').append(txtTrafficlight);
$('#imageContainer').append("<img src='/sites/IT/SiteAssets/"+txtTrafficlight.replace(/<[^>]*>/g, '')+".png' />");
$('.deviceimage').append(imgDevicePicture);
});
call.fail(function (jqXHR,textStatus,errorThrown){
alert("Error retrieving data: " + jqXHR.responseText);
});
}
You're taking records from a SharePoint list and displaying them grouped by a common column value. There are two ways to accomplish this.
Option 1: Perform Separate Queries
If you have three categories of devices (e.g. Laptop, Desktop, and Tablet) you can query the SharePoint list once for each category of items you wish to retrieve.
var urlEndpoint = "http://collaboration-dev.norgine.com/sites/it/SystemInventory/_vti_bin/listdata.svc/Devices$expand=Priority,Devicetype&$filter=Id eq " + window.DeviceId + " and ";
var laptopFilter = "DevicetypeValue eq 'Laptop'",
desktopFilter = "DevicetypeValue eq 'Desktop'",
tabletFilter = "DevicetypeValue eq 'Tablet'";
$.ajax({
url: urlEndpoint + laptopFilter,
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
}).done(displayLaptopResults);
$.ajax({
url: urlEndpoint + desktopFilter,
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
}).done(displayDesktopResults);
$.ajax({
url: urlEndpoint + tabletFilter,
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
}).done(displayTabletResults);
function displayLaptopResults(data){ /* your code here */ }
function displayDesktopResults(data){ /* your code here */ }
function displayTabletResults(data){ /* your code here */ }
This is only possible if you know the different categories beforehand and can compose your queries to filter against those categories. It has the advantage of working with smaller chunks of data at a time, and might be necessary when dealing with large lists.
If you don't know all the possible categories then consider the next option.
Option 2: Perform One Query and Post-process The Results
Alternatively, you can get all the results and place them into an in-memory data structure according to their category before displaying the records on the page.
Instead of having an array of items...
var results = [item1, item2, item3, item4, item5]
You'll have a hashmap with an array property for each category.
var results = {
category1: [item1, item4],
category2: [item2, item3],
category3: [item5]
}
The following code example demonstrates how you can process an array of items to categorize them, then render the results afterwards.
var data = {d:{results:[
{title:"X1 Carbon",DevicetypeValue:"laptop"},
{title:"T470",DevicetypeValue:"laptop"},
{title:"MS Surface Pro3",DevicetypeValue:"tablet"},
{title:"X270",DevicetypeValue:"laptop"},
{title:"M910",DevicetypeValue:"desktop"},
{title:"MS Surface Pro4",DevicetypeValue:"tablet"}]}};
var i = 0, len = data.d.results.length, item, category, devicesByCategory = {};
// loop through the results and add them to the devicesByCategory object
while(i < len){
item = data.d.results[i];
category = item.DevicetypeValue;
if(devicesByCategory[category]){
// if devicesByCategory already has an array for this item's category, add the item to it
devicesByCategory[category].push(item);
}else{
// otherwise, create a new array for the category
devicesByCategory[category] = [item];
}
i++;
}
// loop through all the categories and render them
for(var category in devicesByCategory){
var div = createCategorySection(category);
addResultsToSection(div,devicesByCategory[category]);
}
function createCategorySection(value){
var div = document.getElementById("output").appendChild(document.createElement("div"));
div.appendChild(document.createElement("h1")).appendChild(document.createTextNode(value));
return div;
}
function addResultsToSection(section,results){
var ul = section.appendChild(document.createElement("ul"));
i = 0; len = results.length;
while(i < len){
item = results[i];
ul.appendChild(document.createElement("li")).appendChild(document.createTextNode(item.title));
i++;
}
}
<div id="output"></div>

keep the memory of more than one index

I have more than three TextBoxes. I want to send this data as in the code. The "indeks " value is always the last click. How do I keep the index?
click:function(e) {
var item = e.itemElement.index();
indeks = item;
}
var field= "";
onl: function () {
$.ajax({
type: "GET",
cache:true,
url: MYURL,
success: function (msg, result, status, xhr) {
var obje = jQuery.parseJSON(msg)
var i = 0;
field = " ";
$('#wrapper *').filter(':input').each(function () {
if (txtvalue != "") {
if (i)
field += " and ";
field = field + "[" + obje[indeks]+ "]" $(this ).val() + "'";
i++;
}
});
});
},
As I wasn't sure if I got your question right, I prefered to comment on your topic - but now it seems that my answer helped you, so I decided to post it as an actual answer:
1st step: declare an array outside your success handler
2nd step: push the index and the value for the element into this array
3rd step: loop through all entries of the array and build your 'select' statement
Here is your edited example:
https://jsfiddle.net/Lk2373h2/1/
var clickedIndexes = [];
click:function(e) {
var item = e.itemElement.index();
indeks = item;
}
var field= "";
onl: function () {
$.ajax({
type: "GET",
cache:true,
url: MYURL,
success: function (msg, result, status, xhr) {
var obje = jQuery.parseJSON(msg)
var i = 0;
field = " ";
$('#wrapper *').filter(':input').each(function () {
$(this).attr('id', i);
var txtvalue=$(this).val();
if (i)
clickedIndexes.push({
index: indeks,
value: $(this ).val()
});
var selectString = "";
for (var u = 0; u < clickedIndexes.length; u++) {
selectString += "[" + obje[clickedIndexes[u].index].ALAN + "]" + "=" + "'" + clickedIndexes[u].value + "'";
}
field = selectString;
i++;
});
});
},

Optimize list selected

I have gallery into my project, when page loads it charge all upload images and categories like these:
As you can see, It suit images depending of selected categories. The problem is the page going to slow because it loads all images... How can I do to optimize these process? I think some like delete All categorie, but I donĀ“t know how to do my query to start for example with office categorie filter
There is my code:
function GalleryCatPopulate(url, listname, target) {
var eng = false;
if ((window.location.href.indexOf("lang=en") > 0)) {
eng = true;
}
// Getting our list items
$.ajax({
url: url + "/_api/web/lists/getbytitle('" + listname + "')/items? $select=Title,English",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
completeGalleryCat(data, target, eng);
},
error: function (data) {
failureGalleryCat(data, target);
}
});
}
function completeGalleryCat(data, target, eng) {
var items = data.d.results;
var prefix = "";
var sufix = "<div class='clear'></div>";
if (eng)
prefix = "<div class='filter selected' data-category='cat-all'>All</div>";
else
prefix = "<div class='filter selected' data-category='cat-all'>Todas</div>";
var menu = "";
var cat = "";
var title = "Transporte de Materiales";
console.log(title.replace(/\s/g, "_").replace(/[^\w\s]/gi, ''));
for (var item in items) {
if (eng)
cat = items[item].English;
else
cat = items[item].Title;
menu += "<div class='filter' data-category='" + cat.replace(/\s/g, "_").replace(/[^\w\s]/gi, '') +"'>"+ cat +"</div>";
}
$(target).html(prefix + menu + sufix);
}
function failureGalleryCat(data, target) {
$(target).text("There is something bad wit load images, please check console");
}
function GalleryContentPopulate(url, listname, target) {
var eng = false;
var queryGallery = "$select=Title,Description,Enlace,EncodedAbsUrl,Categoria/Title&$expand=Categoria/Title";
if ((window.location.href.indexOf("lang=en") > 0)) {
queryGallery = "$select=TitleEnglish,DescriptionEnglish,Enlace,EncodedAbsUrl,Categoria/English&$expand=Categoria/English";
eng = true;
}
// Getting our list items
$.ajax({
url: url + "/_api/web/lists/getbytitle('" + listname + "')/items?$top=1000&" + queryGallery,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
completeGalleryContent(data, target, eng);
},
error: function (data) {
failureGalleryContent(data, target);
}
});
}
function completeGalleryContent(data, target, eng) {
var items = data.d.results;
console.log(items);
var menu = "";
var cat = "";
for (var item in items) {
if(items[item].DescriptionEnglish==null)
items[item].DescriptionEnglish="";
if(items[item].Description==null)
items[item].Description="";
if(items[item].Categoria.results!= null && items[item].Categoria.results!= undefined && items[item].Categoria.results.length > 0){
cat =setCategories(eng,items[item].Categoria.results);
}
if (eng){
menu += "<div class='mega-entry " + cat + " cat-all' id='mega-entry-1' data-src='" + items[item].EncodedAbsUrl + "' data-width='' data-height='' data-lowsize=''><div class='mega-covercaption mega-square-bottom mega-landscape-right mega-portrait-bottom mega-red'><div class='mega-title'>" + items[item].TitleEnglish + "</div><p>" + items[item].DescriptionEnglish + "</p></div><div class='mega-coverbuttons'><div class='mega-link mega-red'></div><a class='fancybox' rel='group' href='" + items[item].EncodedAbsUrl + "' title='" + items[item].TitleEnglish + "'><div class='mega-view mega-red'></div></a></div> </div>";
}else{
menu += "<div class='mega-entry "+ cat + " cat-all' id='mega-entry-1' data-src='" + items[item].EncodedAbsUrl + "' data-width='' data-height='' data-lowsize=''><div class='mega-covercaption mega-square-bottom mega-landscape-right mega-portrait-bottom mega-red'><div class='mega-title'>" + items[item].Title + "</div><p>" + items[item].Description + "</p></div><div class='mega-coverbuttons'><div class='mega-link mega-red'></div><a class='fancybox' rel='group' href='" + items[item].EncodedAbsUrl + "' title='"+ items[item].Title +"'><div class='mega-view mega-red'></div></a></div></div>";
}
}
$(target).html(menu);
var api = $(target).megafoliopro(
{
filterChangeAnimation: "pagebottom", // fade, rotate, scale, rotatescale, pagetop, pagebottom,pagemiddle
filterChangeSpeed: 400, // Speed of Transition
filterChangeRotate: 99, // If you ue scalerotate or rotate you can set the rotation (99 = random !!)
filterChangeScale: 0.6, // Scale Animation Endparameter
delay: 20,
defaultWidth: 980,
paddingHorizontal: 10,
paddingVertical: 10,
layoutarray: [9, 11, 5, 3, 7, 12, 4, 6, 13] // Defines the Layout Types which can be used in the Gallery. 2-9 or "random". You can define more than one, like {5,2,6,4} where the first items will be orderd in layout 5, the next comming items in layout 2, the next comming items in layout 6 etc... You can use also simple {9} then all item ordered in Layout 9 type.
});
//console.log("entra");
// FANCY BOX ( LIVE BOX) WITH MEDIA SUPPORT
jQuery(".fancybox").fancybox();
//console.log("sale");
// THE FILTER FUNCTION
$('.filter').click(function () {
$('.filter').each(function () { jQuery(this).removeClass("selected") });
api.megafilter(jQuery(this).data('category'));
$(this).addClass("selected");
});
var categorySelected = getParameterByName("Category");
$("div[data-category='"+categorySelected +"']").click();
}
function failureGalleryContent(data, target) {
console.log(data);
$(target).text("Error loading parallax. Please check console for more info");
}
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
function setCategories(boolLang, objResult){
var cat ="";
for(var item in objResult){
if(boolLang)
cat += replaceAll(" ", "_",objResult[item].English.replace(/[^\w\s]/gi, '')) + ' ';
else
cat += replaceAll(" ", "_",objResult[item].Title.replace(/[^\w\s]/gi, '')) + ' ';
}
return cat;
}
function replaceAll( find, replace,string) {
return string.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}
function escapeRegExp(string) {
return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}
Thankyou in advance!

How to put result into DIV from JSON?

From the below function I am getting results. Now I want to put that result into a div. So how should I put the result into a div?
$(document).ready(function () {
$.ajax({
type: "POST",
url: "../ajaxaction.php",
data: {
action: 'alllist'
},
dataType: 'json',
success: function (msg) {
for (var i = 0; i < msg.length; i++) {
var uname = msg[i].user_name;
var vtitle = msg[i].video_title;
var vid = msg[i].video_id;
var vthumb = msg[i].video_thumb;
}
}
});
});
You can append the result in to div with the format you like but a simple way of adding would be. You can use append() function to keep the added html with new html for each iteration of loop.
success: function(msg){
for (var i = 0; i < msg.length; i++) {
var uname = msg[i].user_name;
var vtitle = msg[i].video_title;
var vid = msg[i].video_id;
var vthumb = msg[i].video_thumb;
$('#divId').append("Name: " + uname + "," + "Title: " + vtitle +
"Id: " + vid + "," + "Thumb: " + vthumb + "<br />");
}
$(document).ready(function() {
$.ajax({
type: "POST",
url: "../ajaxaction.php",
data: { action:'alllist'},
dataType: 'json',
success: function(msg){
for (var i = 0; i < msg.length; i++) {
var uname = msg[i].user_name;
var vtitle = msg[i].video_title;
var vid = msg[i].video_id;
var vthumb = msg[i].video_thumb;
$("#container").html("Username: " + uname + "<br />Video Title: " + vtitle + "<br />Vide ID: " + vid + "<br />Video Thumb: " + vthumb);
}
}});
});
If your div exists:
jQuery('div selector').append(uname+' '+vtitle+...whatever variable and format);
If not
jQuery('element selector to put the div in').append('<div id="aID" class="some classes">'+uname+' '+vtitle+...whatever variable and format...+'</div>');
you can do this:
success: function(msg){
$.each(msg, function(i, item){
$('#divid').html('User Name : '+item.user_name+
'Video title : '+item.video_title+
'Video Id : 'item.video_id+
'Video Thumb : 'item.video_thumb );
});
}

Categories