0

Here is my View:

@using (Ajax.BeginForm("Accept", "FriendRequest", new { id = m.FriendRequest.Id }, new AjaxOptions { OnSuccess = "DoSomthing" })) {
    <input type="button" value="Accept" onclick="submitAjaxform(this);" />
}

Here is the signature of the DoSomething function:

function DoSomthing(a,b,c) {
    alert(a.Status);
}

Here is my javascript function which submits the request:

function submitAjaxform(btn) {
    var form = btn.form;
    var data = $(form).serialize();
    var action = $(form).attr('action');
    var onsuccess = $(form).attr('data-ajax-success');
    $.post(action, $(form).serialize(), function (data, status, xhr) {
         var x = onsuccess + ".apply([" + data + "]);";
         eval(x);
    });
}

Here is my action method:

public JsonResult Accept(long id) {
    return Json(new {status=true,message="some message"});
}

When I run the code. The posting works well, but the onsucess of the jQuery function gives the following error in the console:

missing ] after element list

I don't understand how to fix it. Help will be appreciated.

Edit: Thanks to Rich, here is what worked finally

function submitAjaxform(btn) {
    var form = btn.form;
    var data = $(form).serialize();
    var action = $(form).attr('action');
    var onsuccess = $(form).attr('data-ajax-success');
    $.post(action, $(form).serialize(), function (data, status, xhr) {
         window[onsuccess](data);

    });
}

Found the answer from here Calling a JavaScript function named in a variable

Community
  • 1
  • 1
Parminder
  • 3,088
  • 6
  • 37
  • 61
  • I think this is a scope issue with the `onsuccess` variable. Try moving that variable into the success handler of the `post()` method. Also I'd suggest trying to refactor your code to not use `eval()`. – Rory McCrossan Dec 02 '11 at 11:30
  • Thanks Rory, I am working with the solution from rich now. – Parminder Dec 02 '11 at 12:00

2 Answers2

0

Your data variable is different inside the scope of the success callback, since you are not using the one declared outside I assume your code should be:

function submitAjaxform(btn) {
  var form = btn.form;
  var data = $(form).serialize();
  var action = $(form).attr('action');
  var onsuccess = $(form).attr('data-ajax-success');
  $.post(action, $(form).serialize(), function () {
     var x = onsuccess + ".apply([" + data + "]);";
     eval(x);
  });
}

Alternatively, the data passed as the first parameter of the callback is already an object so you only need to eval your onsuccess, like so:

function submitAjaxform(btn) {
  var form = btn.form;
  var action = $(form).attr('action');
  var onsuccess = $(form).attr('data-ajax-success');
  $.post(action, $(form).serialize(), function (data) {
     eval(onsuccess).apply([data]);
  });
}

As an aside, I would recommend not using eval wherever possible, it is expensive and allows potentially untrusted javascript to run in a browser. If it is possible to refactor your code to not require it, then you should.

Rich O'Kelly
  • 41,274
  • 9
  • 83
  • 114
  • Thanks rick, but now in function OnSuccess(a) { alert(a.Status); } is undefined. Thanks a lot for the answer. – Parminder Dec 02 '11 at 11:54
  • Correcting. a.Status is undefined. – Parminder Dec 02 '11 at 11:54
  • @Parminder this is not surprising, the AjaxOptions.OnSuccess callback is not called with any parameters. Since you are using jQuery to do your form submission, you already know that the post succeeded when the success callback is called. What do you expect `a` to be? – Rich O'Kelly Dec 02 '11 at 12:04
  • Thanks Rich, I know the function makes sure that it succeeded, but I need to know the status returned from the controller action, so basically in my DoSomthing function, I need to get the value of status (a.Status). But it is undefind, where as if I check it in submitAjaxform's on success event, its available. after apply function it disappears. – Parminder Dec 02 '11 at 18:16
0

I suggest other approach to do it...

@model competestreet.com.Models.Page
@{
    ViewBag.Title = "Contact & Support";
    Layout = "~/Views/Shared/_LayoutInner.cshtml";
}

<script src="@Url.Content("~/Scripts/ValidateContactForm.js")" type="text/javascript"></script>
<h2 class="title">
    <span class="text-contact">Contac<span>t</span></span></h2>
<div class="box">
    <div class="t">
    </div>
    <div class="c">
        <div class="content">
            <div class="main-holder">
                <div id="sidebar">
                    <ul>
                        <li class="active"><a href="#">General</a></li>
                        <li><a href="#">Our Mission</a></li>
                        <li><a href="#">Sub Navigation</a></li>
                        <li><a href="#">Sub Navigation</a></li>
                    </ul>
                </div>
                <div id="content">

                    <form class="cmxform" id="contactForm" method="get" action="">
                    <div id="contactFormFields">

                    <table>
                        <tr>
                            <td style="width: 150px;">
                                E-Mail
                            </td>
                            <td>
                                <input id="cemail" type="text" value="E-mail" name="email" size="25" class="required email" /><em id="emEmail">*</em>
                            </td>
                        </tr>
                        <tr>
                            <td style="width: 150px;">
                                Name
                            </td>
                            <td>
                                <input id="cname" name="name" type="text" value="Name" size="25" class="required" maxlength="100" /><em id="emName">*</em>
                            </td>
                        </tr>
                        <tr>
                            <td style="width: 150px;">
                                Subject
                            </td>
                            <td>
                                <input id="csubject" name="subject" type="text" value="Subject" size="25" class="required" maxlength="200" /><em id="emSubject">*</em>
                            </td>
                        </tr>
                        <tr>
                            <td style="width: 150px; vertical-align: top;">
                                Message
                            </td>
                            <td>
                                <textarea id="cmessage" maxlength="1000" type="text" value="Your Message" name="comment" cols="27" rows="10" class="required"></textarea><em id="emMessage">*</em>
                            </td>
                        </tr>
                        <tr>
                            <td style="width: 150px;">
                            </td>
                            <td>
                                <input type="submit" value="Send" class="input-btn" onclick="SendContactForm(); return false;" style=" width:100px; color: Black;" />
                            </td>
                        </tr>
                    </table>

                    </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    <div class="b">
    </div>
</div>

JavaScript of ValidateContactForm.js:

$('#thankYou').hide();

var isEmail_re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
function isEmail(s) {
    return String(s).search(isEmail_re) != -1;
}

function isBlank(s) {
    if (!s || s.length == 0) {
        return true;
    }
    // checks for a non-white space character 
    // which I think [citation needed] is faster 
    // than removing all the whitespace and checking 
    // against an empty string
    return !/[^\s]+/.test(s);
}


function SendContactForm() {
    var isFormValid = true; 

    var isEmailOk = isEmail($('#cemail').val());
    if (isEmailOk == false) {
        $('#emEmail').css('color', 'red');
        isFormValid = false;
    }
    else {
        $('#emEmail').css('color', 'black');
    }

    var isNameOk = isBlank($('#cname').val());
    if (isNameOk) {
        $('#emName').css('color', 'red');
        isFormValid = false;
        //alert('!');
    }
    else {
        $('#emName').css('color', 'black');
    }

    var isSubjectOk = isBlank($('#csubject').val());
    if (isSubjectOk) {
        $('#emSubject').css('color', 'red');
        isFormValid = false;
    }
    else {
        $('#emSubject').css('color', 'black');
    }

    var isMesageOk = isBlank($('#cmessage').val());
    if (isMesageOk) {
        $('#emMessage').css('color', 'red');
        isFormValid = false;
    }
    else {
        $('#emMessage').css('color', 'black');
    }

    if (isFormValid) {
        $.post("/Home/SendContactForm", { email: $('#cemail').val(),
            name: $('#cname').val(),
            subject: $('#csubject').val(),
            message: $('#cmessage').val()
        },
                 function (data) {
                         $('#contactFormFields').hide('slow');
                    if (data.length > 0) {
                          $('#contactForm').html(data);
                          $('#thankYou').show('fast');                       
                        }
         });
    }
}

and C#

public JsonResult SendContactForm(string email, string name, string subject, string message)
{
    StringBuilder sb = new StringBuilder();
    sb.Append("<div id='thankYou' class='thankyou'>Thank you! We are going to contact you as soon as it possible!</div>");
    return Json(sb.ToString());
}

So you don't need to use Ajax.BeginForm()

NoWar
  • 36,338
  • 80
  • 323
  • 498