Lord Vermillion Lord Vermillion -4 years ago 95
jQuery Question

How to prevent ajax get from refreshing MVC page

This is my javascript

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) {
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?

Answer Source

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:


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

You can also use return false here:

    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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download