Using jquery to check if POST is successful - asp.net-mvc

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/

Related

Second time partialview not loading to div via from .ajax() in MVC4

I have issue loading partialview to div second time. I have checked previous posts in SO but non of them really helped me. So I am posting my issue here.
index.cshtml
<div id="DivEmailContainer" style="display:block" class="row">
</div>
_EditEmail.cshtml
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-2 ">
<input type="submit" value="Save" class="btn btn-success width100per" />
</div>
script type="text/javascript">
$(function () {
$("#frmEmail").validate({
rules: {
...
submitHandler: function (form) {
$.ajax({
url: 'PostEditEmail',
type: 'Post',
data: $(form).serialize(),
success: function (result) {
alert("In success");
$('#DivEmailContainer').html(result);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.responseText);
alert(thrownError);
},
complete: function (xhr, textStatus) {
alert(xhr.responseText);
alert(textStatus);
}
});
}
});
controller
public PartialViewResult PostEditEmail(string actiontype, FormCollection col)
{
var communicationLocation = string.Empty;
....
return PartialView("_EditEmail", memberemail);
}
First time partialview loading into DivEmailContainer to error. If submit again partialview loading full post back. not even it is calling submitHandler.
Only thing I observed is 1st time submit <form post was /ContactInformation/GetEditEmailbut when I submit second time <form post was /ContactInformation/PostEditEmail.
What could be wrong?
update
second time Forloop scriptblock loading. May be it is issue with Forloop?
#using (Html.BeginScriptContext())
{
Html.AddScriptBlock(
update
issue with forloop htmlhelper, not with ajax. secondtime script is not loading. #Russ Cam can help on this.
from my experience putting script in a partial leads to very inconsistent results. expecially with the script being inserted into the middle of the page. I would highly recommend that you pull your script from the partial and put it on the main page. Since the partial is loaded after the page load you will need to tie the script to the partial one of 2 ways.
1. tie the events to the document
$(document).on('click', '.targetClass', function(){
//do stuff
});
for example to put an id on your input and change it to a button
<input type="button" value="Save" id="btnSave" class="btn btn-success width100per" />
your click event would then be
$(document).on('click', '#btnSave', function(){
//your ajax call here
});
being tied to the document this click event would fire even though the input is inserted into the document after load
put the script in a function that is called after the partial is loaded
change your
$(function () {
to
function partialScript(){
and call this function after the partial is loaded
$('#DivEmailContainer').html(result);
partialScript();
Try to load partial view like this
$("#DivEmailContainer").load('#Url.Action('ActionName', 'ControllerName')', function () {
//Perform some operation if you want after load.
});

Quick Search Form Not Submitting MVC

I currently have a partial view that renders at the top of every page on the site. The point of this partial view is to provide a form that lets the user do a quick search. I have set the partial view form up as follows:
#using (Html.BeginForm())
{
<div class="col-md-7" style="text-align: right">
<div class="input-group input-group-sm col-sm-6 pull-right">
#Html.TextBox("caseReference")
<button type="submit">
<i class="fa fa-search"></i>
</button>
</div>
</div>
}
#Html.Partial("_MainNavigation")
</div>
</div>
</nav>
<script type="text/javascript">
$(function () {
$("form").on("submit", function (event) {
event.preventDefault();
var request = { caseReference: $('#caseReference').val() };
submitForm(request, '#Url.Action("CaseSearch", "QuickSearch", new { area = "Search" })');
});
});
</script>
However under the page source the form action renders as a request to the home page with a post action. I have read numerous examples and this task seems very straight forward. Would it be a better idea to use the parameters on the #html.BeginForm() method?
So after spending a few hours researching, I have finally got the quick search functionality to work on the home page of my site. In the razorview I have the following code:
<div class="input-group input-group-sm col-sm-6 pull-right">
#Html.Kendo().MaskedTextBox().Name("name").Mask("000000/0000").Deferred()
<button id="search" type="submit">
<i class="fa fa-search"></i>
</button>
<script type="text/javascript">
$(function () {
$("#search").on("click", function (event) {
event.preventDefault();
var value = $('#name').val();
value = value.replace(/[/]/g, "_");
var refVal = value;
var url = '#Url.Action("Action", "Contoller", new { area = "Area" })' + '//' + refVal;
$.ajax({
type: 'GET',
url: url,
cache: false,
dataType: 'json',
contentType: "application/json;",
success: function (result) {
if (result.success) {
window.location.href = result.url;
}
else {
bootbox.alert(result.message);
}
}
});
});
});
However in regards to the following line:
var url = '#Url.Action("Action", "Contoller", new { area = "Area" })' + '//' + refVal;
If I hard code the url and append the search term it works on the Home page because we are at the root directory but from other pages it fails, To get around this I tried to use #Url.Action. However this is producing the following result in the html soure code:
var url = '' + '//' + refVal;
Is there a certain way to use the URL.Action method from withing JS?

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");
?>

How can I return the HTML from MVC controller to a div in my view

I'm trying to return the generated HTML string to the view to dynamically generate a HTML table with results. I'm not able to get the returned HTML string any suggestions and help is greatly appreciated.
Here is my Controller code
public ActionResult ValidateTrams()
{
string html = "";
if (Request.Files.Count == 0 || Request.Files[0].ContentLength == 0)
{
}
else
{
html = ProcessTextFile(Request.Files[0].InputStream);
}
return View(html);
}
I'm trying to grab this returned result in jquery like this
$('#tramsView').live('click', function () {
$.ajax({
url: '/Booking/ValidateTrams',
type: 'POST',
dataType: 'jsonp',
success: function (data) {
alert(data);
$('#TramsViewFrame').html(data);
},
error: function (jqxhr, textStatus, errorThrown) {
$(window).hideWaitScreen();
if (confirm(errorThrown)) { window.location.reload(); }
}
});
});
Finally Below is the CSHTML for the form. Here I'm reading a file from a form with a button type submit
<form action="#" method="post" enctype="multipart/form-data" class="forms" name="form"
id="frmvalidate">
<table>
<tr>
<td>
<input type='file' name='trams' id='ValidatetramsFile' />
</td>
</tr>
<tr>
<td>
<br />
<input name="cbDisplayUmatched" id="cbDisplayUmatched" type="checkbox" value="" checked="true" />
<label style="text-decoration: none; outline: none; font-size: 1.1em; padding: 3px 0 0px 0;">
Display rows that were <strong>NOT</strong> parsed</label>
</td>
</tr>
<tr>
<td>
<br />
<div class="buttons">
<button type="submit" value="VIEW" class="ui-state-default ui-corner-all" id="tramsView">VIEW</button>
</div>
</td>
</tr>
</table>
</form>
Thanks for your time and really appreciate your help. Kind Regards!!!
you can return HTML from action like this,
return Content(html, "text/xml");
It sounds as if your form is still submitting a normal postback, so any asynchronous calls that you're doing are being lost.
Try preventing the default form submission taking place with the following:
$('#tramsView').live('click', function (evt) {
evt.preventDefault();
// ... rest of your code
});
Incidentally, in this case, if all you're doing is updating the html on your #TramsViewFrame, you could just use the slightly simpler $.load() method:
$('#tramsView').live('click', function (evt) {
evt.preventDefault();
$('#TramsViewFrame').load('/Booking/ValidateTrams');
});
Make these changes
Give the attribute HttpPost on top of your controller
[HttpPost]
public ActionResult ValidateTrams()
return the string as Json like this from the controller.
return Json(new { success = html });
Finally change your dataType from jsonp to json
$('#tramsView').live('click', function() {
$.ajax({
url: '/Booking/ValidateTrams',
type: 'POST',
dataType: 'json',
success: function(data) {
alert(data.success);
$('#TramsViewFrame').html(data.success);
},
error: function(jqxhr, textStatus, errorThrown) {
$(window).hideWaitScreen();
if (confirm(errorThrown)) {
window.location.reload();
}
}
});
});​
P.S: If you are using the latest version of jQuery (1.7+), please change the .live handler to .on handler. Not mandatory :)
In your controller since you are using ajax post you need to return as JSON it would be something like this
return Json(html);
i think this is another way relevant to your scenario How can I return the HTML from MVC controller to a div in my view
http://mazharkaunain.blogspot.com/2011/02/how-to-use-aspnet-mvc-javascriptresult.html
instead of storing in "string" store html codes in following format:
HtmlString s = new HtmlString("<html coding/>");
ViewData["Id_as_per_your_choice"] = s;
return View("page_you_want to_respond");
then place "<%: ViewData["Id_Same_as_that_in_above_code"] %>" where ever you want that html code to appear......simple.....
but make initial value of Viewdata as null in "index()"method so that code doesnot appear on page load....

Confirm messagebox when delete, $.post

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;"

Resources