jquery div undefined with .html() - html

I am using Jquery ajax.
I have made ajax call to fetch data and concact the html string and attached to id of div.
$("#divMenuList").html(JsMenuListHtml);
alert($("#divMenuList").html());
But with alert is showing undefined. I have it using listing if i am page change it showing first time with html string but if i will delete second page record and re-call that function it will showing undefined.
Here is the whole function:
function performlisting(data, JsCurrPage) {
var JsMenuTitle = '';
var JsOrderNumber = '';
var JsMenuId = '';
var JsMenuListHtml = '';
var JsCounter = 0;
var JsAlternateRow = '';
var JsIsActive = "false";
var JsIsActiveClass = "";
var JsIsActiveTitle = "";
if (data.Data.length > 0) {
for (i = 0; i < data.Data.length ; i++) {
JsCounter++;
if (JsCounter % 2 == 0) {
JsAlternateRow = "alternate-row";
}
else {
JsAlternateRow = '';
}
//set true/false for update status
if (data.Data[i]['IsActive'] == true) {
JsIsActive = "false";
JsIsActiveClass = "icon-3 info-tooltip";
JsIsActiveTitle = "Published";
}
else if (data.Data[i]['IsActive'] == false) {
JsIsActive = "true";
JsIsActiveClass = "icon-4 info-tooltip";
JsIsActiveTitle = "UnPublished";
}
else {
JsIsActive = "false";
JsIsActiveClass = "icon-4 info-tooltip";
JsIsActiveTitle = "UnPublished";
}
JsMenuTitle = data.Data[i]['MenuTitle'];
JsOrderNumber = data.Data[i]['OrderNumber'];
JsMenuId = data.Data[i]['MenuId'];
JsMenuListHtml = JsMenuListHtml +
'<tr class= ' + JsAlternateRow + '>' +
'<td style="width:3.4%;"><input type="checkbox" value=' + JsMenuId + ' /></td><td style="width:38.8%;">' + JsMenuTitle + '</td>' +
'<td style="width:39%;">' +
'<a title="Up-Rank" href="javascript:void(0);" onclick="return performUpMenu(\'' + JsOrderNumber + '\', \'' + JsMenuId + '\')"><img src=' + JsUpImage + '></a>' +
'<a title="Down-Rank" href="javascript:void(0);" onclick="return performDownMenu(\'' + JsOrderNumber + '\', \'' + JsMenuId + '\')"><img src=' + JsDownImage + '></a>' +
'' + JsOrderNumber + '</td>' +
'<td class="options-width">' +
'' +
'<a href="javascript:void(0);" onclick="return performstatusmenu(\'' + JsIsActive + '\', \'' + JsMenuId + '\');" title= ' + JsIsActiveTitle + ' class=' + JsIsActiveClass + '></a>' +
'</td>' +
'</tr>';
}
$("#divMenuList").html("");
$("#divMenuList").html(JsMenuListHtml);
alert($("#divMenuList").html());
//hide num of raws dropdown
if (parseInt(JsTotalRecs) > parseInt(JsPageSize)) {
alert("Called1");
SetPaging(JsTotalRecs, parseInt(JsCurrPage));
}
else {
alert("Called");
$("#pager").html('');
}
$("#CurrPage").val(JsCurrPage);
SetAllCheckboxes();
}
else {
if ($("#CurrPage").val() > 1) {
//Error Message Pager
$("#product-table").html("");
$("#divSuccessMessage").html("");
alert(parseInt($("#CurrPage").val()));
GetListing(parseInt($("#CurrPage").val() - 1), parseInt(JsPageSize));
}
else {
$("#product-table").html("");
$("#divErrMessage").html("");
$("#divSuccessMessage").html("");
}
}
}
Regards

Related

how to make each json data to an separate element

** i want to display the theaters like a child node element of the demo node and after i want to trigger the onclick event for other function...**
using only javascript
let VizagData = '{"theater":[' +
'{"TheaterName":"Sangam","Quality":"4K","sound":"DolbyAtmos" },' +
'{"TheaterName":"Sarat","Quality":"4K","sound":"DolbyAtmos" },'+
'{"TheaterName":"Melody","Quality":"4K","sound":"DolbyAtmos"}]}';
let VZMData = '{"theater":[' +
'{"TheaterName":"Srikanya","Quality":"4K","sound":"DolbyAtmos" },' +
'{"TheaterName":"kameswari","Quality":"4K","sound":"DolbyAtmos" },'+
'{"TheaterName":"IMAX","Quality":"4K","sound":"DolbyAtmos"}]}';
function search() {
document.getElementById('th').innerHTML = myfunction();
function myfunction() {
var value = document.getElementById('ct').value;
var th1 = document.createElement('div');
document.getElementById('th').appendChild(th1);
th1.innerHTML = "theaters in " + value;
return th1.innerHTML;
}
}
function data() {
var index = document.getElementById('ct');
var demo = document.getElementById("demo");
if(index.value === "vizag"){
const obj = JSON.parse(VizagData);
demo.innerHTML = obj.theater[0].TheaterName + " : " + obj.theater[0].Quality + "," + obj.theater[0].sound + "<br>" + obj.theater[1].TheaterName + " : " + obj.theater[1].Quality + "," + obj.theater[1].sound + "<br>" + obj.theater[2].TheaterName + " : " + obj.theater[2].Quality + "," + obj.theater[2].sound;
}
else {
const obj = JSON.parse(VZMData);
demo.innerHTML = obj.theater[0].TheaterName + " : " + obj.theater[0].Quality + "," + obj.theater[0].sound + "<br>" + obj.theater[1].TheaterName + " : " + obj.theater[1].Quality + "," + obj.theater[1].sound + "<br>" + obj.theater[2].TheaterName + " : " + obj.theater[2].Quality + "," + obj.theater[2].sound;
}
}
var go = document.getElementById('go');
addEventListener('click', search);
addEventListener('click', data);
<select id="ct">
<option value="vizianagaram">vizianagaram</option>
<option value="vizag">vizag</option>
</select>
<button id="go">GO</button>
<div class="th" id="th"></div>
<div id="demo"></div>

Pagination from Ajax response

I'm trying to fetch data from JSON response in a datatable and it works fine. My next step is to add a pagination for all rows. Since I'm using Laravel I've earlier used Laravels built-in system:
{{ $var->links() }}
Now since I'm receiving the response from a POST request to filter out dates, I'm struggling with filtering amount of rows per page. I've tried to Google around without and couln't find a good answer.
I'm a beginner in JavaScript and some support would really help!
This is my code ATM:
$("#date").ready(function() {
$("#date").on('change', function() {
var date = $("#date").find(':selected').val();
var token = $("input[name='_token']").val();
$(document).on('click', '.pagination a', function(event) {
event.preventDefault();
var page = $(this).attr('href').split('page=')[1];
fetch_data(page);
});
$.ajax({
url: "{{ route('mydata') }}",
type: "POST",
data: {
'date': date,
'_token': token
},
dataType: "json",
success: function(data) {
console.log(data);
function status() {
if (data[i].status = 1) {
return '<td class="px-4 py-4"><span class="bg-yellow-500 font-semibold text-white p-2 rounded">Active</span></td>';
}
if (data[i].status = 2) {
return '<td class="px-4 py-4"><span class="bg-blue-500 font-semibold text-white p-2 rounded">Closed</td>';
}
}
function formatDate(date) {
var date = new Date(date);
var yyyy = date.getFullYear().toString();
var mm = (date.getMonth() + 1)
.toString(); // getMonth() is zero-based
var dd = date.getDate().toString();
var h = date.getHours().toString();
var h = ("0" + h).slice(-2);
var m = date.getMinutes().toString();
return yyyy + '-' + (mm[1] ? mm : "0" + mm[0]) + '-' + (dd[1] ? dd :
"0" + dd[0]) + ' ' + h + ':' + m;
}
function remaining_days(start, end) {
var start = new Date(start);
var end = new Date(end);
const _MS_PER_DAY = 1000 * 60 * 60 * 24;
const s = Date.UTC(start.getFullYear(), start.getMonth(), start
.getDate());
const e = Date.UTC(end.getFullYear(), end.getMonth(), end.getDate());
if (end - start < 0) {
return '<span class="text-red-800 font-bold">Late</span>';
} else {
return Math.floor((e - s) / _MS_PER_DAY) + ' Days left';
}
}
var output = '';
for (var i = 0; i < data.length; i++) {
output += '<tr class="bg-gray-100 text-center">';
output += '<td class="px-4 py-4">New</td>';
output += '<td class="px-4 py-4">' + formatDate(data[i].updated_at) +
'</td>';
output += '<td class="px-4 py-4">' + data[i].title + '</td>';
output += '<td class="px-4 py-4">' + data[i].get_admin.first_name +
' ' + data[i]
.get_admin.last_name + '</td>';
output += '<td class="px-4 py-4">#' + data[i].id + '</td>';
output += '<td class="px-4 py-4">' + remaining_days(data[i].created_at,
data[i].end_date) +
'</td>';
output += status();
output += '</tr>';
}
$('#myticketstable').html(output);
},
error: function(xhr) {
if (xhr.status == 422) {
const errors = JSON.parse(xhr.responseText);
console.log(errors);
$.each(xhr.responseJSON.errors, function(i, error) {
console.log('something went wrong');
});
}
}
});
}).trigger('change');});
Best regards

How can I add a line break in an email body after each row

I've created this script to send the none empty rows of a sheet as an email. So far it sends the email, but it places all the found rows in a single continuous line in the email body.
I've tried placing a line break <br/> in various places in the HTML part of the script but no luck so far.
function sendSheetDataViaEmail() {
var SSID = SpreadsheetApp.openById('1dfgdfgdf').getSheetByName('sheet1');
var lastRow = SSID.getLastRow();
var cell = SSID.getRange(12, 1,lastRow-3,9).getDisplayValues();
var data2D = cell.filter(function(item) {//filter by user Id and by spliting month and year
return item[0] != "" // if not empty
});
Array.prototype.transpose = function() { var a = this; return Object.keys(a[0]).map(function (c) {
return a.map(function (r) { return r[c]; }); }); }
//transpose the array, because getValues() returns an array of rows
data2D = data2D.transpose();
// data2D.splice(1,1); // removes the second column... count starts at 0
//if now you need an array or rows again, just transpose again
data2D = data2D.transpose();
var L = data2D.length;
var html = "";
html = "<table id='loadListOfFaturasDeHojeTable' class='order-table table dark3Dtable'> <thead><tr>
<th '>F. ID 🔃</th><th>Trans ID</th> <th>C. ID</th> <th >C. NOME</th> <th >CODDIGO</th> <th >NU DE
SERIE</th> <th >VALOR</th><th >DATA</th> </tr> </thead> <tbody>";
for (var i=0;i<L;i++) {
var thisRow = data2D[i];
var rowHTML = "";
rowHTML = "<tr>";
var rowHTML0 = '<td style="color: red;">'+ thisRow[0] + '</td>'
var rowHTML1 = '<td >'+ thisRow[1] + '</td>'
var rowHTML2 = '<td >'+ thisRow[2] + '</td>'
var rowHTML3 = '<td >'+ thisRow[3] + '</td>'
var rowHTML4 = '<td >'+ thisRow[4] + '</td>'
var rowHTML5 = '<td >'+ thisRow[5] + '</td>'
var rowHTML6 = '<td >'+ thisRow[6] + '</td>'
var rowHTML7 = '<td >'+ thisRow[7] + '</td>'
var rowHTML8 = '<td ">'+ thisRow[8] + '</td>'
rowHTML = rowHTML0 +rowHTML1+rowHTML3 + rowHTML4 + rowHTML5 + rowHTML6 + rowHTML7 + rowHTML8 +
"</tr><br/>";
html = html + rowHTML ;
}
// Logger.log('html: ' + html)
html = html + "</table>";
var settings = {
mailTo: SSID.getRange('J3')//email address
.getValue(),
subject: SSID.getRange('J4')
.getValue(),
body: html,
}
MailApp.sendEmail(settings.mailTo, settings.subject,"" , {
htmlBody: settings.body,
});
}
Try it this way:
function sendSheetDataViaEmail() {
var ss=SpreadsheetApp.openById('ssid');
var sh=ss.getSheetByName('sheet1');
var lastRow=sh.getLastRow();
var vA=sh.getRange(12, 1,sh.getLastRow()-11,9).getDisplayValues().filter(function(item){return item[0]});
var html="";
html='<table id="loadListOfFaturasDeHojeTable" class="order-table table dark3Dtable"><tr><th>F.ID 🔃</th><th>TransID</th><th>C.ID</th><th>C.NOME</th><th>CODDIGO</th><th>NUDESERIE</th><th>VALOR</th><th>DATA</th></tr>';
for(var i=0;i<vA.length;i++) {
html+='<tr><td style="color:red;">'+ thisRow[0] + '</td><td >'+ thisRow[1] + '</td><td >'+ thisRow[2] + '</td><td >'+ thisRow[3] + '</td>';
html+='<td >'+ thisRow[4] + '</td><td >'+ thisRow[5] + '</td><td >'+ thisRow[6] + '</td><td >'+ thisRow[7] + '</td>'<td ">'+ thisRow[8] + '</td>';
}
MailApp.sendEmail(sh.getRange('J3').getValue(),sh.getRange('J4').getValue() ,"",{htmlBody:html});
}

i want to use ajax variable in other function

I want to use modal, so i get the data value from ajax.
the data is like that [{'source_name': '인터넷', 'description': '여행자료', 'source_slug': '_1', 'subject_name': '여행', 'subject_slug': '_6'}]
I want to put the value of source_name "인터넷" to source_name variable.
I want to use soure_name variable at this line.
html += '<li><span> 출처 : ' + source_name + ''
but source_name is undefined.
please help me
this is code.
function showModal(){
var pk = $(this).find('img').attr('id');
$.ajax({
url : '/photo/' + pk + '/',
async: false,
success: function(data){
data= JSON.stringify(data)
var source_slug = data[0]["source_slug"];
var source_name = data[0]["source_name"];
var description = data[0]["description"];
var subject_slug = data[0]["subject_slug"];
var subject_name = data[0]["subject_name"];
}
});
var src = $(this).find('img').attr('src');
var largeImg = $(this).find('img').attr('data-bsp-large-src');
if(typeof largeImg === 'string'){
src = largeImg;
}
var index = $(this).attr('data-bsp-li-index');
var ulIndex = $(this).parent('ul').attr('data-bsp-ul-index');
var ulId = $(this).parent('ul').attr('data-bsp-ul-id');
var theImg = $(this).find('img');
var pText = $(this).find('.text').html();
var modalText = typeof pText !== 'undefined' ? pText : 'undefined';
var alt = typeof theImg.attr('alt') == 'string' ? theImg.attr('alt') : null;
clicked.img = src;
clicked.prevImg = parseInt(index) - parseInt(1);
clicked.nextImg = parseInt(index) + parseInt(1);
clicked.ulIndex = ulIndex;
clicked.ulId = ulId;
$('#bsPhotoGalleryModal').modal();
var html = '';
var img = '<img src="' + clicked.img + '" class="img-responsive"/>';
html += img;
html += '<span class="' + settings.iconClose + ' bsp-close"></span>';
html += '<div class="bsp-text-container">';
html += '<li><span> 출처 : ' + source_name + ''
html += '</span></li>'
html += '<li><span> 과목 및 단원 :' + subject_name + ''
html += '<li><span>' + description + '</span></li>'
html += '</div>';
html += '<a class="bsp-controls next" data-bsp-id="'+clicked.ulId+'" href="'+ (clicked.nextImg) + '"><span class="' + settings.iconRight + '"></span></a>';
html += '<a class="bsp-controls previous" data-bsp-id="'+clicked.ulId+'" href="' + (clicked.prevImg) + '"><span class="' + settings.iconLeft + '"></span></a>';
$('#bsPhotoGalleryModal .modal-body').html(html);
$('.bsp-close').on('click', closeModal);
showHideControls();
}
You need to make the change inside success not after:
function showModal(){
var pk = $(this).find('img').attr('id');
$.ajax({
url : '/photo/' + pk + '/',
async: false,
success: function(data){
data= JSON.stringify(data)
var source_slug = data[0]["source_slug"];
var source_name = data[0]["source_name"];
var description = data[0]["description"];
var subject_slug = data[0]["subject_slug"];
var subject_name = data[0]["subject_name"];
var src = $(this).find('img').attr('src');
var largeImg = $(this).find('img').attr('data-bsp-large-src');
if(typeof largeImg === 'string'){
src = largeImg;
}
var index = $(this).attr('data-bsp-li-index');
var ulIndex = $(this).parent('ul').attr('data-bsp-ul-index');
var ulId = $(this).parent('ul').attr('data-bsp-ul-id');
var theImg = $(this).find('img');
var pText = $(this).find('.text').html();
var modalText = typeof pText !== 'undefined' ? pText : 'undefined';
var alt = typeof theImg.attr('alt') == 'string' ? theImg.attr('alt') : null;
clicked.img = src;
clicked.prevImg = parseInt(index) - parseInt(1);
clicked.nextImg = parseInt(index) + parseInt(1);
clicked.ulIndex = ulIndex;
clicked.ulId = ulId;
$('#bsPhotoGalleryModal').modal();
var html = '';
var img = '<img src="' + clicked.img + '" class="img-responsive"/>';
html += img;
html += '<span class="' + settings.iconClose + ' bsp-close"></span>';
html += '<div class="bsp-text-container">';
html += '<li><span> 출처 : ' + source_name + ''
html += '</span></li>'
html += '<li><span> 과목 및 단원 :' + subject_name + ''
html += '<li><span>' + description + '</span></li>'
html += '</div>';
html += '<a class="bsp-controls next" data-bsp-id="'+clicked.ulId+'" href="'+ (clicked.nextImg) + '"><span class="' + settings.iconRight + '"></span></a>';
html += '<a class="bsp-controls previous" data-bsp-id="'+clicked.ulId+'" href="' + (clicked.prevImg) + '"><span class="' + settings.iconLeft + '"></span></a>';
$('#bsPhotoGalleryModal .modal-body').html(html);
$('.bsp-close').on('click', closeModal);
showHideControls();
}
});}

HTML response in JSON

I have a JSON file such as
[
{
"heading":"Apprenticeship Pathways",
"image":"http:\/\/www.domain.co.uk\/dfdf\/dfdf/images\/content\/join_our_team\/01.png",
"columns":[
{
"data":"<p>Curabitursapienligulasuscipitneccondimentu mneclaciniaavelitCraslaciniaodiositametvel itpellentesquefringillaPellentesquedapibus0 purusvitaemetusultricesultricesCrasvelorci mneclaciniaavelitCraslaciniaodiositametvel velitinhendreritarcicesultricesCrasvelorci5. velitinhendreritarcicesultricesCrasvelorci5.<\\p>"
},
The problem being when inputting the column data, "<\p>" is visible on screen, I.e. the escaped slash is not being removed.
function json_request( url, callback ) {
$.ajax({
url: url,
dataType: 'json',
success: function( data ) {
callback( data );
},
error : function(){
callback( false );
}
});
}
function build_html( $obj ) {
var $firstCol = $obj.columns.shift();
var $columns = '';
for( var i in $obj.columns ) {
$columns += '<div class="hori-con">';
$columns += $obj.columns[i].data;
$columns += '</div>';
}
var $return =
' <li>' +
' <div class="gridRow cf">' +
' <div class="twelveCol last">' +
' <div class="cf hori-con-inner">' +
' <div class="hori-con">' +
' <img src="' + $obj.image + '">' +
' <h3>' + $obj.heading + '</h3>' +
$firstCol.data +
' open' +
' </div>' +
$columns +
' <div>' +
' </div>' +
' </div>' +
' </li>';
return $return;
}
function filter_jobs(){
$('#join_our_team .sub-heading-bar a.nav-box').bind($bind , function(){
var $this = $(this),
$qsKey = 'filter',
$href = $this[0].href,
$basename = $href.split('?' + $qsKey + '=')[1],
$dataContainer = $('#joinOurTeamScroller ul.thelist');
if( typeof $basename !== 'undefined' ) {
json_request('./json/' + $basename + '.json', function( $data ){
$html = '';
if( $data !== false ) {
$.each( $data, function(key, val) {
$html += build_html( val );
});
}
$dataContainer.html($html);
});
}
return false;
});
}
Is there a standardised way of doing this or do I need to search and replace the slashes?