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

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>

Related

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/

href not working in greasemokey

I have following code in my greasemonkey script. In case, i am unable to save my order to server, i display an error message and then a link (created using <a href> to save it again. this link is save_order method again. But this is not working. I tried debugging into it but no luck. (I have basic understanding of JavaScript)
function save_order() {
server_url = 'https://server.com/api/put_order?user_id=' + form.user.value +'&order_id=' + orderId;
GM_xmlhttpRequest({
method: "GET",
url: server_url,
onload: function(response){
if(response.status == 200){
localstorage.removeItem(orderId);
messageBar.innerHTML += '<br/>Order has been saved successfully.';
} else {
if (errorBar.style.display === 'none'){
errorBar.style.display = 'block';
}
errorBar.innerHTML += '<br/>Error saving. <b>Try Again</b>';
}
}
});
}
=======
FULL CODE
// ==UserScript==
// #name SaveOrder
// #version 1.0
// #author myname
// #include https://xx*.xxxxxxxx.com*/*
// #run-at document-end
// #grant GM_xmlhttpRequest
// ==/UserScript==
var saveButton = document.getElementById('save-button');
saveButton.addEventListener("click", save_order,true);
var info_bar = document.getElementById('info_bar');
var error_bar = document.getElementById('error_bar');
var form = document.getElementById('place_order_form');
var order_id = form.order_id.value;
var localstorage = window.localStorage;
if (localstorage.getItem(order_id)){
save_to_db();
}
function save_order(){
localstorage.setItem(order_id, order_id);
}
function save_to_db() {
var random_boolean = false;//Math.random() >= 0.5;
console.log(random_boolean);
server_url = 'https://xxx.xxxx.com/api/put_order?user_id=' + form.user.value +'&order_id=' + order_id;
GM_xmlhttpRequest({
method: "GET",
url: server_url,
onload: function(response){
if(response.status == 200 && random_boolean){
localstorage.removeItem(order_id);
info_bar.innerHTML += '<br/>Order saved successfully';
} else {
if (error_bar.style.display === 'none'){
error_bar.style.display = 'block';
}
error_bar.innerHTML += '<br/>Error saving. <b>Try Again</b>';
}
}
});
}
Your method works just fine, as you can see in this example.
You probably have an error elsewhere.
function test(){
document.body.innerHTML += '<a class="function-link" href="#" onclick="test();">Test</a>';
}
<a class="function-link" href="#" onclick="test();">Test</a>
EDIT : I did some digging, and found a way around your issue.
Instead of adding an onclick on your link, create an event handler in javascript attached to a save-to-db class like this :
document.addEventListener("click", function(e) {
if (e.target.closest('a') && e.target.closest('a').classList.contains("save-to-db")) {
save_to_db();
}
});
Now all you need to do is get rid of your onclick and replace it with class="save-to-db"
document.body.innerHTML += '<br/>Error saving. <b>Try Again</b>';
It works like a charm now :
document.addEventListener("click", function(e) {
if (e.target.closest('a') && e.target.closest('a').classList.contains("save-to-db")) {
save_to_db();
}
});
save_to_db();
function save_to_db() {
console.log('Function called');
document.body.innerHTML += '<br/>Error saving. <b>Try Again</b>';
}

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');
};
});

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

<%#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

how can I load tinymce 4 in modal window?

I have a form in cakephp.. I am opening it in a modal window whih extends jquery.
Now I have loaded tinymce in my form but it is not loading in modal.
tinymce.js is loading. even its all settings are also loading properly.
Can anyone suggest What can be problem ?
Thanks
I have this problem too..
I'm using bootstrap modal box and use the plugin for open multi-modal
I'm use this code Helper :
http://bakery.cakephp.org/articles/jwilcox09/2012/01/04/adding_a_tinymce_image_browser_to_cakephp_2
In the controller i use this code :
public function add() {
if ($this->RequestHandler->isAjax()) {
$this->layout = 'modal';
}
if ($this->request->is('post')) {
$this->Post->create();
if ($this->Post->saveAll($this->request->data, array('deep' => true))) {
$this->Session->setFlash(__('The post has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The post could not be saved. Please, try again.'));
}
}
$users = $this->Post->User->find('list');
$this->set(compact('users'));
}
In the index view i use this code
از این قسمت میتوانید یک پست تازه وارد سایت کنید Js->link(__('پست تازه'), array('action' => 'add'), array(
'update' => '#ajax-modal',
'htmlAttributes' => array('id' => 'EzafKardan', 'class'=>'modalBarGozar btn btn-primary btn-lg',
'data-toggle'=>'modal')
)); ?>
$(function(){
$.fn.modal.defaults.spinner = $.fn.modalmanager.defaults.spinner =
'<div class="loading-spinner" style="width: 200px; margin-left: -100px;">' +
'<div class="progress progress-striped active">' +
'<div class="progress-bar" style="width: 100%;"></div>' +
'</div>' +
'</div>';
$.fn.modalmanager.defaults.resize = true;
$('[data-source]').each(function(){
var $this = $(this),
$source = $($this.data('source'));
var text = [];
$source.each(function(){
var $s = $(this);
if ($s.attr('type') === 'text/javascript'){
text.push($s.html().replace(/(\n)*/, ''));
} else {
text.push($s.clone().wrap('<div>').parent().html());
}
});
$this.text(text.join('\n\n').replace(/\t/g, ' '));
});
}); </script>
var $modal = $('#ajaxKhabari');
$('.modalBarGozar').on('click', function(){
var link = $(this).attr("href"); $('body').modalmanager('loading');
setTimeout(function(){
$modal.load(link, '', function(){
$modal.modal();
}); }, 1000); });
in the modal layout i add the link for tinymce.js and also add to defoult layout and other layout
I'm try everything but did not work...

Categories