AJAX: JSON loop that duplicate the same result - json

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>

Related

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

Parsing and displaying JSON data

I am looking to display the data from my JSON file. The data I would like to display is the title from my JSON file however I am unsure of how to parse it. I think the part I am getting wrong is the 'data[i].archives.year1.title' etc but I am unsure of how to solve this.
This is what I have already tried:
My JSON file
[
{
"archives": {
"year1": {
"title": "Sample Title 1"
},
"year2": {
"title": "Sample Title 2"
},
"year3": {
"title": "Sample Title 3"
}
},
"collections": {
"health": {
"title": "Sample Title 4"
},
"money": {
"title": "Sample Title 5"
},
"relationships": {
"title": "Sample Title 6"
}
}
}
]
HTML
<div class="archives"></div>
<div class="collections"></div>
JavaScript file
fetch('example.json')
.then(function (response) {
return response.json();
})
.then(function (data) {
appendData(data);
})
.catch(error => console.log('Looks like there was a problem: ', error));
function appendData(data) {
var mainContainer = document.getElementById("archives");
for (var i = 0; i < data.length; i++) {
var div = document.createElement("div");
div.innerHTML =
'<span class="archives">' + data[i].archives.year1.title + '</span>' +
'<span class="archives">' + data[i].archives.year2.title + '</span>' +
'<span class="archives">' + data[i].archives.year3.title + '</span>';
mainContainer.appendChild(div);
}
}
function appendData(data) {
var mainContainer = document.getElementById("collections");
for (var i = 0; i < data.length; i++) {
var div = document.createElement("div");
div.innerHTML =
'<span class="collections">' + data[i].collections.health.title + '</span>' +
'<span class="collections">' + data[i].collections.money.title + '</span>' +
'<span class="collections">' + data[i].collections.relationships.title + '</span>';
mainContainer.appendChild(div);
}
}
I expect the output to display all of the titles from "archives" and all of the titles from "collections". I am new to JavaScript.
Your for loops here:
for (var i = 0; i < data.length; i++) //archives
for (var i = 0; i < data.length; i++) //collections
should be:
for (var i = 0; i < data.archives.length; i++) //archives
for (var i = 0; i < data.collections.length; i++) //collections
then you can reference values with:
div.innerHTML =
'<span class="archives">' + data.archives[i].year1.title + '</span>' +
'<span class="archives">' + data.archives[i].year2.title + '</span>' +
'<span class="archives">' + data.archives[i].year3.title + '</span>';
Also bonus points for looking into VueJS or ReactJS and also learning to use console.log in your browser's debug tools.
Edit:
After reading your comment and re-reading your JSON file I realize you have it nested inside an array. You can either delete the square brackets containing your object you intend to use, or use:
for (var i = 0; i < data[0].collections.length; i++)
'<span class="archives">' + data[0].archives[i].year1.title + '</span>'
The square brackets create an array containing the object you are trying to access, where you could append more objects, but since you're using an object of objects already the array containing it seems redundant.

Token Input Ondelete is not working

I have a form where i have used token input plugin to select multiple items from a predefined list. However Ondelete function is not working.
<script type="text/javascript">
$(document).ready(function() {
var1_ids = '<?php echo $records[0]['team_member']?>';
$("#team_member").tokenInput("<?php echo base_url(); ?>staff_activity/get_members", {
theme: "facebook",
prePopulate: [<?php echo $show1; ?>],
resultsFormatter: function(item){ return "<li>" + " " + "<div style='display: inline-block; padding-left: 5px;'><div class='full_name'>" + item.first_name + "</div></div></li>" },
tokenFormatter: function(item) { return "<li><p>" + item.first_name + "</p></li>" },
onAdd: function (item) {
var1_ids = var1_ids + item.staff_id + ',';
$('#team_member_ids').val(var1_ids);
},
onDelete: function (item) {
var1_ids = var1_ids.replace(item.staff_id+',','');
$('#team_member_ids').val(var1_ids);
}
});
});
</script>
where var_dump($records[0]['team_member']?>); is string(11) ",900,4,979,"

Sort JSON data by Date/Time value

Hope someone could help with this small task. I have an array of text blocks that have a DateTime value assigned to them. I would like to publish those text blocks sorted by DateTime so that the latest updated item is always on top.
Here is the script:
function jsonCallBack(data) {
var strRows = "";
$.each(data.News, function(i, item) {
var htmlNewsBody = item["htmlNewsBody"];
var maxLength = 120
var trimmedString = htmlNewsBody.substr(0, maxLength);
trimmedString = trimmedString.substr( 0, Math.min( trimmedString.length,
trimmedString.lastIndexOf(" ") ) );
strRows += "<div id='nrNewsItem-" + i + "'>";
strRows += "<h3>" + item["txtTitle"] + "</h3>";
strRows += "<p>" + item["dtDateTime"] + "</p>";
strRows += "<p>" + trimmedString + "...</p>";
strRows += "</div>"
});
$("#printHere").html(strRows);
};
Also have a working jsFiddle with JSON data.
You can add a custom compare method:
function compare(a,b) {
if (a.dtDateTime < b.dtDateTime) {
return 1;
}
if (a.dtDateTime > b.dtDateTime) {
return -1;
}
return 0;
}
Then in your function:
function jsonCallBack(data) {
data.News.sort(compare);
....

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?