Reputation: 97
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
Upvotes: 3
Views: 1967
Reputation: 2785
You wrote <div id="div1">
and $("#Div1").html(result);
. However div1
not equals Div1
, first symbol is big (upper case). JavaScript is sensitive to upper and lower case.
The type attribute specifies the type of button. Always specify the type attribute for the <button>
element. Different browsers may use different default types for the <button>
element. If you want send data to controller - write type of button type="button"
or type="submit"
.
Attribute values and descriptions:
button
- The button is a clickable buttonsubmit
- The button is a submit button (submits form-data)reset
- The button is a reset button (resets the form-data to its initial values)Try this code:
<div id="div1">
text to change
</div>
<button type="button">change text</button>
@section scripts{
<script>
$(document).ready(function() {
$("button").click(function () {
$.ajax({
url: "/Home/ChangeText", success: function (result) {
$("#div1").html(result); // Div1 != div1
}
});
});
});
</script>
}
Upvotes: 4