Ajax call in razor code refreshes the page - ajax

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="#".

Related

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

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>

Route [ ] not defined

i wan to be able to dlete a price whereby upon clicking the delete button a modal appears which then shows the yes or no delete buttons.here is the ajax function in the view which contains the delete button
function removeogFuelPriceModel(id)
{
$.ajax({
url: "{{route('industryfuelprice.edit.modal')}}",
type: 'post',
'headers': {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
},
data: {
'id': id,
},
success: function (response) {
$("#showEditInventoryModal").html(response);
$("#showMsgModal").modal('show');
},
error: function (e) {
console.log('error', e);
}
});
}
here is a div inside the modal which contains the id which redirects to the delete ajax function
<div class="row"
style="width: 100%; padding-left: 0px; padding-right: 0px;">
<div class="col col-m-12 text-center">
<button type="button"
class="btn bg-primary primary-button"
**onclick="deleteData({{$oilgas->id}})"**
data-dismiss="modal">Yes</button>
<button type="button"
class="btn btn-danger primary-button"
data-dismiss="modal">No</button>
</div>
</div>
here is the ajax function in the modal
function deleteData(id) {
const url = "{{ route('industryoilgas.destroyFuelprice', ['model_id' => "MODEL_ID"]) }}".replace("MODEL_ID", id);
$.ajax({
url: url,
method: "POST",
enctype: 'multipart/form-data',
success: function (response) {
$("#showMsgModal").modal('hide')
$("#showEditInventoryModal").html(response)
$('#showMsgModal').modal('show');
$("#addFuelPrice").attr("disabled", false);
$("#addFuelPrice").css({"cursor":"pointer;"});
loadFuelPrice();
}, error: function (e) {
console.log(e.message)
}
});
}
here are my routes
Route::post('show-industry-fuel-price-edit-modal','IndustryOilGasController#showEditModalFuelPrice')->name('industryfuelprice.edit.modal');
Route::post('delete-fuel-price/{id}', 'IndustryOilGasController#destroyFuelprice')->name('industryoilgas.destroyFuelprice');
i don't understand why am getting that error
Make sure you have defined removeogFuelPriceModel() and deleteData() within a blade component, because an Laravel helper method cannot be resolved outside a predefined php file. In this case, you are mostly defining those methods inside a JS file which won't work properly. To address this issue, you may inject those methods inside a script layout within the blade component. I wish this could help you out!

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....

Pass ASP MVC3 textbox value to Ajax call

I have a simple ASP MVC3 #Html.TextBox that I'm using to input search criteria. However, I need to append the value to the URL in an Ajax call as a query string. How would I go about this? Below is the HTML in the view:
<div class="editor-field">
#Html.TextBox("searchString")
<span onclick='GetCompName(searchString);'>
<input type="image" src="#Url.Content("~/Content/Images/Filter.bmp")" alt="Filter" />
</span>
</div>
And here is the Ajax
function GetCompName(searchString) {
var request = $.ajax({
type: 'POST',
url: 'http://quahildy01/OrganizationData.svc/AccountSet?$select=AccountId,Name,neu_UniqueId&$filter=startswith(Name,' + searchString + ')',
dataType: 'html',
success: function (data) {
alert(data);
},
error: function (data) {
alert("Unable to process your resquest at this time.");
}
});
}
I will also want to output the returned value into another text box. If anyone knows how to do that that would be really helpful as well. Thanks!
the basic problem with your code is the searchString in onclick='GetCompName(searchString); always gonna be literally "serchString", you must specified the parameter in base the value in the input, like this $('.searchbox').val()
keep your javascript unobstructive.
HTML code
<div class="editor-field">
#Html.TextBox("searchString", null, new { #class = "serachbox" })
<span class="searchbox-trigger">
<input type="image" src="#Url.Content("~/Content/Images/Filter.bmp")" alt="Filter" />
</span>
</div>
Set de handler for the event span click
$(document).ready(function() {
$('.searchbox-trigger').click(GetProgramDetails);
});
and your ajax request
function GetProgramDetails() {
var request = $.ajax({
type: 'POST',
url: 'http://quahildy01/OrganizationData.svc/AccountSet?$select=AccountId,Name,neu_UniqueId&$filter=startswith(Name,' + $('.searchbox').val() + ')',
dataType: 'html',
success: function (data) {
alert(data);
},
error: function (data) {
alert("Unable to process your resquest at this time.");
}
});
}

JSONP callback successful but javascript not updating .html when jQueryMobile included

I am building a PhoneGap app using jQuery Mobile. My JSONP cross domain communication works, but have an issue when jQuery Mobile is included. Without it everything works as expected, included, it stops working.
I've reduced code to simplest form - Serialize data, encode and call CrossDomain PHP file using JSONP. Execute success function. I thought it might be bad JS but "alert" works and no JS errors. But the $('#section1').html("SECTION 1 - " + data.message); doesn't update. Note: When I remove jQM it all works!
Below is the HTML and the PHP code it calls. It's as though the jQueryMobile AJAX call is interfering with the update of the .html code. Any ideas? I'm stumped.
Ajax4d.htm
<html><head><title>First jQueryMobile Example</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.css" />
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.js"></script>
<script>
$(document).ready(function() {
$("#foo").submit(function(event) {
event.preventDefault();
var $form = $(this),
$inputs = $form.find("input, select, button, textarea"),
serializedData = $form.serialize();
var postData = serializedData;
var urlStr = "http://www.fohost.co/testURLd.php?";
alert (urlStr + encodeURI(postData));
$.ajax({
url: urlStr,
data: encodeURI(postData),
dataType: "jsonp",
success: function(data){
alert("SUCCESS callback before HTML update: " + data.message);
$('#section1').html("SECTION 1 - " + data.message);
}
});
});
});
</script>
</head>
<body>
<section id="register_page" data-role="page" data-theme="b">
<div data-role="content">
<form id="foo" method="get" action="">
<fieldset data-role="fieldcontain">
<label for="username">Username:</label>
<input type="text" name="username" id="username" value="Chris" placeholder="Username"/>
</fieldset>
<fieldset class="ui-grid-a"><input type="submit" value="Send" /></fieldset>
</form>
</div>
<div id="section1">SECTION</div>
</section>
</body>
</html>
testURLd.php
<?php
header("content-type: application/json");
$user = $_GET['username'];
$rtnjsonobj->success = "true";
$rtnjsonobj->user = $user;
$rtnjsonobj->message = "Stored User: " . $user;
echo $_GET['callback']. '('. json_encode($rtnjsonobj) . ')';
?>
When you use the submit() method, but fire an ajax call, you aren't prohibiting the form from submitting.
Add a return false; to the end of the $("#foo").submit method. This will prohibit the page from reloading onclick.
Use pageinit instead of document ready..
check this link..
http://jquerymobile.com/test/docs/api/events.html
try this one..
$( document ).delegate("#register_page" ,"pageinit", function() {
$("#foo").submit(function(event) {
event.preventDefault();
var $form = $(this),
$inputs = $form.find("input, select, button, textarea"),
serializedData = $form.serialize();
var postData = serializedData;
var urlStr = "http://www.fohost.co/testURLd.php?";
alert (urlStr + encodeURI(postData));
$.ajax({
url: urlStr,
data: encodeURI(postData),
dataType: "jsonp",
success: function(data){
alert("SUCCESS callback before HTML update: " + data.message);
$('#section1').html("SECTION 1 - " + data.message);
}
});
});
});

Resources