Alex Fariñas Alex Fariñas - 3 months ago 10
C# Question

change div text with ajax not working

What am I doing wrong?

I try to change div text with ajax... but doesn't do anything... I guess the problem is in my controller method..

This my div

<div id="div1">
text to change
</div>

<button>change text</button>

@section scripts{
<script>
$(document).ready(function() {
$("button").click(function () {
$.ajax({
url: "/Home/ChangeText", success: function (result) {
$("#Div1").html(result);
}
});
});
});
</script>
}


This my Controller

public JsonResult ChangeText()
{
var result = "New Text";

return Json(result, JsonRequestBehavior.AllowGet);
}


Note: when is running it's enter to method 'ChangeText' but it doesn't print the result(New Text) on my view

Answer

Try this:

<div id="div1">
   text to change
</div>

<button type="button">change text</button> // or type="submit"

@section scripts{
<script>
    $(document).ready(function() {
        $("button").click(function () {
            $.ajax({
                url: "/Home/ChangeText", success: function (result) {
                    $("#div1").html(result); // Div1 != div1
                }
            });
        });
    });
</script>
}