Home > Enterprise >  Passing a Variable with Ajax and Javascript
Passing a Variable with Ajax and Javascript

Time:01-19

I have advanced ASP (classic) skills but am pretty green to JavaScript and Ajax. I'm working on a page that allows users to enter comments in response to a post. I'm wanting the form submission field to submit reader comments to the database, and then show those comments without changing the page. Much like a Facebook comment. Hence Ajax and JavaScript.

I've got the test.asp page (below) working. It's calling the AJAX.asp page, writing to the database, and updating a in the page with the submitted text. My only issue is that I am going to need to update a page with multiple sections, so I need to get a variable into the second JavaScript function to allow me to write to a unique . Currently it's set as id="newcomment" but this will need to change to something like id="newcomment" & var, so that the result is "newcomment1484" (or another unique number) and the right gets updated.

For the life of me I can't figure out how to get a variable in that second function. Any help greatly appreciated. Please keep in mind I'm quite new to JS.

<html>
<head>
</head>
<script>

function SendtoAjax(ident)
{
if(window.XMLHttpRequest)
{
oRequest = new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
oRequest = new ActiveXObject("Microsoft.XMLHTTP");
}

oRequest.open("POST", "AJAX.asp", true);
oRequest.onreadystatechange = UpdateComment;
val=document.getElementById('commentfield').value.replace(/\n/g, "<br>");
oRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
oRequest.send("strCmd=availability&commentaid="   ident   "&commentfield="   encodeURIComponent(val));
}

function UpdateComment(ident)
{
if(oRequest.readyState == 4)
{
if(oRequest.status == 200)
{
document.getElementById("newcomment").innerHTML = oRequest.responseText;
}
else
{
document.getElementById("newcomment").innerHTML = "Asychronous Error";
}
}
}
</script>
<body>

  <form method="post" action="javascript:void(0);" name="form1">


<textarea name="commentfield" id="commentfield"></textarea>
<input id="commentaid" type="hidden" value="Available1434">
<input id="submitcomment" type="button" value="submit" onClick="SendtoAjax(1434);">
<br><br><div id="newcomment"></div>


</form>

</body>
</html>

I tried all manners of getting a variable in there, but have come to learn (I think?) that there is some issue with the "onreadystatechange" and Ajax. Way beyond me at the moment.

CodePudding user response:

you need to pass a formData object, see the docs for examples on how to do that.

let formData = new FormData();

// append some data (key, value)
formData.append("strCmd", "availability");

// send it with the form
oRequest.send(formData);
  • Related