Hi everyone!
I've been struggling with this bug for weeks and I hope you can help me.
I wrote an AJAX request function in a Javascript file for an ASP.net core website application.
Here's the AJAX function:
function CallPostAjax(Posturl, SuccessMsg, P_Data) {
$(document).ready(function () {
$.ajax({
cache:false,
type: "POST",
url: Posturl,
contentType: 'application/x-www-form-urlencoded; charset=utf-8',
data: P_Data,
success: function () {
alert(SuccessMsg);
},
failure: function (xhr,status) {
alert("Failure! " + status + " " + xhr.status);
},
error: function (xhr, status) {
alert("Result: " + status + " " + xhr.status);
}
});
});
}
To fire the server request a button is pressed that is located in a cshtml file. The button with its function is here:
function ChangeValue(NewValue, Name, Type) {
var token = $('input[name="__RequestVerificationToken"]').val();
ChangeForm(Name.value, token, NewValue.value, Type.value);
}
<form id=product onsubmit="ChangeValue(NewValue,Name,Type)">
<input class="EditBoxClass" type="text" id="NewValue" name="NewValue" value=product>
<input type="hidden" id="Name" name="Name" value=product>
<input type="hidden" id="Type" name="Type" value=ATypeValue>
<input class="ButtonClass" type="submit" value="Change" />
</form>
After the button is pressed the data is given to a function written in the Javascript file name "ChangeForm" which gets the data ready and calls the AJAX function.
Here is the "ChangeForm" function that essentially calls the AJAX function:
function ChangeForm(Name, token, value, type) {
var url;
var msg = "Value set successfully";
var newValue = value;
if (type == TheType) {
url = myurl;
}
var data = {
__RequestVerificationToken: token,
Val: newValue
};
CallPostAjax(url, msg, data);
}
The strange part is the AJAX function works perfectly for one of my other pages, but doesn't work for this page where I edit values using an edit box. When I first press the button nothing happens, there is no failure or error message. There is no success message and the value stays the same (I would refresh the page to be sure). On the second try the value changes as it should, but the success function does not execute. From the third time the button is pressed it works perfectly as the value is changed and the success function is also executed.
Thanks!
What I have tried:
I used the debugger to locate where something goes wrong. The data is set as I expected it, even the first time. I noticed that the server function isn't reached when the button is pressed the first time. Therefore the data does not seem to be the issue.
I cleared the cache and set the cache as false for the ajax function for possible cache issues.
I tried adding "preventDefault()" under "$(document).ready" but of course it just made the function not work at all.