Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:&#160;&#160;&#160;</span>
        <input type="text" name="txt_file_dest" value="@ViewBag.GetTextPath">
        <span style="color:black">&#160;&#160;&#160;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">&#160;&#160;&#160;Example:</span> <span style="color:blue"> Server=-</span>
        <br>
        <br>
        <button class="btn btn-success" type="submit" >Save Changes</button>
    </section>
</div>

}

like image 820
Big Poppa Avatar asked Apr 25 '13 01:04

Big Poppa


2 Answers

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>
like image 110
Big Poppa Avatar answered Nov 10 '22 11:11

Big Poppa


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>
like image 27
Andrew Avatar answered Nov 10 '22 09:11

Andrew