Lord Vermillion
Lord Vermillion

Reputation: 5424

How to prevent ajax get from refreshing MVC page

This is my javascript

$.ajax({
    type: 'GET',
    data: {
        _rnd: new Date().getTime()
    },
    url: '@Url.Content("~/Home/RegisterDevice")' + '?name=' + '@Session["username"]' + '&phonenumber=' + $("#phonenumberInput").val() + '&imei=' + $("#imeiInput").val(),
    dataType: 'json',
    async: 'true',
    success: function (data) {
        console.log(data);
        //$("#regdiv").hide();
        //$("#resdiv").append(data);
        //$("#resdiv").show();
        return false;
    }
});

My html has a button to trigger the javasript

<button class="btn btn-success" onclick="RegisterDeviceDetails()">Fortsätt</button>

My MVC Controller has some logic and returns SUCCESS OR FAIL.

return Json("SUCCESS", JsonRequestBehavior.AllowGet);

My problem is that the page refreshes, so the appended response is removed as its refresh. How can i prevent the refresh?

Upvotes: 2

Views: 3190

Answers (1)

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93621

Don't mix inline event handlers with jQuery. It separates the event registration from the event code for no good reason and stops extra jQuery event features from working (multiple events etc)

Suggest adding an id to your button for easy access:

<button id="register" class="btn btn-success">Fortsätt</button>

Then use a standard jQuery event handler:

$('#register').click(function(e){
    e.preventDefault();
    RegisterDeviceDetails();
});

e.preventDefault() will stop the default button behaviour.

You can also use return false here:

$('#register').click(function(e){
    RegisterDeviceDetails();
    return false;
});

return false in a jQuery event handler does the same as both e.preventDefault() and e.stopPropagation().

The return false inside your success handler does nothing as the function actually returned much earlier. It simply started an async operation. success gets called back much later.

Upvotes: 5

Related Questions