Deleted images still being shown - javascript

For some reason, my website still showing images that were already deleted from the specified folder and I have no idea why that's happening and how to solve that.
Process: When the button to delete all admins is pressed, it calls a PHP function that truncate the tables administration, adminimg and login, delete all images from a folder related to id's on table administration with unlink(), and create a registry on administration table with id=1(auto_increment) and name="abc".
Problem: I have a jQuery function that display a specific admin information on textboxes, verify the value in the textbox for the adminID, and display the image associated to that id. After executing the process above, when i call the jQuery function, it display correctly the id=1 and name="abc" but shows the deleted image associated to the admin with id=1 before truncate the tables.
jQuery function (if necessary)
$(".btneditadmin").click( e =>{
let textvalues = displayDataAdmin(e);
let id = $("input[name*='idadmin']");
let name = $("input[name*='nameadmin']");
id.val(textvalues[0]);
nome.val(textvalues[1]);
var img_url = 'Images/Administration/admin'+$("#idadmin").val()+'.jpg';
$("#admin-image").attr('src',img_url);
});
function displayDataAdmin(e) {
let id = 0;
const td = $("#tbody tr td");
let textvalues = [];
for (const value of td){
if(value.dataset.id == e.target.dataset.id){
textvalues[id++] = value.textContent;
}
}
return textvalues;
}

If you're sure that image isn't there anymore then it's caching issue and something like this would take care of it
let img_url = 'Images/Administration/admin'+$("#idadmin").val()+'.jpg';
img_url += '?' + new Date().getTime() ; // cache killer
$("#admin-image").attr('src', img_url);
However, you're calling that function no matter what so I would suggest a onload/error check
​$('#admin-image').load(function(){ // when loaded successfully
console.log('success');
}).error(function(){ // when theres an error
$(this).remove()
// or you could replace it with a default image
$(this).attr('src', '/images/default.jpg');
});​​​​​

Related

Wordpress and JavaScript: trying to hide a button when the product has no sku

I have this situation with my Wordpress site where products with variations are hitting the DOM while missing some inner text on a certain element (which is the same behavior as a product without a sku), but when I console.log the element, the text is there. Here is the code:
const makerBtn = document.getElementById("maker-button");
const sku = document.getElementsByClassName("sku");
const newLink = document.createElement("a");
newLink.innerText = "Buy at Maker's Site";
newLink.className += "fusion-button button-flat fusion-button-default-size button-custom button-3 fusion-button-default-span fusion-button-default-type";
newLink.addEventListener("click", ()=> {
newLink.target = "_blank";
newLink.href = sku[0].innerHTML.toString();
});
makerBtn.appendChild(newLink);
I've added url's to some products in the sku and if they are there, then you click the button and you will be taken to a new site. I've just been trying to find a way to hide the button if it doesn't have a sku, but if I add code like this:
if (sku[0].innerHTML === "") {
newLink.style.display = "none";
}
It will work except the button is hidden for products that have variations too (they have a dropdown menu and you can choose between different colors, etc.) because the sku[0].innerHTML is hitting the DOM as an empty string even though I console log it and the url is there.
I can't figure out which property of these variable products I can add to a conditional so that these pages behave differently. Thank you for any help.
Maybe you can try:
if (sku[0].innerHTML === "") {
newLink.style.opacity= "0.0";
}

Multiplication of two input table element values on html form row not working (Google Webapp)

I am trying to create an order form as a table, where a user enters a quantity required for a product in a row and the corresponding value is calculated by multiplying the user entry by the price held in another element of the same row of the table.
The form is loaded as a WebApp via Google and uses an Apps Script to retrieve the table values from a Google Sheet. The form loads OK with the data as expected but I just can't get the calculation part to work.
If I click the "place Order" button at the bottom of the form, the numberUsed values are included as parameters in the URL so it looks as though the values are updating in those elements but I haven't been able to access them to do the calculation and display it in the element called "value".
I am a novice programmer so I am sure it is something basic I am doing wrong (or not doing). I have created a JSBin https://jsbin.com/siwerat/edit?html,js,console,output and I have tried several variations of code derived from other answers and videos over the last couple of weeks without success so any help will be much appreciated.
//var numRows;
document.addEventListener('DOMContentLoaded', function() {
//new
var elems = document.querySelectorAll('cart');
var instances = M.FormSelect.init(elems);
// end new
document.getElementByname("cart").addEventListener("submit", getValues); //used to submit form - needs validation
//document.getElementByName("numberUsed").addEventListener("oninput",getValues);//used to submit form - needs validation
});
function test(event) {
"use strict";
event.preventDefault();
console.log("getValues function triggered");
}
function getValues() {
event.preventDefault();
var rows = document.querySelectorAll("package-row");
rows.forEach(function(currentRow) {
var numberUsed = Number(currentRow.querySelector('#numberUsed').value);
var price = Number(currentRow.querySelector('#price').value);
//var inPackage = Number(currentRow.querySelector('#inPackage').value);
var inPackage = 1;
var revenue = 1;
document.querySelectorAll('numberUsed');
if (numberUsed == "") {
if (isNaN(inPackage) || isNaN(price)) {
return;
}
revenue = price * inPackage;
} else {
if (isNaN(numberUsed) || isNaN(price)) {
return;
}
revenue = price * numberUsed;
}
var value = revenue * 5;
//currentRow.querySelector("#revenue").innerHTML = revenue;
currentRow.querySelector("#value").innerHTML = value;
});
}
Thanks Rafa for the guidance. After further reading/analysis I have got it working. The Event bubbling video by Learn Google Spreadsheets: [https://www.youtube.com/watch?v=fYpGe5ngujk][1] and an article on EncodeDNA.com (Dynamically create HTML table and Button using Javascript) helped narrow down the issues I had to get a solution.

Creating whole new view based on current user's group sharepoint 2013

I am trying to generate a view based on the current user's group name. Group Name I am gathering from the custom list.
My question is how to apply the gathered group name to 'Group Name' column as a view parameter.
The only solution I figured:
I have created a view with a parameter.
I have added an HTML Form Web Part into the same page and connected it to the list view (sending the value to the parameter via web part connection). Then with a window.onload function I gather the current user's group name and pass this value via Form Postback function. But since the Postback function triggers full page reload, it falls into the endless loop of form submission > page reload.
Another way I have tried is attaching a click event listener to the BY MY GROUPS tab and it works perfectly, but the only disadvantage is that the page reloads each time user clicks on this tab, which I would like to avoid.
So the solution that I need is a way to post the form without a page reload.
Another option suggested here is to use CSR (client side rendering), but that has its own problems:
This code does not work as it is supposed to. In the console it shows me correct items, but the view appears untouchable.
Even if it worked, the other column values are still viewable in the column filter, as in this screenshot:
So, it seems that CSR just hides items from the view (and they are still available). In other words its behavior is different from, for example, a CAML query.
Or am I getting it wrong and there's something wrong with my code?
Below you can find my CSR code:
<script type='text/javascript'>
(function() {
function listPreRender(renderCtx) {
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function() {
var currUserID = _spPageContextInfo.userId;
var cx = new SP.ClientContext('/sites/support');
var list = cx.get_web().get_lists().getByTitle('Group Members');
var items = list.getItems(SP.CamlQuery.createAllItemsQuery());
cx.load(items, 'Include(_x006e_x50,DepID)');
cx.executeQueryAsync(
function() {
var i = items.get_count();
while (i--) {
var item = items.getItemAtIndex(i);
var userID = item.get_item('_x006e_x50').get_lookupId();
var group = item.get_item('DepID').get_lookupValue();
if (currUserID === userID) {
var rows = renderCtx.ListData.Row;
var customView = [];
var i = rows.length;
while (i--) {
var show = rows[i]['Group_x0020_Name'] === group;
if (show) {
customView.push(rows[i]);
}
}
renderCtx.ListData.Row = customView;
renderCtx.ListData.LastRow = customView.length;
console.log(JSON.stringify(renderCtx.ListData.Row));
break;
}
}
},
function() {
alert('Something went wrong. Please contact developer')
}
);
});
}
function registerListRenderer() {
var context = {};
context.Templates = {};
context.OnPreRender = listPreRender;
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(context);
}
ExecuteOrDelayUntilScriptLoaded(registerListRenderer, 'clienttemplates.js');
})();
</script>

On page reload, check boxes get selected and then disappear automatically within a second

I have a problem with a function that i'm writing.
Basically, I'm simulating a landing page. The landing page will contain a querystring. What I'm doing is to deserialize it on a button click and show(to check) the checkboxes defined in the querystring in the HTML.
Below is the click function which contains two functions.
The first one "simulateLandingPage" performs the url change.
The second one called "selectFacetsAutomatically" deserializes the "landingUrl" path and checks automatically the checkboxes in the HTML page according to what is defined in the querystring.
The problem that I'm encountering is that when I click on the "reload-page" button everything works but the checkboxes get selected just for a second and then disappear automatically quickly without any reason. Hence the page won't show the selected checkboxes in the end but just this weird thing.
Can anyone help? I'm pretty new to this and i'm stuck.
Thanks a lot!
$(".reload-page").click(function() {
var landingUrl = "size:4,10,16|base_colour:1,4|brand:53,3392,12767";
simulateLandingPage(landingUrl);
selectFacetsAutomatically(landingUrl);
return false;
});
function simulateLandingPage(landingUrl){
window.location.href = "refinements.html?refine="+ encodeURIComponent(landingUrl);
return false;
}
function selectFacetsAutomatically(landingUrl){
var facetGroup = [];
var selectedFacets = [];
var facetType;
//split string when it finds the pipe symbol
$.each(decodeURIComponent(landingUrl).split(/\|/), function (i, val) {
selectedFacets.push(val);
console.log("val", selectedFacets[i].split(/\:/)[1].split(/\,/));
facetType = selectedFacets[i].split(/\:/)[0];
facetGroup = selectedFacets[i].split(/\:/)[1].split(/\,/);
$.each(facetGroup, function(i,val){
var facetToBeSelected = facetType + "_" + val;
$('[data-id='+facetType+']').find("#"+facetToBeSelected).prop('checked', true);
});
});
return false;
}

JQM - How to get over TypeError: t.data(...) is undefined

In JQuery Mobile, I created a dynamic listview that should create dynamic pages depending on which item is clicked. I managed to get the listview up and running but the dynamic page problem is giving me a headache because of this error:
TypeError: t.data(...) is undefined
...ollapsiblebound",!0).bind("expand collapse",function(t){var n=t.type==="collapse...
I get this on Firebug everytime I try and navigate to a dynamic page. The code I am using to create the listview is this one (and it seems to work fine):
for (i=0; i<contacts_list.length;i++) {
var patient = contacts_list[i];
output += "<li id=" + patient.id + "><a href='#update?patient=" + patient.id + "'><h2>" + patient.name + "</h2><a href='#' data-rel='popup' data-position-to='window' data-transition='pop'></a></li>";
}
}
$("#patlist").append(output).listview("refresh");
And the code I am using to create the pages from clicking in an item from the list view is very similar to the one on this page: http://jquerymobile.com/demos/1.1.1/docs/pages/page-dynamic.html
$(document).bind("pagebeforechange", function (e, data) {
// We only want to handle changePage() calls where the caller is
// asking us to load a page by URL.
if (typeof data.toPage === "string") {
// We are being asked to load a page by URL, but we only
// want to handle URLs that request the data for a specific
// category.
var u = $.mobile.path.parseUrl(data.toPage),
re = /^#update/;
if (u.hash.search(re) !== -1) {
// We're being asked to display the items for a specific category.
// Call our internal method that builds the content for the category
// on the fly based on our in-memory category data structure.
showPatient(u, data.options);
// Make sure to tell changePage() we've handled this call so it doesn't
// have to do anything.
e.preventDefault();
}
}
});
function showPatient(urlObj, options) {
var patientId = urlObj.hash.replace(/.*patient=/, ""),
// Get the object that represents the category we
// are interested in. Note, that at this point we could
// instead fire off an ajax request to fetch the data, but
// for the purposes of this sample, it's already in memory.
patient = JSON.parse(storage.getItem("patients:" + patientId)),
// The pages we use to display our content are already in
// the DOM. The id of the page we are going to write our
// content into is specified in the hash before the '?'.
pageSelector = urlObj.hash.replace(/\?.*$/, "");
if (patient) {
// Get the page we are going to dump our content into.
var $page = $(pageSelector),
// Get the header for the page.
$header = $page.children(":jqmData(role=header)"),
// Get the content area element for the page.
$content = $page.children(":jqmData(role=content)"),
// The markup we are going to inject into the content
// area of the page.
markup = "<p>" + patient.name + "</p><ul data-role='listview' data-inset='true'>",
// The array of items for this category.
cItems = patient.name,
// The number of items in the category.
numItems = 1;
// Generate a list item for each item in the category
// and add it to our markup.
for (var i = 0; i < numItems; i++) {
markup += "<li>" + cItems + "</li>";
}
markup += "</ul>";
// Find the h1 element in our header and inject the name of
// the category into it.
$header.find("h1").html(patient.name);
// Inject the category items markup into the content element.
$content.html(markup);
// Pages are lazily enhanced. We call page() on the page
// element to make sure it is always enhanced before we
// attempt to enhance the listview markup we just injected.
// Subsequent calls to page() are ignored since a page/widget
// can only be enhanced once.
$page.page();
// Enhance the listview we just injected.
$content.find(":jqmData(role=listview)").listview();
// We don't want the data-url of the page we just modified
// to be the url that shows up in the browser's location field,
// so set the dataUrl option to the URL for the category
// we just loaded.
options.dataUrl = urlObj.href;
// Now call changePage() and tell it to switch to
// the page we just modified.
$.mobile.changePage($page, options);
}
}
You forgot to create a static page where you want to append your items to dynamically. You can create a page dynamically if you want this way, before navigating to it, upon selecting a list item.
if ($('body').find('[data-role=page]#update').length === 0) {
$('<div/>', {
'data-role': 'page',
id: 'update',
'data-theme': 'e'
}).appendTo('body');
}

Categories

Resources