I try to call a simple ajax request from client side to server side, but I have a problem with it
when I press the button I have no change in this page even when I got the alert("OK!");
and for example if my Application("bbb")
is 51
I always got OK!
and then 51
only when I have refresh the page I see all the changes in my button for example If is press the button 8 times and Application("bbb")
is 51
I got 8 times of alerts
as OK!
and then 51
and no change for <label id="lbl"></label>
it still have 51 in text and when I refresh the page I got in <label id="lbl"></label>
0 in text
and after next click I got <label id="lbl"></label>
change to 61
that mean the ajax request got the server and change the value in Application("bbb") as expected but I cant cahnge the html view without refreshing the page
why its happen?
this is my simple code :
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<meta charset="utf-8">
</head>
<body>
<button id="changeSessionBtn">Change Session Variable</button>
<label id="lbl">0</label>
<script>
$(document).ready(function(){
$('#changeSessionBtn').click(function(){
$.ajax({
type: 'POST',
url: 'http://localhost/home.asp',
data: { newSessionValue: 'newValue' },
success: function(response){
document.getElementById('lbl').innerHTML = <%=Application("bbb")%>
alert("OK!");
alert(<%=Application("bbb")%>);
//$("lbl").innerHTML =
},
error: function(xhr, status, error){
console.error('Error changing session variable:', error);
}
});
});
});
</script>
</body>
</html>
<%
if IsEmpty(Application("bbb")) then
Application("bbb") = 1
Else
Application("bbb") = Application("bbb") + 1
end if
%>
2
Answers
Make sure the Application object has been initialised in the global.asa file.
https://www.w3schools.com/asp/asp_globalasa.asp
Also lock the Application object before writing to it and then unlock it again.
To solve your problem just change the position of your ASP code to the begin of document as follow: