0

Is there a way I can get the returned value from an action using .submit event listener in jQuery? I have a problem which is when the action is completed it returns a JSON file and my browser navigates to an empty page and just display the JSON returned. I don't want that to happen, I want to be able to read the JSON result and based on it decide what to do.

Here's my POC: View:

@using (Html.BeginForm("SubmitTest", "DMS", FormMethod.Post, htmlAttributes: new { id = "formId" }))
        {
            <input type="submit" value="Sumbit" />
        }    

Controller:

public JsonResult SubmitTest()
        {
            return Json("Done");
        }

Script:

$(document).ready(function () {
        $("formId").submit(function () {
            alert("Submitted");
        });
    });
0

2 Answers 2

1

you can add event.preventDefault or return false to prevent the default event from occurring . so it won't navigate to an empty page.

$(document).ready(function () {
        $("formId").submit(function () {
            alert("Submitted");
            return false;
        });
    });

EDIT: if you want to get the response you need to make an ajax request and get the form data from the fields. you can't get the response with submit function.

$(document).ready(function () {
        $("formId").submit(function () {
            /// make an AJAX request
             $.post(
 $(this).attr('action'), //// action url
 $(this).serialize(), //// serialize form fields
function(json) {
        alert(json);/// json response
    }, 'json');

            return false; /// prevent navigation
        });
    });
Sign up to request clarification or add additional context in comments.

2 Comments

Won't this prevent submitting the form to the server?
@Tha'erAl-Ajlouni no it won't . it submits the form but prevents navigation
0

Use an AJAX form instead of the HTML form, this way you can check the response after it is submitted and do whatever you need using the OnSuccess handler.

For detailed info refer to this article

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.