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?
Related
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
Problem solved, my json array was badly done.
I had just wrongly done my array in php, so I did it again and everything works.
<?php
$history = array();
$history[] = array('name' => $fetch[$s]['value'], 'url' => $url);
echo json_encode(['history' => $history]);
?>
function load_history() {
$.getJSON(URL + 'load.search.historique.php', function(data) {
if (data.type == 'success') {
for (var i = 0; i < data.history.length; i++) {
$('.search-item-result').append('<div class="search-item"><a name="' + data.history[i].name + '" action="redirect" href="' + data.history[i].url + '">' + data.history[i].name + '</a><i class="fas fa-times"></i></div>');
}
} else if (data.type == 'error') {
$('.search-item-result').html('<div class="search-item">' + data.message + '</div>');
}
});
}
Problem is in your JSON data formatting. Format as shown below, you will get desired output. You can view by run the snippet.
var data = {
"type": "success",
"message": "Permission denied: HTTP Exception",
"history": [
[
"Dr. STONE",
"https://mon-site.fr/watch/117-Dr.-STONE/episode-1/saison-1"
],
[
"One Piece ",
"https://mon-site.fr/watch/27-One-Piece-/episode-1/saison-1"
],
[
"One Piece ",
"https://mon-site.fr/watch/27-One-Piece-/episode-1/saison-1"
]
]
}
function load_history() {
if (data.type == 'success') {
var div = document.getElementById('myDiv');
for (var i = 0; i < data.history.length; i++) {
div.innerHTML += '<div class="search-item"><a name="' + data.history[i][0] + '" action="redirect" href="' + data.history[i][1] + '">' + data.history[i][0] + '</a><i class="fas fa-times"></i></div>';
}
} else if (data.type == 'error') {
div.innerHTML += '<div class="search-item">' + data.message + '</div>';
}
}
load_history();
<div id="myDiv"></div>
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();
}
});}
I have a JSON file and I am trying to reload a function inside my code but I cant seem to get it to work. After you click an item from the page, it shows the items contents etc. At the bottom I have a similar product for each item. What i want to do is reload the page on click of the similar product image and show the correct item on the page but I cant seem to make it work. Any help or suggestions is very much appreciated thanks!
I included a working example below please visit the codepen link:
http://codepen.io/tcarp/pen/aBPLqX
'use strict';
$.ajax({
dataType: "jsonp",
url: '',
success: function(json){
//check for window hash and display product category
var categoryHash = window.location.hash;
switch(categoryHash)
{
case '#tomatoes':
displayTomatoes();
break;
default:
displayAll();
break;
}
//display product category based on click
$("#tomatoes").click(function(event){
displayTomatoes();
event.preventDefault();
window.location.hash = '#tomatoes';
});
$("#displayall").click(function(event){
displayAll();
});
//display all products function
function displayAll() {
var categoryImage = '';
$.each(json, function (i, item) {
categoryImage += '<div class="col-lg-3 col-md-4 col-sm-6 col-xs-12">' + '' + '<img class="img-responsive img-hover productImagesCategory" src="' + item.imageURL + '">' + '<h3>' + item.itemName + '</h3>' + '' + '</div>';
});
$('#imagesCategoryProducts').hide().html(categoryImage).fadeIn('slow');
//show individual product function on click
$(".showProduct").click(function(event){
//hide all current products
$('#productCategories').hide();
//get passed data from other function
var clickedItemName = '<h1>' + $(this).data('itemname') + '</h1>';
var clickedItemUPC = $(this).data('itemupc');
var clickedItemOZ = $(this).data('itemoz')
var clickedItemDescription = '<p>' + $(this).data('itemdescription') + '</p>';
var clickedItemImage = '<img class="img-responsive img-rounded center-block" src="' + $(this).data('itemimage') + '">';
var clickedItemGluten = $(this).data('itemgluten');
var clickedItemBPA = $(this).data('itembpa');
var clickedItemGMO = $(this).data('itemgmo');
var clickedItemLowSodium = $(this).data('itemlowsodium');
var clickedItemOrganic = $(this).data('itemorganic');
var clickedItemPageURL = $(this).data('itempageurl');
//check if clicked data equals correct item
$.each(json, function (i, item) {
if (item.itemName === clickedItemName) {
clickedItemName
}
if (item.itemFullUPC === clickedItemUPC) {
clickedItemUPC
}
if (item.itemPackSize === clickedItemOZ) {
clickedItemOZ
}
if (item.itemDescription === clickedItemDescription) {
clickedItemDescription
}
if (item.imageURL === clickedItemImage) {
clickedItemImage
}
if (item.itemGlutenFree === clickedItemGluten) {
clickedItemGluten
}
if (item.itemBPAFree === clickedItemBPA) {
clickedItemBPA
}
if (item.itemGMOFree === clickedItemGMO) {
clickedItemGMO
}
if (item.itemOrganic === clickedItemOrganic) {
clickedItemOrganic
}
if (item.itemLowSodium === clickedItemLowSodium) {
clickedItemLowSodium
}
//assign window hash to each product
if (item.itemFullUPC === clickedItemPageURL) {
event.preventDefault();
clickedItemPageURL = clickedItemPageURL.replace(/\s/g, '');
window.location.hash = clickedItemPageURL;
}
});
//remove extra characters from UPC
var originalUPC = clickedItemUPC;
var strippedUPC = '<h2>' + originalUPC.slice(1, -1); + '</h2>';
//remove characters after slash from Pack Size
var originalPackSize = clickedItemOZ;
var strippedPackSize = '<h2>' + clickedItemOZ.substring(clickedItemOZ.lastIndexOf("/") + 1); + '</h2>';
//show individual product information
$('#productSocialShare').show();
$('#individualProduct').show();
$('#relatedProducts').show();
//append product information to appropriate DIV
$('#productTitle').html(clickedItemName);
$('#productUPC').html(strippedUPC);
$('#productOZ').html(strippedPackSize);
$('#productDescription').html(clickedItemDescription);
$('#productImage').html(clickedItemImage);
//check if gluten free is true and show image
if (clickedItemGluten == "Y") {
clickedItemGluten = '<img class="img-responsive img-rounded img-margin" src="http://www.cento.com/DEV/images/misc/gluten_free_test.jpg">';
$('#productGlutenFree').html(clickedItemGluten);
$('#productGlutenFree').show();
} else {
$('#productGlutenFree').hide();
}
//check if bpa free is true and show image
if (clickedItemBPA == "Y") {
clickedItemBPA = '<img class="img-responsive img-rounded img-margin" src="http://www.cento.com/DEV/images/misc/bpa_free_test.jpg">';
$('#productBPAFree').html(clickedItemBPA);
$('#productBPAFree').show();
} else {
$('#productBPAFree').hide();
}
//check if gmo free is true and show image
if (clickedItemGMO == "Y") {
clickedItemGMO = '<img class="img-responsive img-rounded img-margin" src="http://www.cento.com/DEV/images/misc/gmo_test.jpg">';
$('#productGMOFree').html(clickedItemGMO);
$('#productGMOFree').show();
} else {
$('#productGMOFree').hide();
}
//check if organic is true and show image
if (clickedItemOrganic == "Y") {
clickedItemOrganic = '<img class="img-responsive img-rounded img-margin" src="http://www.cento.com/DEV/images/misc/organic_test.jpg">';
$('#productOrganic').html(clickedItemOrganic);
$('#productOrganic').show();
} else {
$('#productOrganic').hide();
}
//check if low sodium is true and show image
if (clickedItemLowSodium == "Y") {
clickedItemLowSodium = '<img class="img-responsive img-rounded img-margin" src="http://www.cento.com/DEV/images/misc/low_sodium_test.jpg">';
$('#productLowSodium').html(clickedItemLowSodium);
$('#productLowSodium').show();
} else {
$('#productLowSodium').hide();
}
//show random recipe for each item
var url = 'http://www.cento.com/DEV/recipes.json';
$.getJSON(url, function(json) {
var randomRecipe = json[Math.floor(Math.random() * json.length)];
randomRecipe = '<div>' + '' + '<img class="img-responsive img-hover" src="' + randomRecipe.recipeImageCategoryURL + '">' + '' + '' + '<h3 class="similarProductSubCategoryImgCaption">' + randomRecipe.recipeName + '</h3>' + '' + '</div>';
$('#featuredRecipe').append(randomRecipe);
});
//show similar product
var categoryItems = [];
$.each(json, function(i, item){
if(item.itemCommodity == '1120' && item.itemBrandLetter == "C") categoryItems.push(item);
if(item.itemCommodity == '2120' && item.itemBrandLetter == "C") categoryItems.push(item);
});
var similarProduct= '';
$.each(json, function(i,item){
similarProduct = categoryItems[Math.floor(Math.random()*categoryItems.length)];
similarProduct += '<div>' + '' + '<h3 class="similarProductSubCategoryImgCaption">' + similarProduct.itemName + '</h3>' + '' + '</div>';
});
$('#productSimilar').append(similarProduct);
});
closeNav();
}
}
});
Got this to work. I was able to add the function to the body on click method and pass in all the data from the href. Works!
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