Bootstrap alert won't show after AJAX call in ASP.Net Razor Pages - ajax

I'm trying to display a Bootstrap Alert after an AJAX call within an ASP.Net Core Razor Pages application. The AJAX call to the Page Model handler works and returns the expected data, but the Success Function within the AJAX call never displays the Bootstap Alert.
Any ideas?
Thanks.
Cshtml
<style type="text/css">
.alert {
display: none;
}
</style>
<script type="text/javascript">
$(document).ready(function () {
$(function () {
$('button').on('click', function(){
const token = $('[name="__RequestVerificationToken"]').val();
var data = { "MyVar": "Test"};
$.ajax({
url: '?handler=SaveOrder',
method: "post",
contentType: "application/json",
dataType: 'application/json; charset=utf-8',
headers: {
"RequestVerificationToken" : token
},
data: JSON.stringify(data),
success: function(data){
alert(data.success);
$('.alert').show();
}
}); //Close AJAX
})//Close Btn Click
});//Close function
});//Close document ready
</script>
<div id="msg" class="alert alert-danger alert-dismissible" role="alert">
<div class="alert-message">
Put message here.
</div>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="alert" aria-label="Close"></button>
</div>

Related

Ajax Call to PartialViewResult does not Replace Div with PartialView

I've done this dozens of times before and have been testing all morning, I must be missing something very obvious.
I have a form that submits data and if the data already exists, I just want to overwrite that form using a PartialView. I can debug the code and watch the POST get called and I even watch the PartialView reciev its model and data but the PartialView doesn't get rendered on the screen and my AJAX doesn't return anything to the console so I'm not sure how to Troubleshoot this.
My Controller
[HttpPost]
[Route("Send")]
public PartialViewResult Send([FromBody] InstantAlert InstantAlert)
{
string view = "~/views/shared/_InstantAlert_Exists.cshtml";
}
My View
<!-- Form -->
<div id="DivSubmitForm">
<partial name="~/views/home/_Partials/_SubmitForm.cshtml", model="Model" />
</div>
<!-- End Form -->
My Script
$(function () {
$(document).on("click", '#btnSubmit', function () {
if ($('form').valid()) {
Submit();
}
});
function Submit() {
//JSON data
var InstantAlert = {
url: $('#url').val(),
userId: $('#userId').val(),
institutionId: $('#institutionId').val()
}
var jsonToPost = JSON.stringify(InstantAlert);
$.ajax({
url: '/home/Send',
contentType: "application/json; charset=utf-8",
data: jsonToPost,
type: "POST",
success: function (result) {
console.log("Success");
//$('#DivSubmitForm').html(result);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
});
PartialView
<div class="form-group">
<div class="alert alert-danger alert-dismissible" role="alert">
<strong>This article has already been submitted</strong>
<hr class="message-inner-separator">
<p>
test
</p>
</div>
</div>
Argh, so I discovered a form tag on my page which means the controller was inevitably always reloading my initial controller....

Ajax call in razor code refreshes the page

I'm populating a folder structure using TreeView in .cs file, rendering it in the view.cshtml. When an item is clicked, I call a js function which makes an ajax call to the web api, gets the file content and supposed to display the result in a TextArea or Div.
The result comes back from web api, and displays it in the textarea momentarily and disappears. I guess it's refreshing the page. But I'm not sure how to prevent it. I have done similar stuffs before, didn't behave so. I'm sure I'm missing something, but I can't tell what I'm missing.
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<form>
<div style="width: 100%; overflow: hidden;">
<div style="width: 600px; float: left;">
<ul>
#foreach (var node in Model.Nodes[0].ChildNodes)
{
<li>#node.Text</li>
<ul>
#foreach (var f in node.ChildNodes)
{
<li>#f.Text</li>
}
</ul>
}
</ul>
</div>
<div id="divLog" style="margin-left: 620px;overflow:auto;"><textarea id="txtLog" rows="10" cols="50"></textarea></div>
</div>
</form>
<script>
function getLog(fileref) {
var baseURL = window.location.protocol + '//' + window.location.host + '#Url.Content("~")';
var apiUrl = baseURL + "/api/logapi?fileref=" + fileref;
document.getElementById("txtLog").innerText = "";
$(document).ready(function () {
$.ajax({
url: apiUrl,
type: "GET",
success: function (data, textStatus, jqXHR) {
document.getElementById("txtLog").innerText = data;
//document.getElementById("txtLog").innerHTML = data;
//$("#txtLog").val(data);
alert(data);
}
});
});
}
</script>
Maybe another solution for any people coming here. I had the same issue in my Razor pages project when trying to call an Ajax function from a form. The page would call the correct page handler and return the Json result, however the page would always refresh, and the success part in the ajax call would not be called. What worked FOR ME was to REMOVE the form element and replace it with a div. Now the Ajax call returns correctly for me.
<div id="first" class="section"> //WHEN THIS WAS FORM THE PAGE REFRESHED
<div class="section">
#Html.HiddenFor(m => m.PersonId)
#Html.HiddenFor(m => m.ProviderId)
#Html.AntiForgeryToken()
<div class="container2">
<input type="radio" name="group1" id="radio-1" checked="checked">
<label for="radio-1"><span style="font-size:16px;" class="radio">I want to recieve all Emails (personal and marketing)</span></label>
</div>
<button onclick="setPreferences()" class="btn btn-save">Save <i class="fa fa-save"></i></button>
</div>
</div>
And the ajax:
$.ajax({
url: '/UserPreferences?handler=SetPreferences',
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(model),
headers: {
RequestVerificationToken: $('input:hidden[name="__RequestVerificationToken"]').val()
},
success: function (response) {
console.log(response);
}
});
I used button instead of anchor link, it works as expected, it doesn't refresh the screen.
<style>
.btn1 {
background-color: transparent;
border: hidden;
}
</style>
<li><input type="button" id="a" value="#f.Text" onclick="getLog('#f.Value')" class="button btn1"></li>
First, remove the Ajax call from the document ready function:
function getLog(fileref) {
var baseURL = window.location.protocol + '//' + window.location.host + '#Url.Content("~")';
var apiUrl = baseURL + "/api/logapi?fileref=" + fileref;
document.getElementById("txtLog").innerText = "";
$.ajax({
url: apiUrl,
type: "GET",
success: function (data, textStatus, jqXHR) {
document.getElementById("txtLog").innerText = data;
//document.getElementById("txtLog").innerHTML = data;
//$("#txtLog").val(data);
alert(data);
}
});
}
Secondly, replace the empty href attribute of the anchor link by href="javascript:;" or href="#".

How to call ajax function on buttonclick in laravel?

View Code:
<script>
function getMessage(){
$.ajax({
type:'POST',
url:'/getmsg',
data:'_token = <?php echo csrf_token() ?>',
success:function(data){
$("#msg").html(data.msg);
}
});
}
</script>
<body>
<div id = 'msg'>This message will be replaced using Ajax. Click the button to replace the message.</div>
<input type="button" value="Replace Message" onclick='getMessage()'>
</body>
Here ,When I click on the button it should be replaced by the other text. But nothings appears on clicking.
Controller code:
public function index(){
$msg = "This is a simple message.";
return response()->json(array('msg'=> $msg), 200);
}
In pure js that code work fine
function getMessage(){
alert('Its working!');
}
<body>
<div id = 'msg'>This message will be replaced using Ajax.
Click the button to replace the message.</div>
<input type="button" value="Replace Message" onclick='getMessage()'>
</body>
Looks OK.
Put a breakpoint in your success and see what data is.
Or do a console.log
Mick
in your ajax code you didn't define dataType, add dataType:"json", to retrive the json data, change your ajax code as
function getMessage(){
$.ajax({
type:'POST',
url:'/getmsg',
dataType:'json',
data:{
_token = '<?php echo csrf_token() ?>'
},
success:function(data){
$("#msg").html(data.msg);
}
});
Update your code with below mentioned code, and let's try.. i will working for me..
<script type="text/javascript" charset="utf-8">
$(document).on('click', '#btnSelector', function(event) {
event.preventDefault();
/* Act on the event */
getMessage();
});
var getMessage = function(){
$.ajax({
type:'POST',
url:'/getmsg', //Make sure your URL is correct
dataType: 'json', //Make sure your returning data type dffine as json
data:'_token = <?php echo csrf_token() ?>',
success:function(data){
console.log(data); //Please share cosnole data
if(data.msg) //Check the data.msg isset?
{
$("#msg").html(data.msg); //replace html by data.msg
}
}
});
}
</script>
<body>
<div id = 'msg'>This message will be replaced using Ajax. Click the button to replace the message.</div>
<input type="button" value="Replace Message" id='btnSelector'>
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<body>
<div id='msg'>This message will be replaced using Ajax. Click the button to replace the message.</div>
<input type="button" id="ajax_call" value="Replace Message">
</body>
<script>
$(function () {
$('#ajax_call').on('click', function () {
$.ajax({
type:'POST',
url:'<?php echo url("/getms"); ?>',
data:'_token = <?php echo csrf_token() ?>',
success:function(data){
$("#msg").html(data.msg);
},
complete: function(){
alert('complete');
},
error: function(result) {
alert('error');
}
});
});
});
</script>
Jquery onclick function: jquery onclick function not defined
Also check: Function not calling within an onclick event

how to put full response of jsonp in textarea and display the full response in div?

i am trying to display the full response of jsonp call in textarea and div but for some reason it doesnt work! could any one tell me what i am doing wrong here?Thanks
ajax script:
<script>
$(function() {
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "https://api.somesite.com/test&count=-1",
success: function(data) {
alert(data);
$(".response").append(data);
$("#outputtext").append(data);
document.myform.outputtext.value = document.myform.outputtext.value+data+'\n' ;
}
});
});
</script>
<div class="response"></div>
<form id="myform" name="myform" action="./" method="post">
<td><textarea rows="6" cols="15" name="outputtext" style="width: 99%;"></textarea></td>
</form>

Why Ajax Jquery form click not working vs div that works?

Ajax Jquery form not working vs div why its happen and how can i fix my error?
view.html-Code with form
not working
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
</head>
<body>
<form id="parse-form" action="#" method="post">
<button type="submit" id="submit-html">submit ajax request without parameters</button>
</form>
<div>array values: <div id="array-values"></div></div>
<script type="text/javascript">
$(document).ready(function() {
$('#submit-html').click(function() {
$.ajax({
url: 'controller.php',
type: 'POST',
dataType:'json',
success: function(data) {
alert("response begin");
alert(data);
$.each(data, function (i, elem) {
$('#array-values').append('<div>'+elem+'</div>');
});
}
});
});
});
</script>
</body>
</html>
view.html -form replaced by div
working
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
</head>
<body>
<div id="parse-form">
<button type="submit" id="submit-html">submit ajax request without parameters</button>
</div>
<div>array values: <div id="array-values"></div></div>
<script type="text/javascript">
$(document).ready(function() {
$('#submit-html').click(function() {
$.ajax({
url: 'controller.php',
type: 'POST',
dataType:'json',
success: function(data) {
alert("response begin");
alert(data);
$.each(data, function (i, elem) {
$('#array-values').append('<div>'+elem+'</div>');
});
}
});
});
});
</script>
</body>
</html>
controller.php -simple php file that return json array:
<?php
$arr=array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);
?>
Thanks
The form has a default action with a type="submit" button, which is submitting, so you'll need to stop that from happening by adding return false or event.preventDefault() , like this:
$(document).ready(function() {
$('#submit-html').click(function(e) {
$.ajax({
url: 'controller.php',
type: 'POST',
dataType:'json',
success: function(data) {
alert("response begin");
alert(data);
$.each(data, function (i, elem) {
$('#array-values').append('<div>'+elem+'</div>');
});
}
});
return false;
//or e.preventDefault();
});
});
Without this, the form is submitting as it normally would with no JavaScript, leaving the page. So effectively it's doing a refresh, instead of AJAX submitting your form (which doesn't have time to complete...because you left :)
An element of type=submit inside a <form> will perform the form request when clicked on.
You need to abort the default behavior by running event.preventDefault() inside the click callback.
My guess is that the form is submitting and refreshing the page before the ajax has a chance to respond.
Try putting return false; at the end of the click handler.
$('#submit-html').click(function() {
$.ajax({
url: 'controller.php',
type: 'POST',
dataType: 'json',
success: function(data) {
alert("response begin");
alert(data);
$.each(data, function(i, elem) {
$('#array-values').append('<div>' + elem + '</div>');
});
}
});
return false;
});
Of course you'll have the same issue if the user hits Enter in one of the fields. Unless you're preventing the Enter key from submitting the form, you may want to the handle the event using the submit() handler.
$('#parse-form').submit(function() {
$.ajax({
url: 'controller.php',
type: 'POST',
dataType: 'json',
success: function(data) {
alert("response begin");
alert(data);
$.each(data, function(i, elem) {
$('#array-values').append('<div>' + elem + '</div>');
});
}
});
return false;
});
Try using submit() http://api.jquery.com/submit/ , this should work with keyboard events as well as clicks. You can use serialize() to get any form data into the ajax objects data variable.

Resources