Images not being displayed despite setting attr(src , "") - javascript

<%#val testId:String %>
<%#val platforms:String %>
<body>
<div class = "conatainer">
<div class="page-header">
<h1>Preview of litmus test ${testId } <small> Platforms chosen for preview : </small></h1>
</div>
<div class ="btn-toolbar bnt-toolbar-lg" id = "buttonsPlace"><br>
<img id="imagePlaces">
</div>
</div>
$( document ).ready(function myFunct() {
var platforms = "${platforms}";
var platformList = platforms.split(",");
var btn = new Array(platformList.length);
var image_id = new Array(platformList.length);
var img = new Array(platformList.length);
for(i=0;i<platformList.length;i++)
{
image_id[i]=100*i-1 + "";
console.log(image_id);
btn[i]=document.createElement("button");
img[i]=document.createElement("image");
btn[i].appendChild(document.createTextNode(platformList[i]));
btn[i].appendChild(img[i]);
$("#buttons").append(btn[i]);
btn[i].setAttribute("id",i+"");
btn[i].setAttribute("class","btn btn-success");
img[i].setAttribute("src","");
img[i].setAttribute("id",image_id[i]);
console.log("button id is: "+i+" and image id is :"+image_id[i]);
console.log("hiding");
$("#"+i).hide();
}
var testId = "${testId}";
console.log("hey");
var is_loaded = false;
var delay = 1;
fetchFunct();
function fetchFunct(){
console.log("entered function");
$.ajax
({
type: "GET",
url: "/content/mosaic/multi/preview/status/"+testId ,
async: true,
dataType : "json",
success : function(response)
{
console.log(response);
console.log(response.images);
if(response.status === false)
{
console.log("Processing details");
//show still in progress
$("#load").show();
$("#heading").hide();
delay=delay*2;
if(delay>60)
{delay=1;}
setTimeout(fetchFunct,delay*1000);
}
else
{
$("#load").hide();
$("#heading").show();
var responses = new Array(platformList.length);
/*for (var m in responses.images){
// var responses[]=responses.images[m];
console.log("heyyeyey "+responses[]);
}*/
for(var m in response.images){
i=0;
// console.log(" response image is : "+response.images[m]);
responses[i++]=response.images[m]; }
for(i=0;i<platformList.length;i++)
{
$("#"+i).show();
console.log("image id is : "+image_id[i]);
console.log(platformList[i]);
console.log("Loading :"+i);
$("#"+i).click(function(){
console.log(this.id);
//console.log("the first child is :"+this.children().first().id);
//alert("you clicked the "+platformList[this.id]+" button");
console.log("The response image you are looking for is "+response.images[platformList[this.id]]);
console.log(image_id[this.id]);
$("#"+image_id[this.id]).attr("src","http://" + response.images[platformList[this.id]]);
})
}
is_loaded = true;
}
}
}).fail(function(data) { console.log("FAIL"); }).done(function(data) { console.log("coming out of ajax");});
}
});
I am dynamically creating buttons according to the input in platformList and then on clicking i wish to display the images corresponding to the URLs received through an AJAX request. However though I am not getting an error , the images are not being displayed. The buttons are being correctly displayed; console is showing the correct URLs have been received through ajax BUT images are not getting displayed. I think this could be because of some mistake in me appending img[i] as child of btn [i] or somehow the attr(src,"") is not changing the source attribute properly. Though I think the former is more likely.Please Help :\ Somehow the image is not attaching to the DOM element I think

Related

How to persist data inside div that appended on button click in JSP using JavaScript, Spring Boot?

I have a dropdown list of cities and a button to add city into vendor model. So I want to add selected city name inside div when button clicked each time. For example, I have list of cities in dropdown and suppose I selected Bangalore and when clicked on add button then it should get added inside div and when I refresh the page, div list should be persistence. Which means, when page get reload or refreshed then added city should be displayed inside a div. Currently what I am suffering from is when I reload page then the cities I added after button clicked, gets emptied each time. So I want help regarding this. Any suggestions would be helpful for me.
Below is my api controller code to save selected city into database:
#RequestMapping(value = AkApiUrl.setdeliverycity, method = { RequestMethod.POST, RequestMethod.GET }, produces = { MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<?> setdeliverycity(HttpServletRequest request, HttpSession session, #RequestParam("delivercityid") String delivercityid,
#RequestParam("vendorid") String vendorid) {
CustomResponse = ResponseFactory.getResponse(request);
try {
User loginuser = (User) session.getAttribute("user");
Long vid = Long.parseLong(vendorid);
User vendor = userDao.findByUserid(vid);
String vendorname = vendor.getName();
Long cid = Long.parseLong(delivercityid);
DeliveryCity city = deliverycityDao.findByDelivercityid(cid);
VendorCity vendorCity = new VendorCity();
vendorCity.setVendorcity(city);
vendorCity.setName(vendorname);
vendorCity.setVendorid(vendor);
vendorCity.setCreatedby(loginuser);
VendorCity delivercity = vendorcitydao.save(vendorCity);
if (delivercity != null) {
CustomResponse.setResponse(delivercity);
CustomResponse.setStatus(CustomStatus.OK);
CustomResponse.setStatusCode(CustomStatus.OK_CODE);
CustomResponse.setResponseMessage(CustomStatus.SuccessMsg);
}
} catch (Exception e) {
e.printStackTrace();
CustomResponse.setResponse(null);
CustomResponse.setStatus(CustomStatus.Error);
CustomResponse.setStatusCode(CustomStatus.Error_CODE);
CustomResponse.setResponseMessage(CustomStatus.ErrorMsg);
}
return new ResponseEntity<ResponseDao>(CustomResponse, HttpStatus.OK);
}
Below is script for button click to add cities into div when Ajax success:
function addcity(){
var vendorid = document.getElementById('vendordeliveryid').value;
var delivercityid = document.getElementById('vendorcitydd').value;
var url = "../api/setdeliverycity";
$.post(url,{
delivercityid : delivercityid,
vendorid : vendorid,
}, function(data, status) {
if (data.status == "OK") {
if (data.statusCode == 1) {
debugger
console.log(data.response);
var vendor = data.response;
var vid = vendor.vendorcityid;
var city = vendor.vendorcity.city;
var citydiv = "";
var cityid = vendor.vendorcity.delivercityid;
var citylistlength = city.length;
if(citylistlength > 0) {
citydiv = citydiv+"<div>"+city+" <i class=\"fa fa-times\" onclick=\"removecity('"+cityid+"')\"></i></div>";
}else{
citydiv = citydiv+"<div style=\"text-align: center; float: left; margin-left: 40%; font-size: medium; font-weight: bolder; background: blanchedalmond;\"><span>Choose city from list</span></div>";
}
$('#citydivid').append(citydiv);
$('#cid').val(cityid);
$('#vendorcityid').val(vid);
} else {
var error = data.responseMessage;
swal(error, "", "error");
}
} else {
var error = data.responseMessage;
swal(error, "", "error");
}
});
}
You can check on page load if there is any data inside your localStorage or not .If yes you can get that datas and call your ajax to execute further codes and inside this ajax call if data are successfully appended inside your DOM your can clear previous data and save new data i.e : vendorid..etc inside localStorage.
Here , is sample code which should work :
$(function() {
//check if the localStorage is not null
if (localStorage.getItem("delivercityid") != null) {
var delivercityid = localStorage.getItem("delivercityid"); //get that value
var vendorid = localStorage.getItem("vendorid");
ajax_call(vendorid, delivercityid); //call function
localStorage.clear(); //clear from here after page load..
}
});
function addcity() {
var vendorid = document.getElementById('vendordeliveryid').value;
var delivercityid = document.getElementById('vendorcitydd').value;
ajax_call(vendorid, delivercityid)
}
function ajax_call(vendorid, delivercityid) {
var url = "../api/setdeliverycity";
$.post(url, {
delivercityid: delivercityid,
vendorid: vendorid,
}, function(data, status) {
if (data.status == "OK") {
if (data.statusCode == 1) {
debugger
console.log(data.response);
var vendor = data.response;
//..
//other codes..
localStorage.setItem("vendorid", vendorid);
var delivercityid_datas = JSON.parse(localStorage.getItem("delivercityid")) || []; //all datas
delivercityid_datas.push(delivercityid); //push new data inside localstorage
localStorage.setItem("delivercityid", JSON.stringify(delivercityid_datas)); //reinitalze again
} else {
var error = data.responseMessage;
swal(error, "", "error");
}
} else {
var error = data.responseMessage;
swal(error, "", "error");
}
});
}

onComplete in AjaxUpload getting before server side code hits

I am working on some legacy code which is using Asp.net and ajax where we do one functionality to upload a pdf. To upload file our legacy code uses AjaxUpload, but I observed some weird behavior of AjaxUpload where onComplete event is getting called before actual file got uploaded by server side code because of this though the file got uploaded successfully still user gets an error message on screen saying upload failed.
And here the most weird thins is that same code was working fine till last week.
Code:
initFileUpload: function () {
debugger;
new AjaxUpload('aj-assetfile', {
action: '/Util/FileUploadHandler.ashx?type=asset&signup=False&oldfile=' + assetObj.AssetPath + '&as=' + assetObj.AssetID,
//action: ML.Assets.handlerPath + '?action=uploadfile',
name: 'AccountSignupUploadContent',
onSubmit: function (file, ext) {
ML.Assets.isUploading = true;
ML.Assets.toggleAsfMask(true);
// change button text, when user selects file
$asffile.val('Uploading');
$astfileerror.hide();
// If you want to allow uploading only 1 file at time,
// you can disable upload button
this.disable();
// Uploding -> Uploading. -> Uploading...
ML.Assets.interval = window.setInterval(function () {
var text = $asffile.val();
if (text.length < 13) {
$asffile.val(text + '.');
} else {
$asffile.val('Uploading');
}
}, 200);
//if url field block is visible
if ($asseturlbkl.is(':visible')) {
$asfurl.val(''); //reset values of url
$asfurl.removeClass('requiref error'); //remove require field class
$asfurlerror.hide(); //hide errors
}
},
onComplete: function (file, responseJSON) {
debugger;
ML.Assets.toggleAsfMask(false);
ML.Assets.isUploading = false;
window.clearInterval(ML.Assets.interval);
this.enable();
var success = false;
var responseMsg = '';
try {
var response = JSON.parse(responseJSON);
if (response.status == 'success') { //(response.getElementsByTagName('status')[0].textContent == 'success') {
success = true;
} else {
success = false;
responseMsg = ': ' + response.message;
}
} catch (e) {
success = false;
}
if (success) {
assetObj.AssetMimeType = response.mimetype;
$asffile.val(response.path);
$asffile.valid(); //clear errors
ML.Assets.madeChanges();
if (ML.Assets.saveAfterUpload) { //if user submitted form while uploading
ML.Assets.saveAsset(); //run the save callback
}
} else { //error
assetObj.AssetMimeType = "";
$asffile.val('');
$astfileerror.show().text('Upload failed' + responseMsg);
//if url field block is visible and type is not free offer.
if ($asseturlbkl.is(':visible') && this.type !== undefined && assetObj.AssetType != this.type.FREEOFFER) {
$asfurl.addClass('requiref'); //remove require field class
}
ML.Assets.hideLoader();
}
}
});
}
I was facing the same issue but I fixed it with some minor change in plugin.
When “iframeSrc” is set to “javascript:false” on https or http pages, Chrome now seems to cancel the request. Changing this to “about:blank” seems to resolve the issue.
Old Code:
var iframe = toElement('<iframe src="javascript:false;" name="' + id + '" />');
New Code with chagnes:
var iframe = toElement('<iframe src="about:blank;" name="' + id + '" />');
After changing the code it's working fine. I hope it will work for you as well. :)
Reference (For more details): https://www.infomazeelite.com/ajax-file-upload-is-not-working-in-the-latest-chrome-version-83-0-4103-61-official-build-64-bit/

Copy jQuery object to modal, then hide or show, then display

I want to display a footer within a modal only when user is logged in (via ajax).
I want the footer itself to be contained in the main HTML page, which can be over-ridden by other users.
So I have a hidden container holding it on the main page:
<div style="display:none" id="signupModalFooterContainer">
<div class="modal__footer btn-group" class="signupModalFooter">
You are logged in
</div>
</div>
I can add it to the popup content:
popUpContent += $('#signupModalFooterContainer').html();
How can I make the browser re-draw the modal content between running $('.signupModalFooter').show() or $('.signupModalFooter').hide() after adding it to the window?
Empty and Replace your html content before showing
if (loggedin == 'yes') {
$('.signupModalFooter').html('You are logged in');
} else {
$('.signupModalFooter').html('');
}
$('.signupModalFooter').show();
What I ended up doing, recommended by a mentor, is to
create a "state object" which tracks the "logged in" state as well as holding various other attributes.
create two render() functions, one to render the modal main content and one to render the inner content, when events are showing feedback within the modal.
The state object looks like this:
var my_state = {
logged_in: (wordpress_i18n_key.loggedIn == 1) ? true : false,
message: undefined,
inner_container: '<div id="innerDiv"></div>',
other_attribute: undefined,
// Grab the login form from a hidden container in the DOM
login_form: $('#LogInContainer').html(),
initialize: function(target){
this.target = $(target).attr("href");
this.siteID = $(target).attr('data-someData');
}
}
Where wordpress_i18n_key.loggedIn is either a 0 or 1 that wordpress prints out to the HTML page in a <script></script> tag to make php variables available to javascript.
This function renders the main modal content:
function render_modal(){
var message = (my_state.message ? '<p>'+my_state.message+'</p>' : '');
my_state.wrapper = '<div class="modal__wrapper" id="wrapperDiv">';
if (my_state.logged_in){
my_state.wrapper += my_state.header;
my_state.wrapper += '<div class="modal__content" id="contentDiv">'+message+my_state.signup_button+'</div>';
my_state.wrapper += my_state.footer;
} else {
my_state.wrapper += my_state.header;
my_state.wrapper += '<div class="modal__content" id="contentDiv">'+message+my_state.login_form+'</div>';
}
my_state.wrapper += '</div>';
if ($('#cboxLoadedContent')) {
$('#cboxLoadedContent').html(my_state.wrapper);
}
my_state.message = undefined;
}
Where #cboxLoadedContent is the main container in the colorbox.js modal.
Then for activity that should show feedback within part of the modal:
function render_inner_modal_activity(){
my_state.content = '';
$('#innerDiv').html = '';
if (my_state.action == 'processing'){
my_state.content += my_state.spinner;
} else if (my_state.action == 'login_failed') {
my_state.content += my_state.message;
my_state.content += my_state.login_form;
} else {
// login, sign_up_form, etc
my_state.content += my_state.message;
}
if ($('#innerDiv')) {
$('#innerDiv').html(my_state.content);
}
}
When user clicks modal page button:
/**
* Initial Modal Window to Register for a Class
*
* Also leads to options to login and sign-up with API
*
*/
$(document).on('click', "a[data-target=someButton]", function (ev) {
ev.preventDefault();
my_state.initialize(this);
render_mbo_modal();
$("#modalContainer").load(my_state.target, function () {
$.colorbox({html: my_state.wrapper, href: my_state.target});
$("#modalContainer").colorbox();
});
});
Filling out the modal form, feedback stays in the modal:
/**
* Sign In to API
*/
$(document).on('submit', 'form[id="login"]', function (ev) {
ev.preventDefault();
var form = $(this);
var formData = form.serializeArray();
var result = { };
$.each($('form').serializeArray(), function() {
result[this.name] = this.value;
});
$.ajax({
dataType: 'json',
url: mz_mindbody_schedule.ajaxurl,
type: form.attr('method'),
context: this, // So we have access to form data within ajax results
data: {
action: 'client_log_in',
form: form.serialize()
},
beforeSend: function() {
my_state.action = 'processing';
render_mbo_modal_activity();
},
success: function(json) {
var formData = $(this).serializeArray();
var result = { };
$.each($('form').serializeArray(), function() {
result[this.name] = this.value;
});
if (json.type == "success") {
my_state.logged_in = true;
my_state.action = 'login';
my_state.message = json.message;
render_mbo_modal();
} else {
my_state.action = 'login_failed';
my_state.message = json.message;
render_mbo_modal_activity();
}
} // ./ Ajax Success
}) // End Ajax
.fail(function (json) {
my_state.message = 'ERROR SIGNING IN';
render_mbo_modal_activity();
console.log(json);
}); // End Fail
});
And this is the outer container the modal initially references:
<div class="modal fade" id="modalContainer" tabindex="-1" role="dialog" aria-labelledby="mzSmallModalLabel" aria-hidden="true"></div>

problems displaying page, deleting contents and repopulating - could this be multiple binding?

I have a mobile app.
It consists of 2 screens. The first is for capturing user
credentials and the 2nd is for displaying data.
The idea is to collect the credentials on screen 1.
Then make an ajax call with the credentials to get data and present it on
screen 2 as a series of links.
Then allow the user to touch a link on screen 2. This will return the link data to the javascript and pass it to the ajax call and get more data - THEN delete all the data on screen 2 and repopulate it with the new data.
First thing I want to find out: is showing a page with mobile.changePage(), populating it, deleting the contents and then repopulating it (without another call to mobile.changePage()) a reasonable thing to do?
I'm having a problem and I think its related to how I'm using onclick in the <a>
Each time I display the most recently received data, I want to display it in an <a>. I write each onclick to call the getData routine passing it information to determine the next ajax AND whatever is being displayed in the <a>. The only way I could figure out to access that was in onclick.
Is there a better way?
I'm able to display the results of the first ajax call just fine. But things get weird with the 2nd, 3rd etc.
Sometimes I'll touch a link and I'll progress thru the screens as I expect.
Sometimes I'll touch an <a> on the 1st result screen, the 2nd result screen will display and then (without me selecting data from the 2nd screen) the 3rd screen will display.
I've looked at the logs and the getData() routine is being executed.
What could be causing this? Am I somehow not destroying all the <a> properly? Am I using onclick in a fashion its not designed for? Should I be using buttons styled to look like links instead of <a>
Here's my code:
"use strict";
var app = {
onDeviceReady: function() {
$('#startButton').click(function(){
app.getDeptsForUser();
});
},
getDeptsForUser: function(){
var parms = new Object();
parms.userName = assignedUser;
app.getData(JSON.stringify(parms),"ENDPOINT1", "Departments");
$.mobile.changePage("#index", { transition: 'slide' });
},
getData: function(paramStr, endpoint, displayHeader){
var paramStrObj = JSON.parse(paramStr);
var serverName = server + ":" + port;
var encoded = Base64().encode(paramStrObj.userName + ':' + pass);
var authType = 'Basic ' + encoded;
var option = endpoint+"?action=start&params=" + paramStr;
var URL = serverName + "/rest/bpm/wle/v1/service/"+option;
$.ajax({
url: URL,
type: "POST",
crossDomain: true,
jsonp: "callback",
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", authType);
},
success: function (result) {
console.log("MobileMockUp getData() ajax success result="+JSON.stringify(result));
if (endpoint === "ENDPOINT1"){
app.displayData(paramStr, endpoint,"Departments", result.data.data.depts.items);
}
else if (endpoint === "ENDPOINT2"){
app.displayData(paramStr, endpoint,displayHeader, result.data.data.checklists.items);
}
else if (endpoint === "ENDPOINT3"){
app.displayData(paramStr, endpoint,displayHeader, result.data.data.checks.items);
}
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Unable to retrieve '+displayHeader);
},
});
},
displayData: function(currParms,currEndPt, headerText, list){
var nextEndpt;
var nextHeaderText;
var currParmsObj = JSON.parse(currParms);
if (currEndPt === "MD#getDeptsForUser"){
nextEndpt = "MD#getCheckLists";
nextHeaderText = "Check Lists";
}
else if (currEndPt === "MD#getCheckLists"){
nextEndpt = "MD#getChecks";
}
var htmlListString="";
var parmObj;
var newLink;
$('#headerText').text(headerText);
for (var i = 0; i < list.length; i++){
parmObj = new Object();
if (currEndPt === "ENDPOINT1"){
parmObj.userName=currParmsObj.userName;
parmObj.dept=list[i];
}
else if (currEndPt === "ENDPOINT2"){
parmObj.userName=currParmsObj.userName;
parmObj.dept=currParmsObj.dept;
parmObj.checklist=list[i];
}
else if (currEndPt === "ENDPOINT3"){
nextHeaderText = list[i];
}
var str = JSON.stringify(parmObj);
str = str.toString().replace(/"/g, '\\"');
newLink = "<a style='background:#ffffff;padding-top:5%;border-top: thin solid black; display:block;font-size:12px;font-weight:normal;color:#000000;text-decoration: none;' href='#' onclick='app.getData(\""+str+"\",\""+nextEndpt+"\",\""+nextHeaderText+"\")'><pre>" + list[i] + " </pre></a><br>";
htmlListString=htmlListString+newLink;
}
$('#taskListUL').empty();
$('#taskListUL').append(htmlListString);
}
};
Could this be multiple binding?
i figured out it was multiple bindings

asynchronous HTTP (ajax) request works in script tag but not in js file

I have this ajax call here in a script tag at the bottom of my page. Everything works fine! I can set a breakpoint inside the 'updatestatus' action method in my controller. My server gets posted too and the method gets called great! But when I put the javascript inside a js file the ajax call doesn't hit my server. All other code inside runs though, just not the ajax post call to the studentcontroller updatestatus method.
<script>
$(document).ready(function () {
console.log("ready!");
alert("entered student profile page");
});
var statusdropdown = document.getElementById("enumstatus");
statusdropdown.addEventListener("change", function (event) {
var id = "#Model.StudentId";
var url = '#Url.Action("UpdateStatus", "Student")';
var status = $(this).val();
$.post(url, { ID: id, Status: status }, function (data) {
// do something with the returned value e.g. display a message?
// for example - if(data) { // OK } else { // Oops }
});
var e = document.getElementById("enumstatus");
if (e.selectedIndex == 0) {
document.getElementById("statusbubble").style.backgroundColor = "#3fb34f";
} else {
document.getElementById("statusbubble").style.backgroundColor = "#b23f42";
}
}, false);
</script>
Now I put this at the bottom of my page now.
#section Scripts {
#Scripts.Render("~/bundles/studentprofile")
}
and inside my bundle.config file it looks like this
bundles.Add(new ScriptBundle("~/bundles/studentprofile").Include(
"~/Scripts/submitstatus.js"));
and submitstatus.js looks like this. I know it enters and runs this code because it I see the alert message and the background color changes. So the code is running. Its just not posting back to my server.
$(document).ready(function () {
console.log("ready!");
alert("submit status entered");
var statusdropdown = document.getElementById('enumstatus');
statusdropdown.addEventListener("change", function (event) {
var id = "#Model.StudentId";
var url = '#Url.Action("UpdateStatus", "Student")';
var status = $(this).val();
$.post(url, { ID: id, Status: status }, function (data) {
// do something with the returned value e.g. display a message?
// for example - if(data) { // OK } else { // Oops }
});
var e = document.getElementById('enumstatus');
if (e.selectedIndex == 0) {
document.getElementById("statusbubble").style.backgroundColor = "#3fb34f";
} else {
document.getElementById("statusbubble").style.backgroundColor = "#b23f42";
}
}, false);
});
In the console window I'm getting this error message.
POST https://localhost:44301/Student/#Url.Action(%22UpdateStatus%22,%20%22Student%22) 404 (Not Found)
Razor code is not parsed in external files so using var id = "#Model.StudentId"; in the main view will result in (say) var id = 236;, in the external script file it will result in var id = '#Model.StudentId'; (the value is not parsed)
You can either declare the variables in the main view
var id = "#Model.StudentId";
var url = '#Url.Action("UpdateStatus", "Student")';
and the external file will be able to access the values (remove the above 2 lines fro the external script file), or add them as data- attributes of the element, for example (I'm assuming enumstatus is a dropdownlist?)
#Html.DropDownListFor(m => m.enumStatus, yourSelectList, "Please select", new { data_id = Model.StudentId, data_url = Url.Action("UpdateStatus", "Student") })
which will render something like
<select id="enumStatus" name="enumStatus" data-id="236" data-url="/Student/UpdateStatus">
Then in the external file script you can access the values
var statusbubble = $('#statusbubble'); // cache this element
$('#enumStatus').change(function() {
var id = $(this).data('id');
var url = $(this).data('url');
var status = $(this).val();
$.post(url, { ID: id, Status: status }, function (data) {
....
});
// suggest you add/remove class names instead, but if you want inline styles then
if (status == someValue) { // the value of the first option?
statusbubble.css('backgroundColor', '#3fb34f');
} else {
statusbubble.css('backgroundColor', '#b23f42');
};
});

Categories