JavaScript confirm dialog in Django - javascript

I have a Django form. And I need a confirm/cancel dialog on form submit. A had an idea of sending POST data from jQuery... but is it a way to use javascript dialog as middleware?

Add the bellow code according to your need in your Html
<form><input type="submit" value="Submit" id="confirm"/> </form>
and jQuery code for confirm dialog
<script>
jQuery("#confirm").click(function(){
$("<div></div>").appendTo('body')
.html('<div><h3> write your message for confirm dialog</h3></div>')
.dialog({
title: "Confotm Dialog" ,
width:500, height:300,
modal:true,
resizable: false,
show: { effect: 'drop', direction: "left" },
hide:{effect:'blind'}
buttons: {
Yes: function() {
jQuery.ajax({
type:"POST", //post data
data:{'key':key}, //if you want to send any data to view
url:'/get_viewerModal/' // your url that u write in action in form tag
}).done(function(result){
alert("am done") //this will executes after your view executed
})
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
});
<script>
here you need ajax knowledge and it is very easy to use am sure you do this :)

Related

Triggering event on clicking OK button in Jquery Modal dialog box

I am trying to display a dialog box with just an OK button on response of an ajax call. When the user clicks OK, it should reload the page. But now page reload is immediately happening after the dialog box is popped up. It is not waiting for the user to click OK. FYI I am using Jquery Modal dialog box.
Simple browser alert() does the job for me, but I don't like the appearance of alert().
Any help is highly appreciated!
$.ajax({
url: "modules/mymod/save.php",
type: "POST",
data: $('#requestForm').serialize(),
statusCode: {404: function () {alert('page not found');}},
success: function (data) {
// alert(data);
modal({type: 'alert', title: 'Alert', text: data});
window.location.href = window.location.href;
}
});
Reference:
$.ajax({
url: "modules/mymod/save.php",
type: "POST",
data: $('#requestForm').serialize(),
statusCode: {404: function () {alert('page not found');}},
success: function (data) {
// alert(data);
modal({
type: 'alert',
title: 'Alert',
text: data,
buttons: [{
text: 'OK', //Button Text
val: 'ok', //Button Value
eKey: true, //Enter Keypress
addClass: 'btn-light-blue btn-square', //Button Classes
onClick: function() {
window.location.href = window.location.href;
}
}, ],
center: true, //Center Modal Box?
autoclose: false, //Auto Close Modal Box?
callback: null, //Callback Function after close Modal (ex: function(result){alert(result);})
onShow: function(r) {
console.log(r);
}, //After show Modal function
closeClick: true, //Close Modal on click near the box
closable: true, //If Modal is closable
theme: 'xenon', //Modal Custom Theme
animate: true, //Slide animation
background: 'rgba(0,0,0,0.35)', //Background Color, it can be null
zIndex: 1050, //z-index
buttonText: {
ok: 'OK',
yes: 'Yes',
cancel: 'Cancel'
},
template: '<div class="modal-box"><div class="modal-inner"><div class="modal-title"><a class="modal-close-btn"></a></div><div class="modal-text"></div><div class="modal-buttons"></div></div></div>',
_classes: {
box: '.modal-box',
boxInner: ".modal-inner",
title: '.modal-title',
content: '.modal-text',
buttons: '.modal-buttons',
closebtn: '.modal-close-btn'
}
});
}
});
Because your reload runs irrespectively of what is clicked. If you want to assign a callback function to the modal window:
jQuery UI dialog with boolean return - true or false
Also, there is no need to make location.href equal itself (or use the window object). location.reload() works just as well.
You can pass the dialog modal buttons attributes, each with a registered event, like this:
$.ajax({
url: "modules/mymod/save.php",
type: "POST",
data: $('#requestForm').serialize(),
statusCode: {404: function () {alert('page not found');}},
success: function (data) {
$("#dialog-confirm").dialog({
resizable: false,
height: 200,
modal: true,
buttons: {
Proceed: function() {
window.location.href = window.location.href;
},
Cancel: function() {
// Cancellation code here
}
}
});
}
});
Simple browser alert() does the job for me because alert() is an blocking call. If you omit the alert then your code is not bind with any event to check whether user clicked on a button or not, that's why the code block executes immediately and page reloads.
So bind the following code:
window.location.href = window.location.href;
inside some button click, to resolve the issue.
dont use window.location function in success.instead open the modal with ok button at success(how to do that, I think you know already) and assign some id to that button let say id="loction_btn".
then use just this
$('document').on('click','#location_btn',function(){
window.location.href = window.location.href;
});

Pass data from jquery dialogue into mysql

I have a website that shows a jQuery dialogue with a TextArea inside it. It also has a save button, what I'm trying to do is to pass the data from the TextArea to MySQL database table.
onEdit: function (ev, elem) {
var $elem = $(elem);
$('#NoteDialog').remove();
return $('<div id="NoteDialog"></div>').dialog({
title: "Note Editor",
resizable: false,
modal: true,
height: "300",
width: "450",
position: { my: "left bottom", at: "right top", of: elem},
buttons: {
"Save": function () {
var txt = $('textarea', this).sceditor("instance").val();
// Put the editied note back into the data area of the element
// Very important that this step is included in custom callback implementations
$elem.data("note", txt);
$(this).dialog("close");
},
"Delete": function () {
$elem.trigger("remove");
$(this).dialog("close");
},
Cancel: function () {
$(this).dialog("close");
}
},
open: function (event, ui) {
$(this).css("overflow", "hidden");
var textarea = $('<textarea id="txt" name="text" style="height:100%; width:100%;">');
$(this).html(textarea);
// Get the note text and put it into the textarea for editing
textarea.val($elem.data("note"));
textarea.sceditor({
resizeEnabled: false,
style: "jquery.sceditor.min.css",
toolbar: 'bold,italic,underline,subscript,superscript|left,center,right,justify|orderedlist,bulletlist,link,image',
width: '100%',
height: '100%'
});
},
close: function (event, ui) {
$("textarea").sceditor("instance").destroy();
}
});
When you click on the button save, send an AJAX request with your textarea data to a PHP file
$.ajax({
type:"POST",
cache:false,
url:"file.php",
data: {data : your_text_area_data} ,
success: function (result) {
//Write there
//If your php file sends back info, it's in the variable result
}
});
In your php file file.php, get your data back and do the query to your data base:
The data from your textarea can be accessed with : $_POST['data'] and then do your query :
INSERT/UPDATE ...
Edit : no need to add a callback as I mentionned in the comment (I'm assuming your code is working as it is), you can add the $.ajax when your SAVE button is triggered :
"Save": function() {
var txt = $('textarea', this).sceditor("instance").val();
//Put the editied note back into the data area of the element
//Very important that this step is included in custom callback implementations
$elem.data("note", txt);
//$.ajax here
$(this).dialog("close");
},

How to submit a form after confirming submit? jQuery, AJAX

Good day, I have a simple html page containing this form:
<form:form method="post" action="details" modelAttribute="code">
<form:input path="code"/>
<br/>
<input type="submit" value="Submit" />
</form:form>
When I press the Submit button I need to check whether there are some records in the database for given code using jQuery AJAX. If yes then popup jQuery UI dialog to ask user whether he really wants to display record details (because it's a paid service). If he confirms I need to submit the form. This is my script on the html page:
$(document).ready(function() {
// Bind an event handler to the submit event
$('form#code').submit( function() {
// Check whether there are some records in the DB using AJAX
$.ajax({
url: 'getResultCount',
type: 'post',
dataType: 'html',
data: $("form#code").serialize(),
success: function(result) {
if(result == 'null') {
$('div#results').html('<p>No records found for ' + $('input#code').val() + '.</p>');
} else {
// At leat one record was found so ask the user
$('#dialog-confirm').dialog({
resizable: false,
draggable: false,
height: 240,
width: 450,
modal: true,
buttons: {
"Display details": function() {
// User confirmed, submit the form
$('form#code').submit();
},
Cancel: function() {
$(this).dialog("close");
}
}
});
}
}
});
return false;
});
});
When I press "Display details" button nothing happens. I think it is because I'm entering the same submit handler which returns false. How to solve it so that form submit is executed? Please advise.
Thank you in advance.
Vojtech
Change
$('form#code').submit();
to
$('form#code')[0].submit();
It will skip the jQuery onsubmit function.
Basic example: http://jsfiddle.net/4Ax6m/
There is one simple answer: Do not use <input type="submit" ... />.
You can instead use <button onlick="handler()">Submit</button>, where handler() is your function bound to the submit-event of the form in the above code. If your handler decides that the form should be submitted just submit it programmatically. Edit: Which is actually already in your code.
You'd need to wait for the .ajax to succeed since it is currently running in async mode.
So disable it using the async option on ajax. Documentation Here
ANSWER SPECIFICALLY FOR YOU
JS
$(document).ready(function () {
// Bind an event handler to the submit event
$('form#code').submit(function () {
// Check whether there are some records in the DB using AJAX
$.ajax({
url: 'getResultCount',
type: 'post',
dataType: 'html',
data: $("form#code").serialize(),
async: false,
success: function (result) {
if (result == 'null') {
$('div#results').html('<p>No records found for ' + $('input#code').val() + '.</p>');
//No Records found, submitting!!
return true;
} else {
// At leat one record was found so ask the user
$('#dialog-confirm').dialog({
resizable: false,
draggable: false,
height: 240,
width: 450,
modal: true,
buttons: {
"Display details": function () {
// User confirmed, submit the form
return true;
},
Cancel: function () {
//TODO: Don't think you need this line?
$(this).dialog("close");
//CANCEL!!!
return false;
}
}
});
//User skipped Dialog somehow...ignoring....DO NOT SUBMIT
return false;
}
}
});
});
});
Note: This will return true and false to continue the submit process to the server

how to reopen modal dialog in jquery after closing it?

I have an Asp.Net MVC application, where in 1 View, I have a list with every record showing Edit icon. Clicking the edit icon opens a modal dialog popup to update the record .
I face problem in reopening the dialog or clicking other edit icon for popup after closing the dialog .
Following is my jquery code to open the dialog :
var singltym;
$(function () {
$('#addSingleTimeDialog').dialog({
cache: false,
autoOpen: false,
width: 450,
height: 450,
closeOnEscape: true,
resizable: true,
modal: true});
$('#singletymlink').on('click', function () {
singltym = $(this);
var dialogDiv = $('#addSingleTimeDialog');
var viewUrl = singltym.attr('href');
$.ajax({
cache: false,
url: viewUrl,
dataType: 'html',
success: function (data) {
dialogDiv.html(data);
dialogDiv.dialog('open');
}
});
return false;
});
});
var singltym;
$(function () {
$('#addSingleTimeDialog').dialog({
cache: false,
autoOpen: false,
width: 450,
height: 450,
closeOnEscape: true,
resizable: true,
modal: true});
$('#singletymlink').on('click', function () {
singltym = $(this);
var dialogDiv = $('#addSingleTimeDialog');
var viewUrl = singltym.attr('href');
$.ajax({
cache: false,
url: viewUrl,
dataType: 'html',
success: function (data) {
dialogDiv.html(data);
dialogDiv.dialog('open');
//I work in this method
$( this ).dialog( "close" );
}
});
});
});
Or
$.ajax({
cache: false,
url: viewUrl,
dataType: 'html',
success: function (data) {
dialogDiv.html(data);
$("#dialogDiv").dialog("open");
$( this ).dialog( "close" );
}
If $( this ).dialog( "close" ); not working because not try this specific sentence??
$('#addSingleTimeDialog').dialog("close");
The above issue can be solved by including the below scripts in parent view from where the dialog popup is clicked & initiated :
<script type="text/javascript" src="../../Scripts/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="../../Scripts/jquery.validate.min.js"></script>
<script type="text/javascript" src="../../Scripts/jquery.validate.unobtrusive.min.js"></script>
As well as insert the below scripts in child view which is the UI for modal dialog popup :
<script type="text/javascript" src="../../Scripts/jquery.validate.min.js"></script>
<script type="text/javascript" src="../../Scripts/jquery.validate.unobtrusive.min.js"></script>
By scripting in such way, the jquery script conflict is avoided & reopening of dialog can be swiftly done.
You could use the open method:
$('#addSingleTimeDialog').dialog('open');
Came across this older question, found a simpler solution not listed here.
Add an event listener for the close event, and call destroy when the dialog is closed.
close: function(event, ui) {$(this).dialog("destroy");}
Try writing $( this ).dialog( "close" ); method in close function. Eg :
close: function(){ $( this ).dialog( "close" ); },
$( this ).dialog( "close" ); does not destroy the dialog, instead it just closes and makes it available to be used for next time.
My problem was solved by replacing
$(this).dialog("close");
with
$(this).dialog("destroy");

Get content from TinyMCE editor

I'm trying to get the Content from TinyMCE, but it only returns null. The problem it's loaded in a Dialog box.
The dialog view:
<form>
<textarea name="content" cols="40" rows="25" id="tinymce">
Dette er noget tekst
</textarea>
</form>
<input class="close" onclick="get_editor_content()" name="submit" type="submit" value="Kontakt Oline" style="float: right" id="contenttiny" />
<script type="text/javascript">
tinyMCE.init({
// General options
mode: "textareas",
theme: "advanced",
plugins: "autolink,lists,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
</script>
The view where the dialog is opened from:
<a class="openDialog" data-dialog-id="emailDialog" data-dialog-title="Kontakt/prospekt" href="/Home/tinymce">Contact US</a>
<div id="result"></div>
<script type="text/javascript">
$.ajaxSetup({ cache: false });
$(document).ready(function () {
$(".openDialog").live("click", function (e) {
e.preventDefault();
$("<div ></div>")
.addClass("dialog")
.attr("id", $(this).attr("data-dialog-id"))
.appendTo("body")
.dialog({
title: $(this).attr("data-dialog-title"),
close: function () { $(this).remove() },
modal: true,
position: ['center', 40],
minWidth: 670,
resizable: false
})
.load(this.href);
});
});
$(".close").live("click", function (e) {
e.preventDefault();
var content = tinyMCE.get('tinymce').getContent(); //$("#contenttiny").val();
$.ajax({
type: "POST",
url: "/Home/tinymce",
data: { "content": content },
success: function (data) {
$("#result").html(data.nameret);
$(".dialog").dialog("close");
},
error: function (data) {
alert("There was error processing this");
$(this).closest(".dialog").dialog("close");
}
});
});
</script>
The Controller:
[HttpPost]
public ActionResult tinymce(string content)
{ /*Your other processing logic will go here*/
return Json(new
{
nameret = content
}, JsonRequestBehavior.
AllowGet);
}
P.S. I have used this example to create the modal dialog. Which is an PartialView. It's possible to get the content from tinymce in the main index view. But not in the ajax call.
The solution to the problem was rather simple. The reason was that the tinymce is returning html text, which per default is not allowed. The solution was to put [ValidateInput(false)] over the Controller method.

Categories

Resources