Selectize (.js) and external source - javascript

How I can load dynamicly (like $.ajax or getjson) in selectize options list?
Searched thru the forum, looks like nobody did it this way for some reason (?)
Thanks.

The load(fn) method is probably what you are looking for.
Loads options by invoking the the provided function. The function
should accept one argument (callback) and invoke the callback with the
results once they are available.
Here is the first Remote Source example:
$('#select-repo').selectize({
valueField: 'url',
labelField: 'name',
searchField: 'name',
create: false,
render: {
option: function(item, escape) {
return '<div>' +
'<span class="title">' +
'<span class="name"><i class="icon ' + (item.fork ? 'fork' : 'source') + '"></i>' + escape(item.name) + '</span>' +
'<span class="by">' + escape(item.username) + '</span>' +
'</span>' +
'<span class="description">' + escape(item.description) + '</span>' +
'<ul class="meta">' +
(item.language ? '<li class="language">' + escape(item.language) + '</li>' : '') +
'<li class="watchers"><span>' + escape(item.watchers) + '</span> watchers</li>' +
'<li class="forks"><span>' + escape(item.forks) + '</span> forks</li>' +
'</ul>' +
'</div>';
}
},
score: function(search) {
var score = this.getScoreFunction(search);
return function(item) {
return score(item) * (1 + Math.min(item.watchers / 100, 1));
};
},
load: function(query, callback) {
if (!query.length) return callback();
$.ajax({
url: 'https://api.github.com/legacy/repos/search/' + encodeURIComponent(query),
type: 'GET',
error: function() {
callback();
},
success: function(res) {
callback(res.repositories.slice(0, 10));
}
});
}
});

Related

How do I call Datatables draw() method in Ajax?

I am trying to implement datatables draw() method in my Django application using AJAX. I have implemented both datatables and AJAX, which are working fine. However, I am facing a lot of challenges anytime I create a new object and call the draw() method so that datatables can refresh the table and show the newly created data the proper way. If I add the draw() method, the table does not get populated at all except I refresh the page.
main.js
//datatables
$(document).ready(function() {
$('table').on('click', ".dropdownDatatableButton" ,function() {
$( this ).toggleClass( "active");
});
function csrfSafeMethod(method) {
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
};
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val();
var table = $('#boardsTable').DataTable({
"autoWidth": false,
"info": false,
"lengthChange": false,
"processing": true,
"hover": true,
"serverMethod": 'post',
"searching": true,
"ajax": "/boards/api/data/?format=datatables",
"pagingType": "full_numbers",
"order": [[ 0, "asc" ]],
language: {
search: "",
"zeroRecords": '<img class=' + '"dataTables-error-image"' + 'src=' + "'/static/media/images/empty-search.jpg'"
+ '/>' + '<p class=' + '"dataTables-error-text"' + '>'
+ 'No boards were found that match your search' + '<p/>',
"loadingRecords": '<div class="spinner-border m-5" role="status">'
+ '<span class="sr-only d-block">Loading...</span> </div>'
+ '<p class="d-block text-center mt-3">Pulling board information...' + '</p>',
"processing": '<p class="d-block text-center datatables-processing-text">Please wait...' + '</p>',
"emptyTable": '<img class=' + '"dataTables-error-image"' + 'src=' + "'/static/media/images/new.jpg'"
+ '/>' + '<p class=' + '"dataTables-error-text font-weight-bold"' + '>'
+ 'No boards to show right now' + '<p/>'
+ '<p class=' + '"dataTables-empty-table-description"' + '>'
+ 'When you start working on recruitment campaigns, we’ll list all your boards here.'
+ '<p/>'
+ '<a class="dataTables-error-create-btn show-only-on-mobile" data-bs-toggle="modal"'
+ 'data-bs-target="#createBoardModal" data-bs-backdrop="static"'
+ 'data-bs-keyboard="false">' + 'Create a board' + '<a/>',
},
initComplete : function() {
$("#boardsTable_filter").detach().appendTo('.filter-form');
},
"drawCallback": function(settings) {
var pagination = $(this).closest('.dataTables_wrapper').find('.dataTables_paginate');
pagination.toggle(this.api().page.info().pages > 1);
},
"columns": [
{data: null,
render: function ( data, type, row ) {
// show the board avatar and make merge it with `data: name`
return '<a class="datatable-board-link" href="' + data.url.toLowerCase() + '/manage' + '">'
+ '<img class="datatable-board-link-img" ' + 'src="' + data.avatar + '" ' + 'width="30px" '
+ 'height="30px" ' + 'alt="board avatar" />' + data.name + '</a>' ;
}
},
{data: null,
render: function ( data, type, row, meta ) {
// show the URL which are accessible to candidates
return '<a class="new-tab-board-link" href="' + data.lead.username + '/'
+ data.url + '" target="_blank">' + '/' + data.url
+ '<span class="material-icons">open_in_new</span>' + '</a>';
}
},
{ data: "lead",
render: function ( data, type, row, meta ) {
// show the lead recruiter avatar and combine the first and last names into a single table field
return '<a class="datatable-profile-link"' + 'href="'
+ 'http://127.0.0.1:8080/people/teams/' + data.id + '/' + data.username.toLowerCase() +'"'
+ 'target="_blank"' + '>' + '<img class="datatable-profile-link-img" ' + 'src="'+ data.avatar
+ '" ' + 'width="30px" ' + 'height="30px" ' + 'alt="' + data.name + ' ' + "'s avatar" + '"'
+ '/>' + data.name + '</a>';
},
},
{ data: null,
render: function ( data, type, row, meta ) {
return '<div class="dropdown datatables-dropdown" id="datatablesDropdown">'
+ '<span class="material-icons btn dropdownDatatableButton" id="dropdownDatatableButton"'
+ 'type="button"' + 'data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">'
+ 'more_horiz</span>'
+ '<div class="dropdown-menu dropdown-menu-right datatables-dropdown-inner"'
+ ' aria-labelledby="dropdownDatatableButton">'
+ '<ul>'
+ '<li>Board settings</li>'
+ '<li><a class="btn btn-link btn-sm text-left">Delete</a></li>'
+ '</ul>'
+ '</div>'
+ '</div>';
},
},
],
"columnDefs": [
{"width": "10%", "targets": 3, "orderable": false},
],
});
table.columns().iterator('column', function (ctx, idx) {
$(table.column(idx).header()).append('<span class="sort-icon"/>');
});
// call the AJAX post method
$("#createBoardViaModalForm").on('submit', function (e) {
var spinner = $('#loader');
for ( instance in CKEDITOR.instances ) {
CKEDITOR.instances[instance].updateElement();
}
e.preventDefault();
spinner.show();
var serializedData = $(this).serialize();
$.ajax({
type: 'POST',
url: "post/ajax/board/",
data: serializedData,
success: function (data) {
if($('input[type="checkbox"]').prop("checked") == true){
//some codes
...
//take some serialised data and populate the table
// THIS IS WHERE THE ISSUE STARTS
var data = JSON.parse(data["data"]);
var fields = data[0]["fields"];
$("#boardsTable tbody").prepend(
`<tr>
<td>${fields["name"]||""}</td>
<td>${fields["url"]||""}</td>
<td>${fields["lead"]||""}</td>
</tr>`
);
// invoke datables draw() method to refresh the table
table.draw();
setTimeout(function(){
spinner.hide();
}, 1000);
console.log("Checkbox is checked. Modal will not be closed");
}
else if($('input[type="checkbox"]').prop("checked") == false){
// some codes
...
table.draw();
// more codes
}
},
error: function (jqXHR, textStatus, errorText) {
let data = jqXHR.responseJSON;
// more codes
console.log('There are some errors on the submitted form. Check the data errors array')
console.log(data)
}
})
});
//clear up the error logs when a user enters a value in the highlighted input field
});
I used the datatables reload API.
table = $("#boardsTable").DataTable().ajax.reload();
In your AJAX success function, you can draw it like so:
success: function(data) {
console.log(data);
if (data.d != null && data.d != undefined && data.d.results.length > 0) {
var table = $('#boardsTable').DataTable();
table.rows.add(data.d.results).draw();
}
}

How do I display external API search results in a table?

I am a final year student and am creating a food log web application for my major project. I have created a search function that allows me to search and display external API results, but now I wish to display them in a table, can anyone help please?
I would prefer if it would be a table that can be filtered, eg, the columns ordered ascending/descending?
Thanks
function get foodItem(userInput) {
var storedSearchItem;
$('.resultContainer').html('');
$.ajax({
type: 'GET',
async: false,
url: 'https://api.nutritionix.com/v1_1/search/'+userInput+'?'+
'fields=item_name%2Citem_id%2Cbrand_name%2Cnf_calories%2Cnf_total_fat&appId=325062a4&appKey=bf1a30b2066602dc6f33db888cd53bd3',
success: function(d) {
storedSearchItem = d.hits;
}
});
storedSearchItem.map(function(item) {
var x = item.fields
$('.resultContainer').append(
'<div class="itemBar">'+
'<h2>' + x.item_name + '<h2>' +
'<h3>Calories: ' + x.nf_calories + '<h3>' +
'<h3>Serving Size: ' + x.nf_serving_size_qty + ' ' + x.nf_serving_size_unit +'<h3>' +
'<h3>Total Fat: ' + x.nf_total_fat + '<h3>' +
'</div>'
);
});
}//ends get result function
function searchValue() {
var formVal = document.getElementById('itemSearch').value; //value from search bar
getFoodItem(formVal);
}
$('#searchForm').submit(function(e) {
e.preventDefault();
});`
You need to append your table in the success function
your code will look like something like this
success: function(d) {
storedSearchItem = d.hits;
storedSearchItem.map(function(item) {
var x = item.fields
$('.resultContainer').append(
'<div class="itemBar">'+
'<h2>' + x.item_name + '<h2>' +
'<h3>Calories: ' + x.nf_calories + '<h3>' +
'<h3>Serving Size: ' + x.nf_serving_size_qty + ' ' + x.nf_serving_size_unit +'<h3>' +
'<h3>Total Fat: ' + x.nf_total_fat + '<h3>' +
'</div>'
);
});
}

jquery ajax nested callbacks

I have nested callabcks but resulted output is not ordered correctly. My ajax results are in ascending orders of id but html generated is random. can someone help me out pls?
var formatedhtml = '';
$.ajax({
type: "POST",
url: BASE_URL + 'index.php/orders/read',
dataType: 'json',
success: function(data) {
$.each(data, function(key, value) {
console.log(value);
getdetails(value['id'], function(output) {
formatedhtml = formatedhtml +
'<div class="col-md-4 col-sm-4 col-lg-3 col-xs-6">' +
' <div class="row">' +
' <div class="orderno">' + value['id'] + '</div>' +
'<div class="tableno">' + value['tableno'] + '</div>' +
'<div class="ordertype">' + value['type'] + '</div>' +
'<div class="timestamp">' + value['created'] + '</div>' +
' </div>' +
'<hr>';
$.each(JSON.parse(output['items']), function(k, val) {
formatedhtml = formatedhtml + '<div class="row">' +
'<div class="quantity">' + val[3] + '</div>' +
'<div class="item">' + '</div>' +
'</div>';
});
formatedhtml = formatedhtml +
'<div class="row">' +
'<div class="notes">' + value['id'] + '</div>' +
'</div>' +
'</div>';
$("#orderlist").html(formatedhtml);
console.log(output);
});
});
}
});
edit:
Here is getdetails function. its an ajax request.
function getdetails(id, callback) {
var result;
$.ajax({
type: "POST",
url: BASE_URL + 'index.php/orders/readdetails',
dataType: 'json',
data: {
id: id,
},
success: function(data) {
callback(data[0]);
}
});
};
There are a lot of ways to achieve this, one is to use a promise and sort by id when all requests are done. Another you could create the template and append the details on callback as each detail request has an id you can define in your template a class like 'id-'+value['id'] and use jquery selector and append detail template.
Another solution would be to create a function loop that calls itself untill orderCount == orderLoaded.
Job is done synchronously (takes more time)
//Mock ajax function
$.ajax = function (param) {
if(param.url.indexOf('readdetails') != -1){
param.success(itemsData);
} else {
param.success(ordersData);
}
};
//Mock data
var ordersData = [
{ id : 1, tableno : 'xyz', type: 'invoice', created: '01/01/2001' },
{ id : 2, tableno : 'xyz', type: 'invoice', created: '01/01/2001' },
{ id : 3, tableno : 'xyz', type: 'invoice', created: '01/01/2001' }
];
var itemsData = [
{ id : 1, orderid: 1, quantity: 5 },
{ id : 2, orderid: 1, quantity: 2 },
{ id : 3, orderid: 1, quantity: 1 }
];
// Globals
var formatedhtml = [];
var orders = [];
var lastOrderLoaded = 0;
var BASE_URL = 'localhost/';
function tpl(order, items) {
var html = '<tr class="col-md-4 col-sm-4 col-lg-3 col-xs-6">' +
' <td class="orderno">' + order['id'] + '</td>' +
'<td class="tableno">' + order['tableno'] + '</td>' +
'<td class="ordertype">' + order['type'] + '</td>' +
'<td class="timestamp">' + order['created'] + '</td>' +
' </tr>';
$.each(items, function(key, item) {
html += '<tr class="row">' +
'<td class="item">item: ' + item.id + '</td>' +
'<td class="quantity">quantity: ' + item.quantity + '</td>' +
'</tr>';
});
html +=
'<tr class="row">' +
'<td class="notes"> notes </td>' +
'<td class="notes"> order id ' + order['id'] + '</td>' +
'</tr>' +
'</tr>';
formatedhtml.push({ id: order.id, html : html });
}
$.ajax({
type: "POST",
url: BASE_URL + 'index.php/orders/read',
dataType: 'json',
success: function(data) {
lastOrderLoaded = 0;
orders = data;
getdetails(orders[0]);
}
});
function getdetails(order) {
$.ajax({
type: "POST",
url: BASE_URL + 'index.php/orders/readdetails',
dataType: 'json',
data: {
id: order.id,
},
success: function(data) {
tpl(order, data);
if(lastOrderLoaded < orders.length - 1){
lastOrderLoaded++;
getdetails(orders[lastOrderLoaded]);
} else {
formatedhtml.forEach(function(element){
$("#orderlist").append(element.html);
}); // end each
}
}
});
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="orderlist" border="1">
<tr><th>id</th><th>no</th><th>type</th><th>date</th></tr>
</table>
Promise Solution:
Job is done asynchronously (might take less time also bombards the server with many requests at once)
var formatedhtml = [];
function tpl(order, items) {
var html = '<div class="col-md-4 col-sm-4 col-lg-3 col-xs-6">' +
' <div class="row">' +
' <div class="orderno">' + order['id'] + '</div>' +
'<div class="tableno">' + order['tableno'] + '</div>' +
'<div class="ordertype">' + order['type'] + '</div>' +
'<div class="timestamp">' + order['created'] + '</div>' +
' </div>' +
'<hr>';
$.each(JSON.parse(items['items']), function(key, item) {
var html += '<div class="row">' +
'<div class="quantity">' + item[3] + '</div>' +
'<div class="item">' + '</div>' +
'</div>';
});
html +=
'<div class="row">' +
'<div class="notes">' + order['id'] + '</div>' +
'</div>' +
'</div>';
formatedhtml.push({ id: order.id, html : html });
}
$.ajax({
type: "POST",
url: BASE_URL + 'index.php/orders/read',
dataType: 'json',
success: function(data) {
var syncLoad = [];
$.each(data, function(key, value) {
syncLoad.push(getdetails(value, tpl));
});
$.when.apply($, syncLoad).done(function() {
formatedhtml.sort(function(a, b){
return a.id - b.id;
});
formatedhtml.forEach(function(element){
$("#orderlist").append(element.html);
});
});
}
});
function getdetails(order, callback) {
return $.ajax({
type: "POST",
url: BASE_URL + 'index.php/orders/readdetails',
dataType: 'json',
data: {
id: order.id,
},
success: function(data) {
callback(order, data[0]);
}
});
};
Use async:false in your getDetails() ajax call.
function getdetails(id, callback) {
var result;
$.ajax({
type: "POST",
url: BASE_URL + 'index.php/orders/readdetails',
dataType: 'json',
async: false,
data: {
id: id,
},
success: function (data) {
callback(data[0]);
}
});

Append an HTML block after another appended block

I have an ajax script that retrieves more X results from the database. The number of results depend on the offset hidden field value. The script doubles it. After these X new data, it should append after it another block of an image, but I noticed that if I print in the console the selected element, it shows this:
[prevObject: m.fn.init[1], context: document, selector: "#revendas_conteudo .load_more .item_estoque:nth-child(4)"]context: documentlength: 0prevObject: m.fn.init[1]selector: "#revendas_conteudo .load_more .item_estoque:nth-child(4)"proto: Object[0]
[prevObject: m.fn.init[1], context: document, selector: "#revendas_conteudo .load_more .item_estoque:nth-child(6)"]context: documentlength: 0prevObject: m.fn.init[1]selector: "#revendas_conteudo .load_more .item_estoque:nth-child(4)"proto: Object[0]
Which means it's trying to append to something that still doesn't exist. Below is the Ajax script:
function appendAd(offset, no) {
console.log($('#revendas_conteudo .load_more .item_estoque:nth-child(' + offset + ')'));
$('#revendas_conteudo .load_more .item_estoque:nth-child(' + offset + ')').after(
'<div style="float: left; margin-top: 8px; margin-bottom: 8px; width: 100%; text-align: center;" class="anuncio">' +
'<img src="/uploads/publicidades/publicidade_busca_' + no + '.jpg">' +
'</div>'
);
}
$('#revendas_conteudo .btn_carregar_mais').on('click', function (e) {
$.ajax({
url: '/auto/carros/load_more',
data: {
'offset': $('#offset').val(),
'limit': $('#limit').val(),
'no': $('#no').val()
},
success: function (data) {
obj = JSON.parse(data);
i = 0;
max = obj.total === obj.offset;
var newOffset;
no = parseInt($('#no').val()) + 1;
$('#limit').val(obj.limit);
$('#offset').val(obj.offset);
$('#no').val(obj.no);
$.each(obj.res, function (k, v) {
newOffset = parseInt($('#offset').val()) + 1;
$('#revendas_conteudo .load_more').append(
'<div class="item_estoque">' +
'<div class="avatar">' +
'<img src="/uploads/carros/destaque/' + obj.res[i].imagem_destaque + '"/>' +
'</div>' +
'<div class="texto_anuncio">' +
'<h4>' + obj.res[i].modelo.substring(0, 19) + '</h4>' +
'<div class="detalhes">' +
'<span>' + obj.res[i].marca + ' | ' + obj.res[i].combustivel + ' | ' + obj.res[i].cor + '</span>' +
'<span>' + obj.res[i].ano + '</span>' +
'<span>' + obj.res[i].kilometragem + ' km</span>' +
'</div>' +
'<span class="anunciante">' + obj.res[i].nome_anunciante + '</span>' +
'</div>' +
'<div class="texto_anuncio_right">' +
'<span class="preco"> R$ ' + obj.res[i].preco + '</span>' +
'Veja Mais' +
'</div>' +
'</div>'
);
i++;
$('#offset').val(newOffset);
$('#no').val(no);
if (newOffset == obj.total) {
$('#revendas_conteudo .btn_carregar_mais').css({backgroundColor: '#999'}).html('Sem mais resultados').attr('disabled', true);
}
});
},
complete: function() {
appendAd($('#offset').val(), no);
}
});
});
How can I do it? To append a block after another HTML block has been appended?

How to return a value from javascript function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I have the following function from where i want to return the htm value however i am getting an undefined. I get a return value as i have checked that already.
function loadData(uid) {
$.ajax({
type: "POST",
url: '<%= page.resolveURL("~")%>Haggler.asmx/getLovedProductsSellerStoreByFbId',
//url: '<%= Page.ResolveUrl("~")%>Haggler.asmx/GetFacebookFriends',
data: '{FacebookId:' + uid + ',pageIndex:' + JSON.stringify(pageIndex) + '}',
contentType: "application/json; charset=utf-8",
dataType: 'json',
async: true,
// Page parameter to make sure we load new data
success: function (data) {
var myObject = eval('(' + data.d + ')');
//alert('getProductDescription' + JSON.stringify(myObject));
var html = '';
pageIndex++;
var htmlCategoryList = '';
var i = 0, length = myObject.length;
var _productLink = '';
var _productFullLink = '';
if (length > 0) {
pageCount = myObject[0].PageCount;
if (length > 0) {
for (; i < length; i++) {
if (myObject[i].ShippingQuantity > 0) {
_productLink = myObject[i].SellReqID + '/product/' + myObject[i].CurrentNodeName;
_productFullLink = "http://www.xarato.com/" + myObject[i].SellReqID + "/product/" + myObject[i].CurrentNodeName;
if (myObject[i].Discount == 0) {
/**
if (parts[parts.length-1] == 'loves') {
html += '<li class="polaroid"><div class="prodoptionbg prodseller"><span>Listed by ' + myObject[i].FirstName + ' ' + myObject[i].LastName + '</span></div><a href="/' + _productLink + '"><div style="position:relative;"><img alt="' + myObject[i].NodeName + '" src="/' + myObject[i].
html += '<li class="polaroid"><div style="position:relative;"><img alt="' + myObject[i].RequestTitle + '" src="/' + myObject[i].Image1 + '"_thumb.jpg" width="200" height="' + myObject[i].ThumbHeight1 + '"><div class="options"><span class="favs" id="span' + myObject[i].SellReqID + '">' + myObject[i].Likes + '</span><span class="fav" onclick="calculateLike(event,' + myObject[i].SellReqID + ')">like it!</span></div></div><div class="prod"><span>' + myObject[i].RequestTitle + '</span></div><div class="prodprice1"><span style="font-weight:700;">Rs. ' + Math.round(parseFloat(myObject[i].MRPrice) + parseFloat(myObject[i].ShippingPrice)) + '</span></div></li>';
}else{ **/
//alt="' + myObject[i].RequestTitle + '"
html += '<img alt="' + myObject[i].RequestTitle + '" src="/' + myObject[i].Image1 + '_thumb.jpg" width="200" height="' + myObject[i].ThumbHeight1 + '">';
//}
}
else {
/**if (parts[parts.length-1] == 'loves') {
var _finalPrice = parseFloat(myObject[i].MRPrice) - (parseFloat(myObject[i].Discount) * parseFloat(myObject[i].MRPrice))/100
html += '<li class="polaroid"><div class="prodoptionbg prodseller"><span>Listed by ' + myObject[i].FirstName + ' ' + myObject[i].LastName + '</span></div><div style="position:relative;"><img alt="' + myObject[i].NodeName + '" src="/' + myObject[i].Preview + '_thumb.jpg" width="200" height="' + myObject[i].Height + '"><div class="options"><span class="favs" id="span' + myObject[i].NodeId + '">' + myObject[i].Likes + '</span><span class="fav" onclick="calculateLike(event,' + myObject[i].NodeId + ')">like it!</span></div><div class="kjss"><span>' + myObject[i].Discount + '% Off</span></div></div><div class="prod"><span>' + myObject[i].NodeName + '</span></div><div class="prodprice1"><span style="color:#777777; text-decoration:line-through">Rs. ' + myObject[i].MRPrice + '</span> <span style="font-weight:700;">Rs. ' + Math.round(_finalPrice + parseFloat(myObject[i].ShippingPrice)) + '</span></div></li>';
}else{**/
//alt="' + myObject[i].RequestTitle + '"
html += '<img alt="' + myObject[i].RequestTitle + '" src="/' + myObject[i].Image1 + '_thumb.jpg" width="200" height="' + myObject[i].ThumbHeight1 + '">';
//}
}
}
}
if (clearHtml) {
// $('.bxslider').html('');
//htm = '<li>"' + html + '"</li>';
}
// var htmli = '<li>"' + html + '"</li>';
// $('.bxslider').append(htmli);
htm = '<li>' + html + '</li>';
alert(htm);
return htm;
clearHtml = false;
var options = {
autoResize: true, // This will auto-update the layout when the browser window is resized.
container: $('#main'), // Optional, used for some extra CSS styling
offset: 17, // Optional, the distance between grid items
itemWidth: 225 // Optional, the width of a grid item
};
}
else {
return;
}
}
else {
return;
}
},
failure: function (data) {
alert('failture');
},
error: function (data) {
alert(data.responseText);
}
});
}
This is how i am taking the data but i get an undefined value.
HtmlM += loadData(myObject.data[i].uid);
Please help me out.
Change your loadData to
function loadData(uid, delegate) {
///In ajax instead of return use
delegate(htm);
}
then call like that
loadData(myObject.data[i].uid, function(html){ HtmlM += html ;});
Ajax is asynchronous so you cant just return (yes you can do it synchronous but its not right way)

Categories