Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What causes $.ajax to result a full post-back

Could someone tell me what causes a $.ajax 'POST' request to result a full post-back (full page refresh)?

I'm using the $.ajax 'POST' in the ASP.NET MVC context, where the view is calling the controller method (which returns a JSON result) through a $.ajax 'POST' request.

The code is below.


// View.
<button id="save" onclick="saveClick()" />

// View.
<script type="text/javascript">

    function saveClick() {
        if (!$("form").valid()) {
            return false;
        }

        $.ajax({
            url: '@Url.Action(@MVC.Ticket.ActionNames.SaveTicket, @MVC.Ticket.Name)'
            type: 'POST',
            data: JSON.stringify(getJsonTicket()),
            dataType: 'json',
            contentType: "application/json",
            cache: false,
            success: function(data) {
                alert(data.SaveResult);
            }
        });

        return true;
    }

    function getJsonTicket() {
        ...
    }

</script>

// Controller action.
public virtual JsonResult SaveTicket(Ticket newTicket)
{
    try
    {
        TicketManager.SaveTicket(newTicket);
        return Json(new CreateTicketViewModel {SaveResult = "success"});
    }
    catch
    {
        return Json(new CreateTicketViewModel { SaveResult = "error" });
    }
}
like image 423
dan Avatar asked Jan 10 '13 07:01

dan


2 Answers

Do

<button id="save" type="button" onclick="saveClick()" />

to make sure form is not posted by this button.

Explanation:

The default value for the type attribute of button elements is "submit".

https://stackoverflow.com/a/3315016/1014281

like image 61
iappwebdev Avatar answered Oct 11 '22 10:10

iappwebdev


Are you sure that you are using a <button> and not <input type="submit">? Because if you don't prevent the button from submitting it will submit the form (full postback).

<input type="submit" onclick="return saveClick()"> should work as long as saveClick() always return false.

like image 45
jgauffin Avatar answered Oct 11 '22 10:10

jgauffin