Updating html content on submit - javascript

I am trying to create a simple webpage containing comments in a table. I can successfully populate it by calling following function on "window.onload" event.
function FillCommentsTable() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var comments = JSON.parse(this.responseText);
var i = 0;
var old_tbody = document.getElementById("comments");
var new_tbody = document.createElement("tbody");
for (i = 0; i < comments.length; i++) {
var row = new_tbody.insertRow(-1);
var id = row.insertCell(0);
var user = row.insertCell(1);
var comment = row.insertCell(2);
var timestamp = row.insertCell(3);
id.innerHTML = comments[i].Id;
user.innerHTML = comments[i].User;
comment.innerHTML = comments[i].Comment;
timestamp.innerHTML = comments[i].Timestamp;
}
old_tbody.parentNode.replaceChild(new_tbody, old_tbody);
}
};
xhttp.open("GET", "API/get_comments.php", true);
xhttp.send();
}
The webpage also have functionality to submit and delete comment with simple form calling the API that manipulates the database storing the comments. The wanted functionality here is that after the submit/delete form has been submitted and called the API the page is reloaded and the table updated. To achieve this I have tried to reload the page on submit with:
<form action="API/delete_comment.php" method="post"
onsubmit="window.location.reload()">
<input type="number" name="id">
<input type="submit" value="Delete">
</form>
but this seems to have no effect except that the expected call to the API is sent. This also only occurs when trying to update the table with a form since just binding a button:
<button onclick="window.location.reload()">Load comments</button>
works as intented and updates the table correctly. Is it not possible to sent both the GET for the webpage and the POST to the API triggered on the same event or what am I missing here?

The point of AJAX is to be able to communicate with the server without having to reload the page...
Submit the form with AJAX instead and then simply call your FillCommentsTable again.
<form action="#" method="post" onsubmit="return deleteComment()">
<input type="number" name="id">
<input type="submit" value="Delete">
</form>
function deleteComment() {
var id = document.querySelector("input[name='id']");
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
FillCommentsTable();
}
};
xhttp.open("POST", "API/delete_comment.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("id="+encodeURIComponent(id.value));
return false;
}
Edit:
The above successfully sends the GET request retrieving the data. In addition to these changes I also added
new_tbody.setAttribute("id","comments");
in the FillCommentsTable function. The mistake of omitting this caused the comments table body to lose its name on the first reload which then caused subsequent calls to FillCommentTable to have no effect since there is no tbody called "comments" ...

Ideally, you should have two data call functions, one to GET data from DB and one to POST data to your DB.
function FillCommentsTable() {
//Function Stuff
}
function AddNewComment() {
//Function Stuff
}
You have a few options on how to process the data:
On POST of a new item, after you receive a status of 200, call your
FillCommentsTable function.
If you have an array storing your comments on the client side, as
you make your POST call and after you receive a status of OK,
array.push(newComment)
You can also take advantage of Promises (Browser support, ECMA2015) to ensure sequencing. I will leave it at a resource link for now as its not exactly within scope of the OP.

Related

How Do I Post A Form Without Redirecting Using Raw Javascript?

I've seen several posts about how to post a form using AJAX, but I am curious about options for simplification.
Here's a trimmed down version of what I'm trying:
<form id="message-form" method="POST" action="/send-message" onsubmit="return false;">
<input type="text" name="message"><br/>
<input type="text" name="phone_number"><br/>
<button type="button" onclick="return trysubmit()">Send Message</button>
</form>
<script>
function trysubmit()
{
document.getElementById("message-form").submit();
//notify user of success
//cancel the redirect
return false;
}
</script>
In this case, the form gets submitted, but the redirect still happens.
Is something like the above even possible, or do I have to manually build an AJAX request like this?
form serialize javascript (no framework)
var form = document.getElementById('message-form');
var data = new FormData(form);
var req = new XMLHttpRequest();
req.send(data);
Unless resorting to hacks like posting to a dummy target, AJAX is the way to go.
This works:
const form = document.querySelector("#message-form");
form.addEventListener("submit", event => {
event.preventDefault()
let status = "";
const data = new FormData(form);
const req = new XMLHttpRequest();
try{
req.open("POST", '/send-message');
req.send(data);
status = "success";
}
catch{
status = "failure";
}
notifyuser(status);
});

Maintaining authentication using API and xhr

I'm getting to grips with using an API to display the data on a page refresh. SO the first part is to authenticate using form based authentication. So I have this:
<html>
<head>
<script type="text/javascript">
function CallWebAPI()
{
var request = new XMLHttpRequest(), data = 'username=admin&password=admin';
request.open('POST', 'https://localIP:8443/api/users/_login', true)
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
request.setRequestHeader("Accept", "application/xml")
request.onreadystatechange = function()
{
// D some business logics here if you receive return
//if(request.readyState === 4 && request.status === 200) {
console.log(request.responseText);
//}
}
request.send(data);
}
</script>
</head>
<body>
<div>
<div id="response">
</div>
<input type="button" class="btn btn-primary" value="Call Web API" onclick="javascript:CallWebAPI();" />
</body>
</html>
So from the above, in the console browser I return a proper authentication message as thus:
SUCCESS
So I want to run another function to retrieve data now I'm logged in but it seems to reset back to 'unauthorised. All I did was create another function exactly the same except it was a GET rather than POST and added another button to test it. But it just kept returning 401: unauthorised. Am I doing it in the incorrect order or something?
I insert a second function like this:
function getChannelStats()
{
var stats = new XMLHttpRequest();
stats.open('GET', 'https://localIP:8443/api/channels/statistics?channelId=f237ae66-6c5b-4ffa-9396-0721eb575184', true)
stats.setRequestHeader("Accept", "application/xml")
stats.onreadystatechange = function()
{
// D some business logics here if you receive return
//if(request.readyState === 4 && request.status === 200) {
console.log(stats.responseText);
//}
}
stats.send();
}
request.send(data);
}
And add another button that class that function to get the responseText. I'm expecting an xml message with various numbers in it. But when I try to run it, it asks for me to authenticate - like it's not retaining it?

Post form data to php without page refresh

I am trying to post form data, an array to php file without page refresh. I am using ajax which doesn't seem to be working. Below is form syntax and ajax. Can somebody please help me? Thanks.
<form name="postcontent" id="postcontent">
function[]; //just for an example of data
<button type="button" id="submitform" onclick="posttophp" >Send</button>
<script>
function posttophp() {
var xhttp = new XMLHttpRequest();
xhttp1.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("submitform").innerHTML = this.responseText;
}
};
xhttp.open("POST", "options.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("
function_Options1[]=function[]")
}
</script>
In php, I store function_Options1[] in another variable and use further.
Two ideas to try:
Maybe the script should be placed before calling the function, but not sure about this.
Try onclick="posttophp();"

what causes the URL to change upon form submissions

I often seen websites with a search function and when they search for something, the web page often changes the url to something along the lines of
search.php?q="searchquery"& etc , i have a search page on my site and i use ajax to submit a form that has a search input and sends to a php page which searches through my database and returns data to a specific div on the original page via echo.
function getdata() {
var str = document.getElementById("searcb");
document.getElementById("demo").innerHTML = "You are searching for: " + str.value;
document.getElementById("searchresults").style.display="block";
if (str == "") {
document.getElementById("demo").innerHTML = "";
return;
}
else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("searchresults").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "getuser.php?q=" + str.value, true);
xmlhttp.send();
return false;
}
}
HTML
<form onsubmit="return getdata()">
<input type="search" id="searcb" name="searchBar"></br></br>
</form>
My question is what am i doing differently that causes my url to remain the same compared to a common search engine
In general the url change because a post that reload the page is performed. Your url will not change because you call make an ajax call that will not reload your corrent page .

Making sure request will be completed after changing page

The problem is: I have custom analtyics engine that sends log using JavaScript. I want to send log after user submits a form. The log is send using AJAX. Now the problem is, form submission is not AJAX, it is normal request that refreshes the page.
I already learned that you can force the script executions even if client aborted connection
Does php execution stop after a user leaves the page?
What I want to learn is how to be sure that server recives request and headers if form is submited almost instantly after AJAX call is send?
var url = "...";
var my_form = document.getElementsByTagName("form")[0];
var request_received = false;
my_form.addEventListener("submit", function(e) {
if (!request_received) {
e.preventDefault(); // prevent the form from submitting
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState >= 2 && !request_received) {
request_received = true;
my_form.submit(); // submit the form only if the request has been received
}
};
xhr.open("GET", url, true);
xhr.send();
return false;
}
}, false);
Lets say that this is your form with submit button:
<form id="myForm" action="/myAction.html" method="POST">
<!-- form inputs -->
<input type="submit" value="submit me!" />
</form>
With JavaScript you can bind to the submit event of your form, do your ajax call and then return true to continue submiting your form to the server:
<script type="text/javascript">
document.getElementById('myForm').addEventListener('submit', function(e){
// do your ajax call here and when you finish, return true from
// this function (in the ajax success callback)
return true;
});
</script>

Categories

Resources