How do I change my class data when ajax is successful? - javascript

I am currently working on a project with spring.
My problem is to check Flug and change the value of the class. Data changes properly when refreshed, but does not change when it is brought to the screen via history.back().
How can I change my data?
function get_push_list(pushdata) {
var listdata = pushdata.map(function(obj){
var html = '<li onClick="linkDetail('+obj.push_seq +','+obj.seq_no +')">'
+ '<div class="timeline-wrapper">'
if (obj.flug != "N" ) {
html += '<label class="timeline-label">'+ obj.type +'</label>';
} else {
html += '<label class="timeline-label not-read" id="timeline'+ obj.seq_no +'" >'+ typedata +'</label>'
}
html += '<div class="timeline-title">'+ obj.title +'</div>'
+ '<div class="timeline-content">'+ obj.body +'</div>'
+ '<div class="timeline-time">'+ obj.reg_date +'</div>';
return html;
});
$('#pushlist').append(listdata);
}
...
function linkDetail(push_seq_no,seq_no) {
var timelineid = document.getElementById("timeline" +seq_no);
var data = {};
data.seq_no = seq_no;
data.flug = "Y";
$.ajax({
url : "/update_status",
type : "POST",
dataType : "json",
data: data,
success : function(result) {
if(result.resultCode == "S000"){
timelineid.class = "timeline-label"
location.href= '/NoticeDetail?' + push_seq_no
} else {
alert(result.resultCode,result.resultMsg);
}
}
});
}

In Ajax Success method Remove
timelineid.class = "timeline-label"
And Add (This is for add a new class to your tag)
timelineid.classList.add('timeline-label');
This is for remove old class from your tag.
timelineid.classList.remove('Class name you want to remove');

Related

i want to seperate a function into a multiple function jquery/ajax

I have a JavaScript file that has an Ajax function which calls a JSON file from an online server to extract it's data and interpret it in to a generated table... I want to separate the generate link, generate date, identify the car plate type/country into multiple functions that can be called by the ajax function.
// table of the server's data from JSON file
$(document).ready(function() {
$.ajax({
url: "http://127.0.0.1:3737/anpr?nb=0",
type: "GET",
dataType: "json",
success: function(data) {
var detection_data = '';
// generating the table to interpret the json data
$.each(data, function(key, value) {
detection_data += '<div class="table-row">';
detection_data += '<div class="serial">' + value.id + '</div>';
// identifie the car plate type/country fron json data
var plateType = value.plateType
if (plateType == "1") {
detection_data += '<div class="country">Tunisie TN</div>';
} else if (plateType == "2") {
detection_data += '<div class="country">Tunisie RS</div>';
} else if (plateType == "3") {
detection_data += '<div class="country">Tunisie GOV</div>';
} else if (plateType == "4") {
detection_data += '<div class="country">Lybie</div>';
} else if (plateType == "5") {
detection_data += '<div class="country">Algerie</div>';
} else {
detection_data += '<div class="country">Autre</div>';
}
detection_data += '<div class="visit">' + value.plateNumber + '</div>';
// generate date from json data
detection_data += '<div class="percentage">' + value.date.substr(8, 2) +
'/' + value.date.substr(5, 2) + '/' + value.date.substr(0, 4) +
' ' + value.date.substr(11, 2) + ':' + value.date.substr(14, 2) + ':' + value.date.substr(17, 2) + '</div>';
// generate link
detection_data += '<div>' + '<a class="img-pop-up" href="http://127.0.0.1:3737/anpr/snapshot?year=' + value.date.substr(0, 4) +
'&month=' + value.date.substr(5, 2) + '&day=' + value.date.substr(8, 2) +
'&&hour=' + value.date.substr(11, 2) + '&minute=' + value.date.substr(14, 2) + '&second=' + value.date.substr(17, 2) +
'&plate=' + value.plateNumber.split(" ").join("_") + '&platetype=' + value.plateType + '">link to picture</a>' + '</div>';
detection_data += '</div>';
});
$('#detection_table').append(detection_data);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I tried to make your code more modular and readable. Here's what I could come up with. I am posting only relevant sections of your code to be concise.
NOTE: This is just a recommendation,I have not tested the below code.
var detection_data = '';
// generating the table to interpret the json data
$.each(data, function(key, value) {
detection_data += '<div class="table-row">';
detection_data += getPlateIDHTML(value.id);
// identifie the car plate type/country fron json data
detection_data += getPlateTypeCountryHTML(value.plateType);
// Plate number
detection_data += getPlateNumberHTML(value.plateNumber);
// generate date from json data
detection_data += getDetectionDateHtml(value.date);
// generate link
detection_data += getSnapshotLink(value.date, value.plateNumber, value.plateType);
detection_data += '</div>';
});
$('#detection_table').append(detection_data);
Below are my functions
String.prototype.format = function () {
var a = this, b;
for (b in arguments) {
a = a.replace(/%[a-z]/, arguments[b]);
}
return a; // Make chainable
};
function parseStringAsJSDate(date_as_string) {
return new Date(date_as_string);
}
function getPlateIDHTML(id) {
var plate_id_html = '<div class="serial">%s</div>';
return plate_id_html.format(id);
}
function getPlateNumberHTML(plateNumber) {
var plate_number_html = '<div class="visit">%s</div>';
return plate_number_html.format(plateNumber);
}
function getPlateTypeCountryHTML(plateType) {
var plateTypeCountry = {
"1": "Tunisie TN",
"2": "Tunisie RS",
"3": "Tunisie GOV",
"4": "Lybie",
"5": "Algerie",
};
var plate_type_country_html = '<div class="country">%s</div>';
if(plateType in plateTypeCountry) {
return detection_data_html.format(plateTypeCountry[plateType]);
} else {
return detection_data_html.format("Autre");
}
}
function getDetectionDateHtml(captured_date_as_string) {
var date_of_capture_html = '<div class="percentage">%s/%s/%s %s:%s:%s</div>';
var captured_date = parseStringAsJSDate(captured_date_as_string);
return date_of_capture_html.format(captured_date.getDate(), captured_date.getMonth()+1, captured_date.getFullYear(), captured_date.getHours(), captured_date.getMinutes(), captured_date.getSeconds());
}
function getSnapshotLink(captured_date_as_string, plateNumber, plateType) {
var snapshot_link = "http://127.0.0.1:3737/anpr/snapshot?year=%s&month=%s&year=%s&day=%s&hour=%s&minute=%s&second=%s&plate=%s&platetype=%s";
var snapshot_link_html = '<div><a class="img-pop-up" href="%s">Link to picture</a></div>';
var captured_date = parseStringAsJSDate(captured_date_as_string);
var snapshot_link = snapshot_link.format(captured_date.getDate(), captured_date.getMonth()+1, captured_date.getFullYear(), captured_date.getHours(), captured_date.getMinutes(), captured_date.getSeconds(), plateNumber.split(" ").join("_"), plateType);
return snapshot_link_html.format(snapshot_link);
}
Below is a brief explanation of each function
String.prototype.format: This is an equivalent of the old-school printf in C. I find variable-substitutions of the sort '<div class="serial">'+ id +'</div>' inter-mingling HTML with JavaScript very difficult to read. And therefore this.
parseStringAsJSDate: I assume that your API is under your control. I recommend you to modify the date format to ISO8601 so that it can be parsed by JavaScript as a Date. Your substr function again affects readability.
getPlateIDHTML & getPlateNumberHTML: Simple functions that just use the format function to embed the passed variables into the HTMLs to show ID and plate number.
getPlateTypeCountryHTML: I used a Python object here to reduce the number of ifs and else ifs.
getDetectionDateHtml & getSnapshotLink: I have tried to parse the date as a JavaScript date and this eliminates the substrs. Moreover, the use of format simplifies these functions further.
Let me know your suggestions on this. Suggestions/Criticism from Stack's gurus are more than welcome :)
UPDATE
Please check my updated format function. I sourced it from this excellent answer. Apologies, the earlier one was just copy-pasted, I should have tried it. Please just the format function to the one that's indicated and let me know

jQuery mobile mega dropdown adds more and more buttons

I am using a jquery plugin to generate a mega dropdown on my mobile website:
The menu is generated dynamically: everytime the user clicks on the right arrow, an api call is made to gather all sub-points to the clicked menu-entry. Down the menu everything works fine, but when I click on "back" it seems that there is added a forward/back-button for each menu-level:
This is my code:
// Catching the click-event
$(document).on('click','.next-button', function(){
var subCatContainer = $(this).next('.subcats');
var current = $(this).parent('.shopCatWithSub');
var categoryid = current.data('categoryuuid');
console.log('Next clicked');
console.log(categoryid);
if(typeof categoryid !== "undefined"){
buildSubcats(categoryid, subCatContainer, standardUrl);
} else {
console.log("No category set!");
}
});
// Get subcategories from API:
function buildSubcats(catid, subCatContainer, standardUrl) {
$.ajax({
type: 'GET',
url: 'https://my-awesome-url.de/api?category-id=' + catid,
dataType: 'jsonp',
contentType: 'application/json',
success: function (data) {
handleResponse(data, subCatContainer, standardUrl);
},
error: function(XMLHttpRequest, textStatus, errorThrow) {
console.log(errorThrow);
if (jQuery.isFunction(callback)) {
}
}
});
}
// Build and add new nav-elements:
function handleResponse(data, subCatContainer, standardUrl){
var output = '';
$.each(data, function(key, category){
var element = '';
var uladd = "";
var aClassAdd = "";
if(category.hasSubcategories) {
uladd = '<ul class="subcats"></ul>';
aClassAdd = 'has-next-button';
}
element = '<li class="shopCatWithSub" data-categoryuuid="' + category.categoryUUID + '">'
+ '<a class="text-truncate menu-item ' + aClassAdd + '" href="' + standardUrl + category.categoryUUID + '">'
+ '<i class="icon-' + category.categoryIconClass + ' mr-2"></i>'
+ category.displayName
+ '</a>'
+ uladd
+ '</li>';
output += element;
});
subCatContainer.empty();
subCatContainer.html(output);
// Re-initialize menu
$('.nav-mobile').mobileMegaMenu();
}
I assume that there is a problem with the re-initializing of the complete menu-structure. But I can't figure out how to handle it.

display value (label name) of the clicked item

i have a page with clickable divs that has been populated dynamically with Json. The divs contains list of items, and when i click on a specific one, i get a new page that contains the name and details of the clicked item.
My issue is that i can't figure out how to display the label (name) of the item cliked, if you can give some help. Many thanks !
Here is my JSON array:
$data['dataHeader'] = array('id', 'Name', 'Value');
$data['dataJson'] = array(
array('id1', 'Jeans', 'blablablabla'),
array('id2', 'Leather Jacket', 'some random description'),
array('id3', 'Suede Boots', 'description of boots')
);
Here is what i tried to do :
(function( $ ) {
// Plugin to clickable element
$.fn.infoClickable = function() {
this.each(function() {
// get the object
var elm = $( this );
// Define click event
elm.on("click", function(){
//Get info relative to clicked element
var currentPage = elm.data("page");
loadPage_X_Content(elm);
});
});
}
// Load page 1
loadPage1Content();
// Application du plug-in
$('.clickableDiv').infoClickable();
}( jQuery ));
function loadPage_X_Content(elm){
var nextPage = currentPage + 1;
var nextPageName = '#LV' + nextPage +'Content';
arrayOfData = reponseData;
currentValue = arrayOfData;
var elm = $( this );
var elmID = elm.attr("id");
var PageContent = '';
PageContent += '<div>' + elmID + '</div>';
$.ajax({
url : "Pages/index.php",
type: 'GET',
dataType: 'json',
data: 'action=loadPage' + '&ID=' + elmID,
success: function(reponseData) {
For header :
LVContent += '<div class="HeaderLine">';
$.each(arrayOfData['dataHeader'], function(currentIdx, currentValue)
{
if (currentIdx > 0) PageContent += '<div class="' + arrayOfData[currentIdx] + '">'+ currentValue +'</div>';
});
For data :
$.each(arrayOfData['dataJson'], function(currentIdx, currentValue){
PageContent += '<div class="BlocLine clickableDiv" ';
PageContent += ' id="' + currentIdx + "_" + currentContext + '"';
PageContent += ' >';
// columns
$.each(currentValue, function(currentIdx, currentValueCol){
if (currentIdx > 0){
PageContent += '<div class=" '+ arrayOfData[currentIdx] +' "';
PageContent += ' >'+ currentValueCol +'</div>';
}
});
PageContent += '</div>';
});
$(nextPageName).append(PageContent);
$(nextPageName).find('.clickableDiv').infoClickable();
});
The code included does not specify what elm is.
So just to clarify, is your elm:
var elm = document.getElementById('theAttrDivId');
?
Also you're asking for the name but searching for the ID, so make sure it's:
var elmID = elm.attr("name");

manipulate partial view's content with jquery

With the code below I am trying to update PartialView's HTML.
open_Modal_AssignAmendRoles = function (url) {
$.ajax({
url: url,//PartialView URL
cache: false,
type: "POST",
dataType: "html",
success: function (data, textStatus, XMLHttpRequest) {
var modalhtml = data;
var result = datafetchfunction("action URL", )
if (result.compleate == true) {
result.data.employeeroles.forEach(function (roletype) {
var tagbox = $(modalhtml).find("#tagbox" + roletype.clientroletypeid);
var span = $(modalhtml).find("#rolecontainer" + roletype.clientroletypeid);
var roletypeid = roletype.clientroletypeid
roletype.roles.forEach(function (role) {
var roleid = role.FK_ClientRoleID
var roledescription = role.ClientRole_Description;
var rolecode = role.ClientRole_Code
var markup = ""
markup += " <li class='taglist' id='" + roleid + "'>"
markup += " <button onclick='$(this).parent().remove()' class='tagclose'>"
markup += " <span class='glyphicon glyphicon-remove' aria-hidden='true'></span>"
markup += " </button>"
markup += " <a class='assignedrole' href='Javascript:void(0);' onclick='pop_click_fn(this)'"
markup += " role-id='" + roleid + "' role-type-id=" + roletypeid + ""
markup += " data-toggle='popover' data-trigger='hover' data-content='" + roledescription + "' data-placement='top' > " + rolecode + " </a>"
markup += " </li>";
$(span).append(markup)
})
})
openModal( modalhtml);
}
}
});
}
Step 1:
On button click the open_Modal_AssignAmendRoles() function is called. Then it goes to the success() function.
Step 2:
var result = datafetchfunction("action URL" )
this fetch data as JSON format
Step 3:
Then I start some loop, I already create some spans and find them with
var span = $(modalhtml).find("#rolecontainer" + roletype.clientroletypeid);
Step 4:
then I build a markup and assign this
$(span).append(markup)
and finally, call
openModal( modalhtml);
But modalhtml is not updated as expected, it means lis which I created with loop is not added.
Can someone tell me what is the problem and how to solve this?

Javascript or Jquery to get div by key of div and change value of it

I have a list of tables.
var tables = "";
for (var i = 0; i <= data.length - 1; i++) {
if (data[i].current_order == null) {
tables += '<button class="table_btn" value="' + data[i].id + '">' + data[i].table_number + '</div>';
} else {
tables += '<button class="table_selected" key="' + data[i].current_order + '"value="' + data[i].id + '">' + data[i].table_number + '</div>';
}
And tables have two color, when it is busy or not busy. If there is current_order in table, it shows busy. What I want to do is that when a user clicks empty table, it gets table_id, changes class from table_btn to table_selected and add keyof div, which is current_order.
I use phoenix-framework for my backend, so when a user clicks an empty table, it creates order and passes value of clicked table_id and created order_id. But I am not sure that how can I get a table by value of table div and put key into div...
Can anyone give me advice for this??
So as you tagged Jquery, i'm gonna post this. Change key for ID and you can do the following. I would then wrap the add table and remove table in functions where u pass in the data[i].current_order into and use that.
Edited based on user feeback, not tested
/*If you are not comfortable using the variable 'This',
you can just pass in the id of target table and
change the syntax to $("#"+targetTable)*/
var tables = "";
for (var i = 0; i <= data.length - 1; i++) {
if (data[i].current_order == null) {
tables += '<button class="table_btn" value="' + data[i].id + '">' + data[i].table_number + '</div>';
} else {
tables += '<button class="table_selected" id="' + data[i].current_order + '"value="' + data[i].id + '">' + data[i].table_number + '</div>';
}
// On Click set table to busy
$(".table_btn").click(function(){
addTable($(this).val(), $(this));
});
// Add table function
function addTable(tableId, targetTable){
$.ajax({
url: "YourBackEndHere",
data: tableID
cache: false,
success: function(html){
$(targetTable).removeClass("table_btn");
$(targetTable).addClass("table_selected");
$(targetTable).attr("id", data[i].current_order);
}
});
}
// On click set table to empty
$(".table_selected").click(function(){
removeTable($(this).val(), $(this));
});
// Remove table function
function removeTable(tableId, targetTable){
$.ajax({
data: tableId
url: "YourBackEndHere",
cache: false,
success: function(html){
$(targetTable).removeClass("table_selected");
$(targetTable).addClass("table_btn");
$(targetTable).attr("id", "");
});
}
});
}

Categories