Febin J S
Febin J S

Reputation: 1368

Calling controller method from JQuery calls occurs twice and also returning error?

Hi guys i have posted a similar post before, but that is for another, now i face a strange and odd issue with my Jquery code. Here i was calling a controller method using Jquery but it is calling twice , so that may cause two entries in my db. Here is what i have written in my JQuery

<script type="text/javascript">
    $('#btnSubmit').click(function () {
        var instructorUrl = '@Url.Action("ApplyToBecomeInstructor", "InstructorApplication")';
        var currentUser = '@Model.CurrentUserId';
        var user = [];
        var educationList = [];
        var experience = $('#Experience').val();
        var isWilling = $('#WillingToTravel').is(":checked");
        $('#editorRows .editorRow').each(function () {
            var education = {
                UniversityOrCollege: $(this).find('.university').val(),
                AreaOfStudy: $(this).find('.area').val(),
                Degree: $(this).find('.degree').val(),
                YearReceived: $(this).find('.year').val()
            }
            educationList.push(education);
        });
        var applicationFromView = {
            EducationalBackgrounds: educationList,
            CurrentUserId: currentUser,
            Experience: experience,
            WillingToTravel: isWilling
        }
        $.ajax({
            type: 'POST',
            url: instructorUrl,
            dataType: 'JSON',
            async: false,
            data: JSON.stringify(applicationFromView),
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                return false;
            },
            error: function (data) {
            alert(xhr.status);
            alert(thrownError);
            alert(xhr.responseText);
                return false;
            }
        });
    });
</script>

and my controller action looks like this

[HttpPost]
public ActionResult ApplyToBecomeInstructor(InstructorApplicationViewModel applicationFromView)
{
    Student thisStudent = this.db.Students.Where(o => o.StudentID == applicationFromView.CurrentUserId).FirstOrDefault();
    List<PaulSchool.Models.EducationalBackground> educationList = new List<EducationalBackground>();
    foreach (var educate in applicationFromView.EducationalBackgrounds)
    {
        var education = new Models.EducationalBackground
        {
            YearReceived = educate.YearReceived,
            Degree = educate.Degree,
            AreaOfStudy = educate.AreaOfStudy,
            UniversityOrCollege = educate.UniversityOrCollege
        };
        educationList.Add(education);
    }
    var instructorApplication = new InstructorApplication
    {
        BasicInfoGatheredFromProfile = thisStudent,
        Experience = applicationFromView.Experience,
        EducationalBackground = new List<Models.EducationalBackground>(),
        WillingToTravel = applicationFromView.WillingToTravel
    };
    instructorApplication.EducationalBackground.AddRange(educationList);
    this.db.InstructorApplication.Add(instructorApplication);
    this.db.SaveChanges();
    return this.Redirect("Index");
}

Error message showing is JSON Parsing error.. but it is confusing to me. I really wondered why this is happening, can anybody please take a look and help me?

Upvotes: 0

Views: 3024

Answers (2)

gdoron
gdoron

Reputation: 150253

This is what your code does:

$('#btnSubmit').click(function () { // attach a click handler for the button.
...
...
// Look for elements inside the button... 
UniversityOrCollege: $(this).find('.university').val(), 

Change from click to submit:

$('#formId').submit(function (e) { 
    ...
    // Now "this" is the form - not the button.
    // Look for elements inside the <form>
    UniversityOrCollege: $(this).find('.university').val(), 
    // Prevent the default form submition
    return false // Or: e.preventDefault();

Another tip: use jQuery serialize function.

Upvotes: 1

six8
six8

Reputation: 2990

$('#btnSubmit').click() will fire every time the button is pressed. Often users double click buttons even though it only needs a single click or if you don't give any indication that something is happening they get impatient and click it again. You need some way to determine if the request has been made. There's ways to do this client and server side. The easiest client side way is to disable the button to prevent multiple clicks:

$('#btnSubmit').click(function () {
    // Disable the button so it can't be clicked twice accidentally
    $('#btnSubmit').attr('disabled', 'disabled');
    //...
    $.ajax({
        //...
        complete: function() {
            // Make sure we re-enable the button on success or failure so it can be used again
            $('#btnSubmit').removeAttr('disabled');
        }
    });
});

Upvotes: 0

Related Questions