Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use JavaScript to submit Ajax.BeginForm()

I'm typing this question away from my computer so I don't have the exact code, but the question might be straightforward enough without it.

When I have a submit button directly within an Ajax form and I click the button directly to submit, everything works fine, and as expected. The Ajax.Form POSTs back to the controller which returns a partial view that is rendered inside the current View that I have.

But what I need is for a button to be clicked in the Ajax.Form, and for a JavaScript function to run. The JavaScript function will do some vaildation which decides whether to submit the Ajax.Form or not.

I have tried putting 2 buttons in the Ajax.Form, a hidden submit button and a regular button. I used the onclick event of the regular button to call my JavaScript function which then called the click method of the hidden submit button. (I have also tried just submitting the Ajax.Form directly with document.forms[formname].submit() )

This sort of works.. But not correctly for some reason. The Ajax.Form POSTs back to the controller but when a partial view is returned from the controller, the partial view is the only thing rendered, and it is rendered as basic html with no css/bootstrap.

What is the difference between actually clicking the submit button and doing so programmatically?

How can Achieve what I am trying to do?

Edit

 @using (Ajax.BeginForm("GetInstructorInfo", "Incident", FormMethod.Post, new AjaxOptions { OnBegin = "lookupInstructor();", UpdateTargetId = "InstructorInfo" }, new { @class = "form-inline", role = "form", @id = "instructorInfoForm", @name = "instructorInfoForm" }))
{

//code in here

}

Edit 2 / 3:

<script>
    function lookupInstructor()
    {
        if ($('input[name="Instructors['+userInputInstructor+'].Username'+'"]').length > 0)   //Don't allow user to enter multiple instances of the same Instructor
        {
            document.getElementById("InstructorUsername").value = ''; //clear textbox value
            return false;
        }
        var userInputInstructor =  document.getElementById("InstructorUsername").value;
        $.ajax({
            url: '@Url.Content("~/Incident/LookUpUsername")',
            data: { userInput: userInputInstructor },
            success: function (result) {
                if (result.indexOf("not found") != -1){ //if not found

                    $("#InstructorNotFoundDisplay").show();
                    document.getElementById("InstructorUsername").value = ''; //clear textbox value

                    $('#InstructorInfo').empty();
                    return false;
                }
                else {
                    $("#InstructorNotFoundDisplay").hide();
                    return true;
                }
            }
        });
  }
</script>
like image 638
Michael Avatar asked Apr 29 '26 12:04

Michael


1 Answers

You can use the OnBegin() ajax option to call a function that runs before the form is submitted (and return false if you want to cancel the submit). For example

function Validate() { 
    var isValid = // some logic
    if (isValid) { 
        return true; 
    } else { 
        return false;
    }
}

and then in the Ajax.BeginForm() options

OnBegin = "return Validate();"

Edit

Based on the edits to the question and the comments, you wanting to call an ajax function in the OnBegin() option which wont work because ajax is asynchronous. Instead, use jQuery.ajax() to submit you form rather than the Ajax.BeginForm() method (and save yourself the extra overhead of including jquery.unobtrusive-ajax.js).

Change Ajax.BeginForm() to Html.BeginForm() and inside the form tags replace the submit button with <button type="button" id="save">Save</button>and handle its .click() event

var form = $('#instructorInfoForm');
var url = '@Url.Action("GetInstructorInfo", "Incident")';
var target = $('#InstructorInfo');

$('#save').click(function() {
  if ($('input[name="Instructors['+userInputInstructor+'].Username'+'"]').length > 0) {
    ....
    return; // exit the function
  }
  $.ajax({
    ....
    success: function (result) {
      if (result.indexOf("not found") != -1) {
        ....
      }
      else {
        $("#InstructorNotFoundDisplay").hide();
        // submit the form and update the DOM
        $.post(url, form.serialize(), function(data) {
          target.html(data);
        });
      }
    }
  });
});

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!