Adding slides to Slick with ajax - html

so I'm using Slick Carousel and I'm showing in it a list of products from my database limited to 24 for performance reasons. But I need to show all of them, so I made a afterChange function that ajax loads another 24 products everytime the user is 2 slides before the end and add them with slickAdd function to the end of the Slick.
Everything is working fine but when the slickAdd function executes, the slides width changes for some reason from 457px to 451px and I can see a part of the 4th slide on the current slide.(I have 3 shown) Then if I click on the next button again, the width goes back to 457px and everything is ok.
$('.demo').slick({
slidesToShow: 3,
slidesToScroll: 3,
infinite: false,
});
$('.demo').on('afterChange', function(event, slick, currentSlide, nextSlide){
var komponent = $(".komponent-container.active").attr("id");
var loadWhen = currentSlide+6;
if(loadWhen == slick.slideCount){
console.log("loadmore");
$.ajax({
type: "POST",
url: "/project/public/konfigurator",
data: {id: komponent, from_column: slick.slideCount, requestid: "load_more"},
dataType: "json",
success: function (data) {
var data_parser = JSON.parse(data)[0];
if (data_parser.length > 0) {
var html = '';
for (i = 0; i < data_parser.length; i++) {
var produkt_nazov = 0;
if (data_parser[i].produkt.length > 45) {
produkt_nazov = data_parser[i].produkt.substring(0, 45) + "...";
} else {
produkt_nazov = data_parser[i].produkt;
}
html += '<div><div class="item-container"><div class="container-wrapper"><div class="produkt-container"><div class="item-left"><div class="item-image-wrapper"><img draggable="false" id="produkt-img" src="img/konfigurator/'+komponent+'/' + data_parser[i].produkt + '/1.jpg" alt="" /></div><div class="cena">' + data_parser[i].cena + ' €</div></div><div class="item-right"><div class="item-info"><span class="item-title">' + produkt_nazov + '</span><span class="item-description"><span>Výrobca čipu - ' + data_parser[i].vyrobca_cipu + '</span><span>Veľkosť pamäte - ' + data_parser[i].vram_size + '</span><span>Typ pamäte - ' + data_parser[i].vram_type + '</span><span>Frekvencia jadra - ' + data_parser[i].gpu_memory_clockrate + '</span></span></div><div class="spodna-cast"><div class="action-buttons"><a class="detail-button">Detail</a><a class="add-button">Vybrať</a></div></div></div></div></div></div></div>';
}
$(".demo").slick('slickAdd', html);
console.log("add");
}
},
error: function (result) {
alert('error');
}
});
}
});
});
What could be causing this and how to prevent it?

This fixed it for me
$(".demo")[0].slick.setPosition();

Related

How to get a response from another website using AJAX?

I have a problem about how to get a response from another website using php (api.php) but it works if api.php is placed in my folder where ( Index.php ) is also. Is it possible to get the responses from other pages like ( myurl.com/api.php ). Sorry for my bad english.
ajax placed from index.php
<script title="ajax do checker">
function enviar() {
var linha = $("#lista").val();
var linhaenviar = linha.split("\n");
var total = linhaenviar.length;
var ap = 0;
var rp = 0;
linhaenviar.forEach(function(value, index) {
setTimeout(
function() {
$.ajax({
url: 'api.php?lista=' + value,
type: 'GET',
async: true,
success: function(resultado) {
if (resultado.match("#Aprovada")) {
removelinha();
ap++;
aprovadas(resultado + "");
}else {
removelinha();
rp++;
reprovadas(resultado + "");
}
$('#carregadas').html(total);
var fila = parseInt(ap) + parseInt(rp);
$('#cLive').html(ap);
$('#cDie').html(rp);
$('#total').html(fila);
$('#cLive2').html(ap);
$('#cDie2').html(rp);
}
});
}, 500 * index);
});
}
function aprovadas(str) {
$(".aprovadas").append(str + "<br>");
}
function reprovadas(str) {
$(".reprovadas").append(str + "<br>");
}
function removelinha() {
var lines = $("#lista").val().split('\n');
lines.splice(0, 1);
$("#lista").val(lines.join("\n"));
}
code where the response will appear
<h6 style="font-weight: bold;" class="card-title">Declined - <span id="cDie2" class="badge badge-danger">0</span></h6>
<div id="bode2"><span id=".reprovadas" class="reprovadas"></span>
api.php
enter link description here
full code for index.php enter link description here

Handling Remote Data (Table Data - Undefined)

following the documentation here
I have my own web service with JSON data just for testing purposes here
Ti.API.info('Received text: ' + this.responseText); shows the JSON in console, but when i try display in table I get undefined?
The documentation example uses json.figters.length --- i used json.places.length, as it is the name on array list on my web application.
var win = Ti.UI.createWindow();
var table = Ti.UI.createTableView();
var tableData = [];
var json, places, place, i, row, countryLabel, capitalLabel;
var xhr = Ti.Network.createHTTPClient({
onload : function(){
Ti.API.info('Received text: ' + this.responseText);
json = JSON.parse(this.responseText);
for (i=0; i < json.places.length; i++)
{
place = json.places[i];
row = Ti.UI.createTableViewRow({
height: '60dp'
});
countryLabel = Ti.UI.createLabel({
text: place.country,
font:{
fontSize:'24dp'
},
height: 'auto',
left: '10dp',
top: '5dp',
color: '#000',
touchEnabled:false
});
capitalLabel = Ti.UI.createLabel({
text:'"' + place.captial + '"',
font:{
fontSize:'16dp'
},
height: 'auto',
left: '15dp',
top: '5dp',
color: '#000',
touchEnabled:false
});
row.add(countryLabel);
row.add(capitalLabel);
tableData.push(row);
}//end for
table.setData(tableData);
},
onerror: function() {
Ti.API.info('error, HTTP status = ' + this.status);
alert('Error Reading Data');
},
timeout:5000
});
xhr.open("GET", "http://130.206.127.43:8080/Test");
xhr.send();
win.add(table);
win.open();
you're pushing 2 labels into a row, but a row does not have a wrapper view.
Try something like this:
var rowView Ti.UI.createView({height: 60, layout: 'horizontal'});
rowView.add(countryLabel);
rowView.add(capitalLabel);
row.add(rowView);
tableData.push(row);

How to maintain the dynamic generated textboxes after postback

I am generating dynamic html textboxes in my aspx page. I add a button for do some functionality. now whenever I click on my button it post back and all the dynamic generated textboxes go from my form for this I have to add it again. But I want to maintain these textboxes after postback. Here is the code how i am generating textboxes
<script type="text/javascript">
var textid = null;
var textid1 = null;
$(document).ready(function () {
setupAutoComplete(textid);
setupAutoComplete1(textid1);
var counter = 2;
$("#addButton").click(function () {
if (counter > 5) {
alert("Limit Exceeds");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
textid = "textbox" + counter;
textid1 = "textbox" + counter+1;
// newTextBoxDiv.after().html('<label>Textbox #' + counter + ' : </label>' +
// '<input type="text" name="textbox' + counter +
// '" id="textbox' + counter + '" value="" class="auto">');
newTextBoxDiv.after().html('<div class="fields-left"><label> Leaving from</label><input type="text" name="textbox' + counter + '" id="textbox' + counter + '" class="auto"/> </div><div class="fields-right"> <label> Going to</label> <input type="text" name="textbox' + counter + '" id="textbox' + counter + 1 + '" class="auto"/> </div>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
setupAutoComplete(textid);
setupAutoComplete1(textid1);
counter++;
});
$("#removeButton").click(function () {
if (counter == 1) {
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
});
var setupAutoComplete= function SearchText2(textid) {
$('.auto').autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Home.aspx/GetAutoCompleteData",
data: "{'code':'" + document.getElementById(textid).value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
var setupAutoComplete1 = function SearchText3(textid1) {
$('.auto').autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Home.aspx/GetAutoCompleteData",
data: "{'code':'" + document.getElementById(textid1).value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
</script>
now in this code I am generating maximun 10 textboxes two in each row and after that I write some code for json autocomplete for each dynamic generated textbox. Now problem is this when i click on my button after that its postback and all the textboxes and its values goes away. I am unable to maintain these textboxes. Can anybody tell me how can we maintain the dymanic generated textboxes after postback?
Thanks

Unable to format JSON from WCF for HighCharts?

My WCF returns this JSON and i want to bind to HighCharts Pie
Original from WCF -[{"AllRecordsUrl":"http:\/\/EMS\/sites\/IST\/report.aspx","EMSCenterName":"IST","EMSCenterUrl":"http:\/\/EMS\/sites\/IST","Count":2},{"AllRecordsUrl":"http:\/\/EMS\/sites\/LSS\/report.aspx","EMSCenterName":"LSS","EMSCenterUrl":"http:\/\/EMS\/sites\/LSS","Count":17}]
If i hardCode it in cart series as data: [....] it works but the dynamic proccesed data does not..
After processing - [{name: 'IST' , url: 'http://EMS/sites/IST/report.aspx' , y: 2 },{name: 'LSS' , url: 'http://EMS/sites/LSS/report.aspx' , y: 16 }]
Even after processing it to what i showed above highcharts Pie won't work with my data..
I am not sure what is wrong here, would appreciate some guidance
Here's what is done so far ...
function getDataForHub(json) {
var realArray = $.makeArray(json);
//debugger;
//console.log(JSON.stringify(realArray));
var obj = $.parseJSON(JSON.stringify(realArray));
var chartData = [];
$.each(realArray, function (index, item) {
var final;
var element;
var sB = '';
var name = '';
var url = '';
var y = '';
var color = '';
for (element in item) {
if (element == 'EMSCenterName') {
name = 'name' + ": " + "'" + item[element] + "'";
}
if (element == 'AllRecordsUrl') {
url = 'url' + ": " + "'" + item[element] + "'";
}
if (element == 'Count') {
y = 'y' + ": " + item[element];
}
}
sB = name + ' , ' + url + ' , ' + y ;
//console.log(sB);
var elements = [];
//adding each to an array before being pushed to th final array,
elements.push(sB);
chartData.push(elements);
});
return chartData;
}
And here is my Pie
$(function () {
LoadSodByKey("sp.ui.dialog.js", null);
var stdWidth = 530;
var stdHeight = 200;
Highcharts.setOptions({
colors: ['#50B432', '#ED561B', '#DDDF00', '#24CBE5', '#64E572', '#FF9655', '#FFF263', '#6AF9C4']
});
$('#containerpie').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: true,
height: stdHeight + 120,
width: stdWidth + stdHeight
},
title: {
text: 'Records per Program'
},
tooltip: {
pointFormat: '{point.name}: <b>{point.percentage:.1f}%</b>'
/*formatter: function () {
return '<b>' + this.point.name;
}*/
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %'
},
showInLegend: false
}
},
series: [{
type: 'pie',
size: stdHeight,
data:[{name: 'IST' , url: 'http://EMS/sites/IST/report.aspx' , y: 2 },{name: 'LSS' , url: 'http://EMS/sites/LSS/report.aspx' , y: 16 }],
point: {
events: {
click: function(e) {
//alert(e.point.url);
var options = {
url: e.point.url,
title: e.point.name,
allowMaximize: true,
showClose: true,
width: 1100,
height: 500,
dialogReturnValueCallback: function (result, returnValue) {
//location.reload(true);
}
}
SP.UI.ModalDialog.showModalDialog(options);
e.preventDefault();
}
}
}
}]
});
var data = GetData();});
function GetData(){
var chart = $('#containerpie').highcharts();
series = chart.series[0];
//Ajax call to WCF service
$.ajax({
type: 'GET',
contentType: 'application/json; charset=utf-8',
crossDomain: false,
url: 'http://EMS/_vti_bin/EMSDashboard.svc/GetEMSCenterDataForHub',
data: null,
dataType: 'json',
success: function (response) {
var dynamicData = getDataForHub(response);
//this doesnot work
//series.data = dynamicData;
//even this does not work
//series.data.push(dynamicData)
//Wrong, wrong, wrong
//series.data.push(eval('[' +dynamicData +']'));
//gives me count of two but the chart does not load wiht dynamic data
console.log(series.data.length);
},
error: function (message) {
alert(message.statusText);
}
});
}
Thanx
FIXED:
Here's how
mistake = I had set up a static chart and was trying to use the same with $AJAX call where the chart was already created without the "data" being created, instead now the "data" array is created first and then the chart is created using chart = new Highcharts.Chart({....})
Also removed all client side preprocessing of the JSON received from WCF i.e my server object has additional Properties for Highchart rendering such to get ..
[{"name":"IST","url":"http:\/\/<XXXX>\/sites\/IST\/ASASA.aspx","y":2},
{"name":"LASS","url":"http:\/\/<XXXX>\/sites\/LASS\/ASASA.aspx","y":17}]

jQuery - google chrome won't get updated textarea value

I have a textarea with default text 'write comment...'. when a user updates the textarea and clicks 'add comment' Google chrome does not get the new text. heres my code;
function add_comment( token, loader ){
$('textarea.n-c-i').focus(function(){
if( $(this).html() == 'write a comment...' ) {
$(this).html('');
}
});
$('textarea.n-c-i').blur(function(){
if( $(this).html() == '' ) {
$(this).html('write a comment...');
}
});
$(".add-comment").bind("click", function() {
try{
var but = $(this);
var parent = but.parents('.n-w');
var ref = parent.attr("ref");
var comment_box = parent.find('textarea');
var comment = comment_box.val();
alert(comment);
var con_wrap = parent.find('ul.com-box');
var contents = con_wrap .html();
var outa_wrap = parent.find('.n-c-b');
var outa = outa_wrap.html();
var com_box = parent.find('ul.com-box');
var results = parent.find('p.com-result');
results.html(loader);
comment_box.attr("disabled", "disabled");
but.attr("disabled", "disabled");
$.ajax({
type: 'POST', url: './', data: 'add-comment=true&ref=' + encodeURIComponent(ref) + '&com=' + encodeURIComponent(comment) + '&token=' + token + '&aj=true', cache: false, timeout: 7000,
error: function(){ $.fancybox(internal_error, internal_error_fbs); results.html(''); comment_box.removeAttr("disabled"); but.removeAttr("disabled"); },
success: function(html){
auth(html);
if( html != '<span class="error-msg">Error, message could not be posted at this time</span>' ) {
if( con_wrap.length == 0 ) {
outa_wrap.html('<ul class="com-box">' + html + '</ul>' + outa);
outa_wrap.find('li:last').fadeIn();
add_comment( token, loader );
}else{
com_box.html(contents + html);
com_box.find('li:last').fadeIn();
}
}
results.html('');
comment_box.removeAttr("disabled");
but.removeAttr("disabled");
}
});
}catch(err){alert(err);}
return false;
});
}
any help much appreciated.
I believe you should be using val() and not html() on a textarea.
On a side note, for Chrome use the placeholder attribute on the textarea. You won't need a lot of this code.
<textarea placeholder="Write a comment"></textarea>