Confirm messagebox when delete, $.post - asp.net-mvc

I have this atm:
<img src="/Content/Admin/Images/Icons/delete.gif" />
How can I modify this one so it also shows a confirm messagebox?
As it is now nothing happens when I click it, it doesnt post, what more is needed for it to work?
EDIT:
<form action="/Admin/Users" method="post">
<script type="text/javascript">
$(function() {
$('.delete').click(function() {
$.post(this.href, {}, function(data) {
});
return false;
});
});
</script>
And each link:
<a class="delete" href="/Admin/User/Delete/71"><img src="/Content/Admin/Images/Icons/delete.gif" /></a>
no luck, nothing happens "onclick", not even a javascript error
/M

Indeed more is needed. I would advice you to separate javascript from HTML:
<a id="delete" href="<%= Url.RouteUrl("UserDelete", new { userID = item.UserID }) %>">
<img src="/Content/Admin/Images/Icons/delete.gif" />
</a>
and then register a click handler to this anchor in javascript:
<script type="text/javascript">
$(function() {
$('#delete').click(function() {
$.post(this.href, {}, function(data) {
alert('user successfully deleted');
});
return false;
});
});
</script>

Are you sure nothing is happening? Just calling $.post(url) will request the page, but it ignores any result. You may want to review the docs for the $.post function to accomplish what you'd like to do?
You can add a confirm box like this:
onclick = "if (confirm('Are you sure?')) $.post(this.href); return false;"

Related

DirtyForms does not work properly with $.blockUI

I'm using DirtyForms and $.blockUI plugin, the latter to change pages when clicking on links (in my app, some pages take a couple of seconds more to load and a visual feedback is fine).
When I change field content and then click any link, DirtyForms is triggered: but when I cancel the process to stay on the page, $.blockUI starts its game, resulting in a stuck page
$('form[method="post"]').dirtyForms();
$('a').on('click', function(){
$.blockUI();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.dirtyforms/2.0.0/jquery.dirtyforms.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.blockUI/2.70/jquery.blockUI.min.js"></script>
<p>Change the field content to activate DirtyForms, then click on the link.<br>
When the popup appears, click on "cancel" to stay on the page.<br>
Watch blockUI getting fired as the link is going to be followed</p>
<form action="#" method="post">
<input type="text" name="username" required>
<button type="submit">send</button>
</form>
click me after changing field content
Please, any solution?
EDIT: I also tried with stay.dirtyforms and afterstay.dirtyforms events, but they have no effect. defer.dirtyforms seems to work but the event is triggered twice (I put a console.log() to check) and I am not sure this is the way to go...
I've edit my answer: I've added some line of code to disable first the onbeforeunload dialog alert, taken from here. And at the end a link to an answer with another idea you can try.
My idea: you have to prevent the default link action and use the $.blockUI Modal Dialogs methods to open a custom dialog, then catch the link attribute href from the link put it inside a variable and use the variable value for the #yes button of the dialog.
See if this solution can meet your needs
/* beforeunload bind and unbind taken from https://gist.github.com/woss/3c2296d9e67e9b91292d */
// call this to restore 'onbeforeunload'
var windowReloadBind = function(message) {
window.onbeforeunload = function(event) {
if (message.length === 0) {
message = '';
};
if (typeof event == 'undefined') {
event = window.event;
};
if (event) {
event.returnValue = message;
};
return message;
}
};
// call this to prevent 'onbeforeunload' dialog
var windowReloadUnBind = function() {
window.onbeforeunload = function() {
return null;
};
};
var linkToFollow; // href to follow
$('form[method="post"]').dirtyForms();
$('a').on('click', function(e){
e.preventDefault();
windowReloadUnBind(); // prevent dialog
$.blockUI({ message: $('#question'), css: { width: '275px' } });
linkToFollow = $(this).attr('href');
});
$('#no').click(function() {
$.unblockUI();
return false;
});
$('#yes').click(function() {
$(window.location).attr('href', linkToFollow);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.dirtyforms/2.0.0/jquery.dirtyforms.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.blockUI/2.70/jquery.blockUI.min.js"></script>
<p>Change the field content to activate DirtyForms, then click on the link.<br>
When the popup appears, click on "cancel" to stay on the page.<br>
Watch blockUI getting fired as the link is going to be followed</p>
<form action="#" method="post">
<input type="text" name="username" required>
<button type="submit">send</button>
</form>
click me after changing field content
<div id="question" style="display:none; cursor: default">
<h6>Would you like to contine?.</h6>
<input type="button" id="yes" value="Yes" />
<input type="button" id="no" value="No" />
</div>
Other idea taken from another answer: Other idea would be to make a simple jQuery.ajax({}) call before return value in beforeunload as seen in this answer

Using jquery to check if POST is successful

I am trying to write jquery function that will pop up and say Post was successful! and if not, Post was not successful! How could I use a try catch with inputting some jquery?
#using (Html.BeginForm("Admin", "Home", "POST"))
{
<div class="well">
<section>
<br>
<span style="font-weight:bold">Text File Destination:   </span>
<input type="text" name="txt_file_dest" value="#ViewBag.GetTextPath">
<span style="color:black">   Example:</span><span style="color:blue"> \\invincible\\chemistry$\\</span>
<br>
<br>
<span style="font-weight:bold">SQL Connection String:</span>
<input type="text" name="sql_Connection" value="#ViewBag.GetSqlConnection">
<span style="color:black">   Example:</span> <span style="color:blue"> Server=-</span>
<br>
<br>
<button class="btn btn-success" type="submit" >Save Changes</button>
</section>
</div>
}
So I figured out my answer. Just for future reference to anybody that tries this, below is what I did. I placed it above #using (Html.BeginForm("Admin", "Home", "POST")). #Andrew I did try yours, but I could not get it to work. Thanks to everyone for tyring to help me.
<script language="javascript" type="text/javascript">
$(function() {
$("form").submit(function(e) {
$.post($(this).attr("action"), // url
$(this).serialize(), // data
function (data) { //success callback function
alert("Edit successful");
}).error(function () {
alert('failure');
});
e.preventDefault();
});
});
</script>
You'll want to change your HtmlHelper BeginForm declaration slightly, so that an id attribute will be rendered with the element, like this:
#using (Html.BeginForm("Admin", "Home", FormMethod.Post, new { id = "well-form" }))
Now you can add a script above the declaration which traps-and-submits the form and handles the response (success or error).
<script>
$(function() {
// Find the form with id='well-form'
$('#well-form').submit(function() {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function(result) {
alert('Post was successful!');
},
error: function(result) {
alert('Post was not successful!');
}
});
// return false to cancel the form post
// since javascript will perform it with ajax
return false;
});
});
</script>
$.ajax({
url: 'post.html',
success: function(){
alert('success');
},
error: function(){
alert('failure');
}
});
Compounding to Sonu's answer, I have found similar questions regarding this hard to accomplish as the HTML form submit has no callback and it seems that it is recommended to use ajax() when you want a postback confirmation of your form submission.
Please see this Stackoverflow Link.
Could you use the Ajax Events? such as $.ajaxSuccess
http://api.jquery.com/category/ajax/global-ajax-event-handlers/

How do I get my success message to show after ajax submitting form in Jquery ui-tab

I have form on a jQuery ui-tab, which loads data onto a list displayed on the same ui-tab. I have managed to get the data loaded, and the display to return to same tab for a further item to be entered. However depending on the sort order of the list the new item is not always visually obvious, I want to fade in a message, but I can't get it to work along with returning to the same tab without a manual page refresh.
I have attached both the scripts I am trying to use.
Script A
<script> // this one loads data perfectly but no success message appears
$(document).ready(function() {
$("#addtodoitem").live( 'submit' , function(evt) {
evt.preventDefault();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(data) {
$('.ui-tabs-panel:visible').html(data);
$('.itemadded').fadeIn(1000).delay(4000).fadeOut(1000);
};
});
});
});
Script B
<script> //this one shows the message and loads the data, but it also loads another
//copy of ui-tabs overlapping the original
$(document).ready(function() {
$('#addtodoitem').ajaxForm(function(data) {
$('.ui-tabs-panel:visible').html(data);
$(".itemadded").fadeIn(1000).delay(4000).fadeOut(1000);
}); return false;
});
HTML
<div id="tabs_5" class="tabs">
<h2 id="todo5" class="tablecaption">Add To-do</h2>
<p>To raise a new issue please enter the description of the issue below.</p>
<form id="addtodoitem" class="todo" method="post" action="todo_do.php?do=<?=$todo_do != '' ? "edit&to_id={$_GET['to_id']}" : 'add'?>&pub=1&site_ref=NA">
<input type="hidden" value="0" name="status" id="status">
<textarea name="todo" id="todo" placeholder="To raise a new issue, please type the details of the issue here"><?=$todo_free_text?></textarea> <br />
<input type="submit" value="Submit" class="button" />
</form>
<h2 class="tablecaption itemadded">Thank you, your item has been added to the list.</h2>
I got to a satisfactory solution by using a separate refresh link button and php page to cause the refresh after posting so the script is so:
<script type="text/javascript">
$(document).ready(function(){
$('#addtodo').click(function(e){
e.preventDefault();
if($('#todo').val()!="")
{
$.ajax({
type: 'POST',
url: 'todo_do.php',
data: { 'status': $('#status').val(),
'todo': $('#todo').val()
},
success: function(data){
$('.itemadded').slideDown(500).delay(2000).fadeOut(500);
$('.refreshtodo').slideDown(500);
$('#addtodoitem')[0].reset();
$('#tabs > ul').tabs({selected: 5 });
}
});
}
else{$('.nothing').slideDown(500).delay(1000).fadeOut(500)}
});
});
and the extra php page just contains
<?
header("Location: resident.php#tabs_5");
?>

Why can't I change page after submitting form?

I should see: "Hello" after hitting submit, but I don't. Why?
http://jsfiddle.net/GbfLG/1/
<div data-role="page" id="create">
<script type="text/javascript">
alert("HERE");
$('#form').submit(function() {
$.post("/").success(function(resp) {
alert("RET");
$.mobile.changePage($("#final"));
});
return false;
});
</script>
<div data-role="content">
<form id="form">
<input type="submit" name="g" value="Submit" id="g"/>
</form>
</div>
</div>
<div data-role="page" id="final">
Hello
</div>​
jQM has a different set of rules then the normal web page. You have used your java script in the wrong place. With jQM, if possible write all you js code in separate file/files.
This is a fix made to your jsFiddle code, it is working now, I have just put it in right context. Your js code was not changed a bit.
Example:
$('#create').live('pagebeforeshow',function(e,data){
$('#form').submit(function() {
$.post("/").success(function(resp) {
$.mobile.changePage($("#final"));
});
return false;
});
});
Your form is submiting - the return false; isn't working as it should.
Try..
$('#form').submit(function(e) {
e.preventDefault();
e.stopPropagation();
... stuff ...
});
Also in your fiddle you haven't defined $.changePage so it comes out as 'undefined'.

Edit sortable selectable li with jquery-ui

I want to allow editing list items in a selectable / sortable list.
Here is a list example:
http://jsbin.com/aweyo5
credits to rdworth
So I would we go about allowing the user to edit items? I know how to update/change their text but how I do I got about allowing the user to input text directly into the list item?
Here is a working answer :
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.19.custom.min.js"></script>
<script type="text/javascript" src="jeditable.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
function makeEditable()
{
$('.editable').editable(function(value, settings)
{
/* Debug
console.log(this);
console.log(value);
console.log(settings);
*/
return(value);
});
}
function makeDeletable()
{
$('a.delete').click(function(e)
{
e.preventDefault();
$(this).parent().remove();
});
}
function addTopic(topicName)
{
$("ul.#topics").append('<li><span class="editable">' + topicName +'</span><a class="delete" href="">delete</a></li>');
makeEditable();
makeDeletable();
}
makeEditable();
makeDeletable();
$( "#topics" ).sortable();
$("form").submit(function() {
addTopic($('input[name=topic]').val());
return false;
});
$('a#add').click(function(e)
{
e.preventDefault();
addTopic($('input[name=topic]').val());
});
});
</script>
<ul id="topics">
<li><span class="editable">topic 1</span><a class="delete" href="">delete</a></li>
<li><span class="editable">topic 2</span><a class="delete" href="">delete</a></li>
<li><span class="editable">topic 3</span><a class="delete" href="">delete</a></li>
</ul>
<form>
New topic: <input type="text" name="topic" /><br />
</form>
<a id="add" href="">add</a>
Hope it helps :)
You can get jeditable here:
http://www.appelsiini.net/projects/jeditable

Resources