Jquery/Ajax/CSS show/hide div after form subimit with Ajax - javascript

I am having an issue showing a hidden DIV after posting a form with Ajax. The setup is like so;
index.html - My content and form is loaded into a div from a resource page
<div id="inst_stud_resource_change_success" style="display: none;">
<div class="greenbox">
Deleted!
</div>
</div>
<div id="inst_stud_resources_getpackages">
<script type="text/javascript">
$("#inst_stud_resources_getpackages").fadeOut("slow").load('/inst/stud/resources/getpackages?inst_id={{ inst.id }}&stud_id={{ stud.id }}').fadeIn('slow');
</script>
</div>
/inst/stud/resources/getpackages.html - this page has the form, and the content needed for the DIV on index.html
The Jquery is used like so on getpackages.html;
<script type="text/javascript">
$(document).ready(function() {
$('#delete_package').on('submit', function(event) {
$.ajax({
data : {
stud_id : $('#stud_id').val(),
pck_id : $('#pck_id').val()
},
type : 'POST',
url : '{{ url_for('mod_inst_stud.delete_package2') }}'
})
.done(function(data) {
if (data.error) {
$('#errorAlert').text(data.error).show(); // IGNORE haven't gotten this far
$('#successAlert').hide(); // IGNORE haven't gotten this far
}
else {
$("#inst_stud_resources_getpackages").hide(); // doesn't seem to do anything
$('#inst_stud_resource_change_success').show(); // never shows the div on Index.html
$('#inst_stud_resource_change_success').delay(3200).hide(); // never hides, since it is never shown..
$("#inst_stud_resources_getpackages").load('/inst/stud/resources/getpackages?inst_id={{ inst.id }}&stud_id={{ stud.id }}').show(); // this seems to work since the div from index.html is updated with the new content from getpackages.html
}
});
event.preventDefault();
});
});
Any ideas what is going on? I'm not really that verse in web development, my background is more in python/flask, not Jquery/Ajax/CSS.

I found the solution..
else {
$("#inst_stud_resources_getpackages").hide();
$('#inst_stud_resource_change_success').fadeIn(1000);
$('#inst_stud_resource_change_success').delay(2600).fadeOut(3500);
$("#inst_stud_resources_getpackages").delay(7200).fadeIn().load('/inst/stud/resources/getpackages?inst_id={{ inst.id }}&stud_id={{ stud.id }}');
}
Apparently there is a queue in Jquery, however .load() will always go to the front. So It was negating the order of my calls. I had to move some lines around, and add an animation to .load() in order to delay it from loading right way. Seems to be working well now.

Related

Initialize fotorama with images loaded by JSON/ajax

I tried to search but i can help with this ...
My html code is:
//<![CDATA[
window.onload=function(){
$("[data-instagram]").each(function(el) {
$.getJSON({
method: 'GET',
url: $(this).data("instagram"),
dataType: 'jsonp',
success: function(response) {
$('.fotorama').append('<img src="' + response.thumbnail_url + '">');
$('.fotorama').fotorama();
}
});
})
}//]]>
<!-- 1. Link to jQuery (1.8 or later), -->
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<!-- fotorama.css & fotorama.js. -->
<link href="http://cdnjs.cloudflare.com/ajax/libs/fotorama/4.6.4/fotorama.css" rel="stylesheet"> <!-- 3 KB -->
<script src="http://cdnjs.cloudflare.com/ajax/libs/fotorama/4.6.4/fotorama.js"></script> <!-- 16 KB -->
<span data-instagram="https://api.instagram.com/oembed/?url=https://www.instagram.com/p/BNijakrAX5y/?taken-by=nba"></span>
<span data-instagram="https://api.instagram.com/oembed/?url=https://www.instagram.com/p/BNlZYpDgwr_/?taken-by=nba"></span>
<span data-instagram="https://api.instagram.com/oembed/?url=https://www.instagram.com/p/BNlTnGFAqQ4/?taken-by=nba"></span>
<span data-instagram="https://api.instagram.com/oembed/?url=https://www.instagram.com/p/BNlFOilgZ3b/?taken-by=nba"></span>
<!-- 2. Add images to <div class="fotorama"></div>. -->
<div class="fotorama" data-auto="false">
</div>
<!-- 3. Enjoy! -->
As you can see, in html i have few <span> elements with atribute data-instagram. Script found each span element with data-instagram and load instagram images via JSON/ajax into <div class="fotorama"></div>
I tried to initialize fotorama gallery with, but it looks like it wont initialize properly.
I tried to folow http://fotorama.io/customize/initialization/ to turn off auto initialization by adding data-auto="false" atribute to fotorama div, and $('.fotorama').fotorama(); into script code but it doesnt work.
How can i make this work?
Thank you, sorry for bad english.
You migh be aware of the async. nature of javascript so i will explain it straightforward , note that i've removed window.onload and some unrelated stuff for simplicity
$("[data-instagram]").each(function(el) {
$.getJSON({
//extra stuff hidden
success: function(response) {
$('.fotorama').append('<img src="' + response.thumbnail_url + '">');
$('.fotorama').fotorama(); //1
}
});
});
$('.fotorama').fotorama(); // 2
setTimeout(function(){ $('.fotorama').fotorama(); },3000); // 3
Your code scans over all data-instagram takes its value and uses that to make an async. call to instagram on success of which you call fotogram to initialize your slide but the problem is that since you're loading many images fotorama initialization gets run more than once(on each success).After first initialization any further attempt would only mess up the slider.Note that if you put it outside[2] foreach that wouldn't work either because at this point even the first request would be in pending state.
So what can you do? Well the simplest(and bad :P too) way would be to remove [1] use a timeout and initialize say after 3 seconds ( meanwhile show a loader gif) see [3] problem here is you cannot trust the network so a better way would be to use a counter , initial value of which would be equal to the no. of calls want to make. On each success callback decrement it by 1 as well as checking if it's 0 .When it is 0 you fire up fotogram
var count = $("[data-instagram]").length;
$("[data-instagram]").each(function(el) {
$.getJSON({
// other stuff
success: function(response) {
$('.fotorama').append('<img src="' + response.thumbnail_url + '">');
count--;
if(count === 0 )
$('.fotorama').fotorama(); //this was the last pending call,all images loaded. Initialize
}
});
});

Set iFrame source and reload with jQuery

I have a unique issue that--while I've seen similar questions and answers--none quite address my challenge.
Currently, I provide a "print" button that loads the print dialog on a browser based on an embedded and hidden iframe. This works just fine, but I don't want to slow down page loading by pulling in the iframe for a large PDF.
So, I want to load an iframe without the source, then write the proper source url if the user clicks the print icon, then reload the iframe, and finally, show the dialog box.
Unfortunately, the print dialog pops up before I can reload the iframe so loads a blank page in the dialog box. On subsequent clicks, the PDF is loaded and ready for print.
<a href='#' id='load_pdf' ><i class='fa fa-2 fa-print'></i></a>
<iframe id="iFramePdf" src="" style="display:none;"></iframe>
<script type="text/javascript">
jQuery(document).ready(function() {
$("#load_pdf").click(loadPDF);
function loadPDF() {
$('#iFramePdf').attr('src', "my.pdf");
// Attempt to reload iframe
$('#iFramePdf').load("my.pdf");
sendPrint('iFramePdf')
}
function sendPrint(elementId) {
var iframe = $(element_id)[0];
iframe.contentWindow.focus();
iframe.contentWindow.print();
}
});
</script>
I've tried the following various methods to reload:
// Attempt 1
$('#iFramePdf').attr('src', function () { return
$(this).contents().get(0).location.href });
// Attempt 2
$('#iFramePdf').attr("src", $('#iFramePdf').attr("src"));
$('#iFramePdf').attr('src', function () { return $(this).contents().get(0).location.href });
// Attempt 3
$('#iFramePdf')[0].contentWindow.location.reload(true);
// Attempt 4
var getMyFrame = document.getElementById(elementId);
getMyFrame.contentWindow.location.reload(true);
I've even tried using jQuery's defer method, but had no luck with that (possibly because I'm lacking knowledge). If I could get any guidance, I'd appreciate it.
try to change this:
function loadPDF() {
$('#iFramePdf').attr('src', "my.pdf");
// Attempt to reload iframe
$('#iFramePdf').load("my.pdf");
sendPrint('iFramePdf')
}
to something like this:
function loadPDF() {
$('#iFramePdf').attr('src', "my.pdf");
}
$('#iFramePdf').load(function(){
sendPrint('iFramePdf')
})
it should work
You can try .promise(). For obvious reasons I can't test it out, but I think 3 seconds should be adequate for the iframe to load. Be aware that this is as syntactically correct as I can get it without testing it out. Adjust the fadeIn(1800) and the delay(1200) accordingly.
HTML
<a href='#' id='load_pdf' ><i class='fa fa-2 fa-print'></i></a>
<p id="msg" style="display: none;">Printing Document...</p>
<div id="printPort" style="opacity: 0; width: 1px; height: 1px;"></div>
jQuery
$(function() {
$("#load_pdf").on('click', loadPDF('my.pdf'));
// Create the iframe, and put it inside #printPort
// Change it's src to the file argument
// Animate the #msg for 3 seconds
var loadPDF = function(file) {
$('<iframe id="iFramePdf" src="blank.html"></iframe>').appendTo("#printPort");
$("#iFramePdf").att('src', file);
return $('#msg').fadeIn(1800).delay(1200).fadeOut();
}
var sendPrint = function(elementId) {
var iframe = $(element_id)[0];
iframe.contentWindow.focus();
iframe.contentWindow.print();
}
// Once the animation is done the promise will resolve and sendPrint will execute on callback.
$.when(loadPDF).done(sendPrint('iFramePdf'));
});

Create a custom popup that is responsive and can post to database

I am currently working on an intranet solution for my company written in PHP using the Laravel framework, this requires me to do a lot of new things I have never done before, 1 of these is creating a popup that has dynamic html depending on a drop down list such as this:
I have a calendar (http://fullcalendar.io/)
When I click on a day in this calendar a popup should show that looks something like this:
After selecting a value from that dropdown list a different set of fields should be shown depending on the value selected for example:
OR
So I really need a lot of control over the popup, I have no previous experience with working with popups (unless a simple alert of a variable in javascript counts) and I need a whole deal of functionality, it also needs to be able to post to a database so I think it might even have to be a form element. I also need to be able to fire the popup from the onclick event from the fields in my calendar so that makes it extra hard for someone who has always written back end code up until now.
SO WHAT IS YOUR QUESTION?
Could anyone tell me what the easiest/fastest way to achieve this is without losing any functionality necessities, can I do this from php, does a feature like this exist in the Laravel framework?(if it does I coudldn't find it) or do I have to start using something like jquery?
I found a bunch of libraries such as Fancybox that claim to be able to do this but I can't make head nor tail out of their usage guide.
For everyone who thinks this doesn't belong here: my only question is not "Is it Possible?" I am also asking how do I do it, what do I write in my html, javascript, php to make it work?
EDIT: I just read something about jquery dialogs that seems interesting, seems like you can use jquery dialogs to create a popup from a form you have in your html (form is hidden) but I can't seem to get the code to fire off the popup (dialog) to work so far I have this:
$(document).ready(function() {
$('#calendar').fullCalendar({
//calendar options here
dayClick: function(date, jsEvent, view) {
//to get date use date.format());
//POPUPCODE START
$("#logform").dialog({ //Shows dialog
height: 250,
width: 450,
modal: true,
buttons: {
"Cancel": function() {
$( this ).dialog( "close" );
},
"Save": function() {
$.ajax({
url: "/url/to/submit", //
timeout: 30000,
type: "POST",
data: $('#modalform').serialize(),
dataType: 'json',
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("An error has occurred making the request: " + errorThrown)
},
success: function(data){
//Do stuff here on success such as modal info
$( this ).dialog( "close" );
}
}
}
}
}),
//POPUPCODE END
var myCalendar = $('#calendar');
myCalendar.fullCalendar();
var myEvent = {
title:"Work 7.6h",
allDay: true,
start: date,
end: date
};
myCalendar.fullCalendar( 'renderEvent', myEvent,true );
},
eventClick: function(calEvent, jsEvent, view) {
var myCalendar = $('#calendar');
myCalendar.fullCalendar('removeEvents',calEvent._id);
}
})
});
And for my html I have:
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-default">
<div class="panel-heading">Calendar</div>
<div class="panel-body">
<div id='calendar'></div>
<a class='iframe' href='home.blade.php'>Click me</a>
</div>
<form id="logform" style="display:none">
<input type="text" name="something">
<input type="text" name="somethingelse">
</form>
</div>
</div>
</div>
</div>
The trouble started only after adding the code between //popupcode start and //popupcode end now my calendar won't even show and I get
SyntaxError: missing ) after argument list
The place it is pointing at is the 3rd line above my //popupcode end here:
}
}
} //this one
}
}),
//POPUPCODE END
But no matter what I add or remove there I keep getting the same error
I figured it out myself, instead of making things harder by learning all kinds of new things I got it to work by removing all the code I added previously and adding 1 line of code to create the popup by using jquery.
I removed all the code that I was using to create the popup and replaced it by this: $("#somediv").load().dialog({modal:true});
I created a div called 'somediv' around my form and now it's doing what I need it to do, seeing as my entire form is in the popup now I'm pretty sure I can add a button to it that can submit the form so I can catch that with php and then I'll be able to do whatever I want with the data in php (post to database or return error messages etc...)
Ok, first of all, i recommend to use Javascript.
It's possible with only PHP, HTML and CSS but you will have to refresh the page all the time for the next popup to appear.
You can just make divs that are positioned fixed or absolute and they will overlay the underlaying content. The overlaying div(popup) will be a normal div where you can make forms and whatever you want.
Here is a quick jsfiddle I threw toghether:
http://jsfiddle.net/0zvqm5nr/17/
Here is the code:
HTML
<div class="calendar">
<h1>Your calendar would be here</h1>
<button id="popupButton">13.05.2015</button>
</div>
<div class="popup">
<h2>13.05.2015</h2>
Activity:
<form action="site.php" method="post">
<select id="activity">
<option class="placeholder" selected disabled>Select</option>
<option>work</option>
<option>youth leave</option>
</select>
</form>
</div>
<div class="popup">
<h3>Work 13.05.2015</h3>
this will be the work popup
</div>
<div class="popup">
<h3>Youth leave 13.05.2015</h3>
this will be the youth leave popup
</div>
CSS
.calendar {
width: 500px;
height: 500px;
background: green;
}
.popup {
width: 500px;
height: 500px;
background: grey;
display: none;
position: fixed;
top: 0;
left: 0;
}
Javascript
document.getElementById("popupButton").onclick = function() {
document.getElementsByClassName("popup")[0].style.display = "block"
}
document.getElementById("activity").onchange = function() {
document.getElementsByClassName("popup")[0].style.display = "none"
var selectedValue = this.options[this.selectedIndex].innerHTML;
if (selectedValue == "work") {
document.getElementsByClassName("popup")[1].style.display = "block";
}
if (selectedValue == "youth leave") {
document.getElementsByClassName("popup")[2].style.display = "block";
}
}
I hope this helped.

jQuery Mobile popups/notifications

I want to create a small popup/notification that will occur when values change in my database. the logic is being passed correctly. However, I'm not sure how to make the popups occur properly and at all as well.
I have two buttons:
CS
GH
I would like to have the notifications pop up a little bit above these buttons. This is what I have created but I just haven't positioned them yet:
<div id="GH_popup" data-role="popup">
<p> GH is OFF! </p>
</div>
<div id="CS_popup" data-role="popup">
<p> CS is OFF! </p>
</div>
I also have some Javascript that determines when these notifications will pop up:
<script type="text/javascript" >
$(document).ready(function () { GrabGhCsStatus(); });
function GrabGhCsStatus() {
var url = '#Html.Raw(Url.Action("index","GhCsStatus"))';
$.get(url, function (data) {
if (data.CheckIfCsIsRunning == 1 && data.CheckIfGhIsRunning == 0) {
$("#GH_popup").popup();
$("#GhCsStatus_GH").remove();
if (data.CsStatus == 0) {
$('#GhCsStatus_CS').buttonMarkup({ icon: 'GhCsStatus-Red' });
} else {
$('#GhCsStatus_CS').buttonMarkup({ icon: 'GhCsStatus-Green' });
}
}
}
...
...
...
</script>
I feel as though I am putting the jQuery popup attributes in the wrong areas and that I am not using them properly =/
To call a popup programmatically, use this code
$('#popup_id').popup('open');
To close it
$('#popup_id').popup('close');
Popup widget API

Ajax callback refresh div

I implemented a Ajax callback function to update a div (announcement) in my web page.
It works fine, but the current issue is that the Ajax call function update the announcement div, however, after rewrite the content, the Javascript functions in this content are not load it. Therefore, my toggle function in table does not work after update content.
My ajax call function
setInterval("_checkUpdate()", 2000); //2 seconds one call.
function _checkUpdate() {
var callback=new Object();
callback.success=this.checkUpdateonExternalSuccess;
callback.failure=this.checkUpdateonExternalFailure;
YAHOO.util.Connect.asyncRequest('GET' , '/ci/ajaxCustom/ajaxCheckUpdate',callback);
};
On success, it update the content to rewrite to my Div
function checkUpdateonExternalSuccess (o){
if(o.responseText!==undefined) {
var str=o.responseText;
if(str !== 'nocontent') {
document.getElementById('updateContent').innerHTML=str; (Write the new content to my div)
location.reload(); //Reload the whole page, i do not want that
}
}
};
It works, it write the new content with Javascript, but the Javascript functions are not load it.
Javascript:
$(document).ready(function() {
//First hide all the contects except the headcontent
$(".content").hide();
$(".headContent").show();
//If user click on the head title, it hide/show content
$(".headTitle").click(function () {
collapseHeadContent();//reset all
var aParentTD= $(this).closest("td");
var aHeadContent = aParentTD.find (".headContent");
aHeadContent.toggle();
});
// If uses click on the title, it has toggle event for the content
$(".title").click(function () {
collapseContent(); //First reset all
var aParentTD = $(this).closest("td");
var aContent = aParentTD.find(".content"); // Content in the same TD with Title
aContent.toggle();
});
});
function collapseContent() {
//find the Head content to hide and reset of content
$(".headContent").hide();
$(".content").hide();
}
function collapseHeadContent() {
$(".content").hide();
}
HTML:
<div id="annoucementTableDiv">
<table id="annoucementTable">
<tbody id="tdContent">
<tr>
<td><span id="tdtitle"><a class="headTitle"> Forbidden: Error 403</a></span> <br />
<span class="annfrom">PLC team - 19/08/2010 at 10:30<br /> </span>
<br />
<span class="headContent"><P>Due to scheduled maintenance, HOME showed the error 403:<br/>
This is now resolved and customers can update again as normal </P>
</span>
</td>
</tr>
</tbody>
<tbody id="tdContent">
<tr>
<td>
<span id="tdtitle">
<a class="title">Downloading maps</a>
</span> <img src="/euf/assets/themes/standard/images/layout/important.png" class="alert_icon" alt="alert"></img><br />
<span class="annfrom">Sent by 2nd line - 05/11/2009 at 15:30<br /> </span>
<span class="content">Since this morning it has been reported that multiple customers are again receiving this error message.<br /><br />This error has been escalated to the relevant teams with the highest priority and is currently being looked into.
An estimated time for a fix is not yet available but we will keep you updated.
</span>
<br />
</td>
</tr>
</tbody>
</table>
</div>
If I do location.reload, the Javascript functions work. But I do not want to refresh the page.
Any ideas?
Since you're also hiding/showing things, I recommend you change you're ready handler into a named function then call it on document.ready, like this:
function loadFunc() {
$(".content").hide();
$(".headContent").show();
}
$(function() {
loadFunc():
$(".headTitle").live('click', function () {
collapseHeadContent();
$(this).closest("td").find(".headContent").toggle();
});
$(".title").live('click', function () {
collapseContent();
$(this).closest("td").find(".content").toggle();
});
});
This also uses .live() to set your click functions up once. Then when you do your AJAX load, you can just call loadFunc again to do hiding/showing or any other work, like this:
function checkUpdateonExternalSuccess (o){
if(o.responseText!==undefined) {
var str=o.responseText;
if(str !== 'nocontent') {
document.getElementById('updateContent').innerHTML=str;
loadFunc();
}
}
};
Sounds like you need the live function. It is quite straight forward.
$('.title').live('click', function() {
collapseContent(); //First reset all
var aParentTD = $(this).closest("td");
var aContent = aParentTD.find(".content"); // Content in the same TD with Title
aContent.toggle();
});
Basically adds the click handler to all title elements. Even if another loads the event is still associated with it. You can use this for all elements that are loaded by AJAX during the life of the page. So you do the same for the head element and so on.
In a project I'm writing at the moment, I insert HTML and Javascript content separately. The HTML is inserted as usual into innerHTML. And I got the javascript in a JS file which I load into my document during runtime like this:
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = 'myJavascriptFile.js';
headID.appendChild(newScript);
Wrap your table related code into a function and call it once on document.ready and after you ajax-request. Avoid triggering document.ready as suggested by Uoli, because it can cause unpredictable side effects as all your $(document).ready(function() { blocks will be executed again.

Categories

Resources