I have an Ajax call that works just fine when I do not have the unobtrusive Ajax script referenced. When I add it to the page it prevents the onSuccess Javascript from firing. When trying to render a partial view with the script referenced everything works just fine. Also, what is weird is that the onSuccess function triggers when the page first loads.
To clarify, I have the script referenced at the bottom of my DOM and the web.config file has it enabled. When using the browser debug, I see that the AJAX is successful, it just does not make it to the javascript onSuccess method. Here is my code:
Reference to the scripts:
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@Scripts.Render("~/Scripts/jquery-ui-1.10.4.min.js")
@Scripts.Render("~/Scripts/jquery.unobtrusive-ajax.min.js")
@Scripts.Render("~/Scripts/jquery.validate.unobtrusive.min.js")
@Scripts.Render("~/Scripts/AAData.js")
@RenderSection("scripts", required: false)
</body>
</html>
AJAX Call:
@using (Ajax.BeginForm("Search", "Home", new AjaxOptions { OnSuccess = "onSuccess", HttpMethod = "GET", UpdateTargetId = "Search" }))
{
<div class="col-md-6 form-inline">
<div class="form-group" style="width:85%;">
<div class="right-inner-addon">
<i class=" glyphicon glyphicon-search"></i>
<input type="text" data-autocomplete="@Url.Action("Quicksearch","Home")" class="form-control" placeholder="Search" name="q" value="@ViewBag.CurrenetFilter" />
</div>
</div>
<div class="form-group">
<button class="btn btn-default form-inline" type="submit">Search</button>
</div>
<br />
</div>
}
Controller:
public ActionResult Search(string q, int? page, string catb = null)
{
return Json(new { url = Url.Action("Search", "Items", new { query = q, pageNum = page, categoryB = catb }) }, JsonRequestBehavior.AllowGet);
}
Javascript:
var onSuccess = function (result) {
if (result.url) {
// if the server returned a JSON object containing an url
// property we redirect the browser to that url
window.location.href = result.url;
}
I shifted the ordering of the scripts and updated jquery to the latest in order to fix this. Scripts are in the following order:
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/Scripts/jquery.validate.min.js")
@Scripts.Render("~/Scripts/jquery.validate.unobtrusive.min.js")
@Scripts.Render("~/Scripts/jquery.unobtrusive-ajax.min.js")
Jquery is version 2.1.1
unobtrusive ajax is 3.1.2