New ajax calls not resetting the existing data in the JSP table - javascript

Below is my ajax function which retrieves the data from servelt and shows it fine in the jps and the problem is every time a new ajax calls is submit the form just appends the data into the results received from previous calls, I need reset the current values stored in the table OrderResultContainer and then display it with new data.
I tried
document.getElementById("OrderResultContainer").reset = ();
but it's just reset the entire form data and not showing any data in the page.
function addData() {
if(window.XMLHttpRequest) {
var xhttp = new XMLHttpRequest();
var loading = document.getElementById("loading");
document.getElementById("loading").style.display = "";
document.getElementById("OrderResultContainer").style.display = "none";
xhttp.open("POST","Order",true);
var formData = new FormData(document.getElementById('orderform'));
xhttp.send(formData);
xhttp.onreadystatechange=function() {
if ((xhttp.readyState == 4) && (xhttp.status == 200)) {
var jsonorderdata = JSON.parse(xhttp.responseText);
txt = "";
for (x in jsonorderdata) {
txt += "<tr><td>" + jsonorderdata[x].ordernumber+"</td>""</tr>";
}
document.getElementById("loading").style.display = "none";
document.getElementById("ViewOrderResultContainer").innerHTML = document.getElementById("ViewOrderResultContainer").innerHTML + txt;
document.getElementById("divOrderResultContainer").style.display = "";
}
};
}else
console.log('Ajax call is failed');
}
Can anyone help me on how to reset the data in the table OrderResultContainer alone after a new ajax response received from servlet.

You append the received data to the previous with following code:
document.getElementById("ViewOrderResultContainer").innerHTML = document.getElementById("ViewOrderResultContainer").innerHTML + txt;
So if you change it like following you would have only new data:
document.getElementById("ViewOrderResultContainer").innerHTML = txt;

It is kind of hard to see without the corresponding html but this looks like the problem:
document.getElementById("ViewOrderResultContainer").innerHTML =
document.getElementById("ViewOrderResultContainer").innerHTML + txt;
Your taking the innerHtml from the ViewOrderResultContainer and append the value from txt. If you do that more than once than it will keep growing. If you want to replace the text than replace it with
document.getElementById("ViewOrderResultContainer").innerHTML = txt;
p.s. the given javascript is not valid
txt += "<tr><td>" + jsonorderdata[x].ordernumber+"</td>""</tr>";

Related

Send an email with an HTML table, with attachment, when a Google Form response is submitted

I have a function that runs on an installable "on form submit" trigger. It sends an an email when a form response is submitted.
The Google Form has multiple questions including a question that lets the responder include attachments. I need to send both questions and answers in a table format. The questions should be in bolded in the table. The attachments should be included in the email.
Here's my current code:
function onFormSubmit() {
var email = "example#gmail.com";
var subject = "Form Responses";
var body = "<table>";
var attachments = [];
var form = FormApp.getActiveForm();
var responses = form.getResponses();
var lastResponse = responses[responses.length-1];
var itemResponses = lastResponse.getItemResponses();
for (var i = 0; i < itemResponses.length; i++) {
var question = itemResponses[i].getItem().getTitle();
var response = itemResponses[i].getResponse();
body += "<tr><td><b>" + question + "</b></td><td>" + response + "</td></tr>";
if (itemResponses[i].getItem().getType() === FormApp.ItemType.FILE_UPLOAD) {
var fileId = itemResponses[i].getResponse().getId();
var file = DriveApp.getFileById(fileId);
attachments.push(file.getBlob());
}
}
body += "</table>";
GmailApp.sendEmail(email, subject, "", {htmlBody: body, attachments: attachments});
}
The problem is that the code errors out:
TypeError: itemResponses[i].getResponse(...).getId is not a function.
How do I fix that?
itemResponses[i].getResponse() is a string not a file. Try this.
let fileId = DriveApp.getFilesByName(itemResponses[i].getResponse()).next().getId();
Although I would suggest you use try catch incase a file of that name doesn't exist.

A function to return 3 random profiles from JQuery?

I would like to create a web app that returns 3 random profiles of student that are randomly assigned to you once you click a button.
I am looking for un function that does that but I can't find anything. Do you have anything that does the job?
Here is the Github repository if you need it.
All I've tried function(randomusers) but I failed
$.getJSON("https://randomuser.me/api/", function (randomusers) {
var user = randomusers.results[0];
document.getElementById("prenom").textContent = (user.name.first); //prénom
document.getElementById("adresse").textContent = (user.location.street + " " + user.location.city + " " + user.location.state); // adresse
document.getElementById("email").textContent = (user.email); //email
var img = document.createElement('IMG'); //profile picture
img.setAttribute('src', user.picture.large);
document.getElementById("photo").appendChild(img);
}
I want 3 random user profiles to appear when I click the "find my partners" button. Unfortunately, I am not able to display these 3 profiles and anything for the record. Is it that I didn't link the button to the JS function or that the function is wrong?
I am new to coding and I was a bit too ambitious so I have no clue how to do it now.
Thanks a lot for your help
There are multiple ways to display this in both JavaScript and in JQuery.
You can find the working code sample in this git repository
https://github.com/helloritesh000/DisplayRandom3Profile
Call function GetRandomProfiles() on click on button Find My Partners. This will load 1 profile at a time keep clicking the button it will load the another profile.
<script type="text/javascript">
function GetRandomProfiles()
{
$.getJSON( "https://randomuser.me/api/", function( randomusers ) {
var user = randomusers.results[0];
// document.getElementById("picturegenerator").innerHTML = "";
var img = document.createElement('IMG');
img.setAttribute('src', user.picture.large);
document.getElementById("picturegenerator").appendChild(img);
var detail = document.createElement('div');
detail.innerHTML = "";
var prenom = document.createElement('div');
prenom.setAttribute('id', 'prenom');
prenom.innerHTML = user.name.first;
detail.innerHTML += prenom.outerHTML;
var adresse = document.createElement('div');
adresse.setAttribute('id', 'adresse');
adresse.innerHTML = user.location.street +" "+ user.location.city + " " + user.location.state;
detail.innerHTML += adresse.outerHTML;
var email = document.createElement('div');
email.setAttribute('id', 'email');
email.innerHTML = user.email;
detail.innerHTML += email.outerHTML;
document.getElementById("picturegenerator").appendChild(detail);
} );
}
</script>
Another way to achieve is just add the server call in a for loop which runs 3 times. It will pull 3 profiles in single button click.
<script type="text/javascript">
function GetRandomProfiles()
{
for(i=0; i<3;i++)
{
$.getJSON( "https://randomuser.me/api/", function( randomusers ) {
var user = randomusers.results[0];
// document.getElementById("picturegenerator").innerHTML = "";
var img = document.createElement('IMG');
img.setAttribute('src', user.picture.large);
document.getElementById("picturegenerator").appendChild(img);
var detail = document.createElement('div');
detail.innerHTML = "";
var prenom = document.createElement('div');
prenom.setAttribute('id', 'prenom');
prenom.innerHTML = user.name.first;
detail.innerHTML += prenom.outerHTML;
var adresse = document.createElement('div');
adresse.setAttribute('id', 'adresse');
adresse.innerHTML = user.location.street +" "+ user.location.city + " " + user.location.state;
detail.innerHTML += adresse.outerHTML;
var email = document.createElement('div');
email.setAttribute('id', 'email');
email.innerHTML = user.email;
detail.innerHTML += email.outerHTML;
document.getElementById("picturegenerator").appendChild(detail);
} );
}
}
</script>
Well, you have to do three tasks, and you can do it by using pure JavaScript.
Get 3 random users from the API URL (https://randomuser.me/api/) through HTTP request.
Collect the random user data in an array.
Print the HTML with the proper contents from the array that you have.
With pure JavaScript:
You need to create a helper function to do asynchronous HTTP requests (AJAX). This is a very basic structure for any web project with JavaScript to do asynchronous HTTP requests without any third party library like jQuery. This helper function is kinda similar to $.get(), $.getJSON(), $.ajax() functions in jQuery.
var newXHR = null;
function sendXHR(type, responseType, url, data, callback) {
newXHR = new XMLHttpRequest() || new window.ActiveXObject("Microsoft.XMLHTTP");
newXHR.responseType = responseType;
newXHR.open(type, url, true);
newXHR.send(data);
newXHR.onreadystatechange = function() {
if (this.status === 200 && this.readyState === 4) {
callback(this.response); // Anonymous function is required at this point: function(argument) { ... }.
}
};
}
Note:
You can not use a for loop statement with asynchronous requests
because the results can be obtained at an undetermined time, while the
execution of a for loop is synchronous. In that sense, it is
quite useful to use a callback function that allows the
continuation of the execution of your code when the previous execution
ends in a recursive function with asynchronous requests.
Then:
You may create a recursive function with three parameters: url, times, callback. Where:
url. It's a string that is the API URL: https://randomuser.me/api/.
times. It's a number. In this case is 3, because you need to do 3 HTTP requests to the API URL.
callback. It's a function reference to execute passed as parameter. Its value must be a function. This function reference can receive a value as parameter.
The count and arrayOfUsers variables must be defined in the global scope.
function getUsers(url, times, callback) {
if (count < times) { // Check the limit in the recursive process. You need to execute this function only 3 times to get 3 random users from the API URL.
sendXHR("GET", "json", url, null, function(response) { // The response parameter contains the data from the API URL, so you can store this value in an array for every request.
arrayOfUsers.push(response); // Save the random user data from the API in the array.
count++; // Increment the counter.
getUsers(url, times, callback); // Keep executing the function to get more random user data.
});
} else {
callback(arrayOfUsers); // Once reaching the limit return the result of arrayOfUsers through the callback function.
}
}
To store random user data obtained from the HTTP request, you can use Array#push: In this case: arrayOfUsers.push(response);.
A more practical way to build an HTML markup with data is by concatenating strings.
In this case, I have this function:
function renderUsers(data) {
var html = "", len = data.length, user;
for (var i = 0; i < len; i++) {
user = data[i];
html += "<div class=\"user\"><div><label>Name: </label><span title=\"";
html += "LastName: ";
html += user.results[0].name.last;
html += "\">";
html += user.results[0].name.first;
html += "</span></div><div><label>Address: </label><span>";
html += user.results[0].location.street;
html += " ";
html += user.results[0].location.city;
html += " ";
html += user.results[0].location.state;
html += "</span></div><div><label>Email: </label><span>";
html += user.results[0].email;
html += "</span></div><div><label>Image: </label><span>";
html += "<img alt=\"";
html += user.results[0].picture.large;
html += "\" src=\"";
html += user.results[0].picture.large;
html += "\" /></div></div>";
}
return html; // Return the built html.
}
You would have something like this:
(function() {
// Declaring global variables.
var newXHR = null, arrayOfUsers = [], count = 0;
// Helper function to make HTTP requests (AJAX) with JavaScript.
function sendXHR(type, responseType, url, data, callback) {
newXHR = new XMLHttpRequest() || new window.ActiveXObject("Microsoft.XMLHTTP");
newXHR.responseType = responseType;
newXHR.open(type, url, true);
newXHR.send(data);
newXHR.onreadystatechange = function() {
if (this.status === 200 && this.readyState === 4) {
callback(this.response);
}
};
}
// Recursive function to get random users.
function getUsers(url, times, callback) {
if (count < times) { // Check the limit in the recursive process. You need to execute this function only 3 times to get 3 random users from the API URL.
sendXHR("GET", "json", url, null, function(response) { // The response parameter contains the data from the API URL, so you can store this value in an array for every request.
arrayOfUsers.push(response); // Save the random user data from the API in the array.
count++; // Increment the counter.
getUsers(url, times, callback); // Keep executing the function to get more random user data.
});
} else {
callback(arrayOfUsers); // Once reaching the limit return the result of arrayOfUsers through the callback function.
}
}
// Function to render in the page with the random users.
function renderUsers(data) {
var html = "", len = data.length, user;
for (var i = 0; i < len; i++) {
user = data[i];
html += "<div class=\"user\"><div><label>Name: </label><span title=\"";
html += "LastName: ";
html += user.results[0].name.last;
html += "\">";
html += user.results[0].name.first;
html += "</span></div><div><label>Address: </label><span>";
html += user.results[0].location.street;
html += " ";
html += user.results[0].location.city;
html += " ";
html += user.results[0].location.state;
html += "</span></div><div><label>Email: </label><span>";
html += user.results[0].email;
html += "</span></div><div><label>Image: </label><span>";
html += "<img alt=\"";
html += user.results[0].picture.large;
html += "\" src=\"";
html += user.results[0].picture.large;
html += "\" /></div></div>";
}
return html; // Return the built html.
}
var btnFindMyPartners = document.getElementById("btnFindMyPartners");
btnFindMyPartners.onclick = function() {
var users = document.getElementById("users");
users.removeAttribute("hidden");
users.textContent = "Loading...";
arrayOfUsers = []; // Reset array of users.
count = 0;
getUsers("https://randomuser.me/api/", 3, function(data) {
document.getElementById("users").innerHTML = renderUsers(data);
});
};
}());
body {
font-family: "Segoe UI", sans-serif;
font-size: 0.8em;
}
button {
border: #819bc2 solid 1px;
cursor: pointer;
}
#users,
#users .user,
#users .user div,
button {
border-radius: 5px;
margin: 5px;
padding: 5px;
}
#users {
border: #819bc2 solid 1px;
}
#users .user {
background-image: linear-gradient(to left, #cfcee6, #fff);
border: #46628c solid 1px;
box-shadow: inset #92979c 0 0px 20px 0px;
}
#users .user div {
border: #d4dbe7 solid 1px;
}
<button id="btnFindMyPartners">Find my partners</button>
<div id="users" hidden>
</div>
I would like to remind you of the following when you build HTML markup dynamically.
HTML5 - The id attribute:
The id attribute specifies its element's unique identifier (ID). The
value must be unique amongst all the IDs in the element's home subtree
and must contain at least one character. The value must not contain
any space characters.
Hope this helps a little bit more.

Can't select data attr when added with jquery

I am adding some data to data attr with jquery when click button
$(document).on('click','.musicButton',function(){
var genre = $('.musicPlay').last().data('genre');
var musicBox = $($('#musicBoxTemplate').html());
$(musicBox).appendTo('.allMusics');
$('.getData').last().data('music',genre);
}
Then I need when that data
$(document).on('click','.musicPlay',function(){
var data = $(this).data('genre');
var music = $('.getData[data-music=' + data + ']');
if( music.find(':first-child').attr('tagName').toLowerCase() == 'em'{
//Do some stuff
}
}
that alert me undefined. why it don't see that data when I need?

Javascript - parse XML document to create array

I am working on a web-based application which contains 'divs' that I use for clickable buttons. Currently, my code calls a handleClick function for each 'div' button that needs to be handled. I would like to parse an xml document to get the inputs required for my handleClick function. I have tried implementing solutions from this thread: Parsing XML with Javascript and create array, but I haven't had any luck. I have also been trying to use this information: http://www.w3schools.com/xml/dom_intro.asp, but I'm confused as to what is really needed. The w3schools code uses the XMLHttpRequest function, but the stackoverflow code does not. Here's what I have so far:
//Change background image when Login button clicked.
handleClick("#btnLogin", "SideMenu.png", "LoginButton", "SideMenuButton");
function handleClick (inputButton, inputImage, inputIndexOFF, inputIndexON) {
$(inputButton).click(function() {
$("body").css("background-image", "url(" + inputImage + ")");
//This is how I remove the highlight from the buttons.
zIndexON(inputIndexON);
//This is how I apply the highlight to buttons.
zIndexOFF(inputIndexOFF);
});
}
function zIndexOFF (inputClass) {
var x = document.getElementsByClassName(inputClass);
for (i = 0; i < x.length; i++) {
x[i].style.zIndex = "-1"
}
}
function zIndexON (inputClass) {
var x = document.getElementsByClassName(inputClass);
for (i = 0; i < x.length; i++) {
x[i].style.zIndex = "1"
}
}
//XML
<buttons>
<button>
<inputButton>#btnLogin</inputButton>
<inputImage>SideMenu.png</inputImage>
<inputIndexOFF>LoginButton</inputIndexOFF>
<inputIndexON>SideMenuButton</inputIndexON>
</button>
</buttons>
My initial idea was to create a function to load the xml doc per the information from the w3schools page, then use a for loop to parse the xml elements, and create an array containing the necessary inputs for the handleClick function, then loop through the array to call the handleClick function to process all of the clicks, rather than repeat the same call to handleClick for each button. If there is a simpler way, I'm all ears.
EDIT: I have created a handleClicks function trying to implement the thread from the post I linked above. I also edited my XML doc to resemble the XML from the same thread.
function handleClicks () {
//Get all buttons from XML
var btns = jQuery(buttons).find("button");
//Get input fields for each button in XML
for (var i = 0; i < btns.length; i++) {
var ret = [];
var tot = [];
ret[0] = jQuery(btns[i]).find('inputButton').text();
ret[1] = jQuery(btns[i]).find('inputImage').text();
ret[2] = jQuery(btns[i]).find('inputIndexOFF').text();
ret[3] = jQuery(btns[i]).find('inputIndexON').text();
tot.push(ret);
}
//Call handleClick function for each button from XML doc, and pass in inputs to handleClick function
for (var j = 0; j < button.length; i++) {
handleClick(tot[0].text, tot[1].text, tot[2].text, tot[3].text);
}
}
The buttons still highlight on hover, but nothing happens when I click.
Regarding XML parsing your example is correct. The only place that is not clear is your buttons variable in jQuery(buttons).find("button");. The following example correctly parses the sample xml and calls handleClick with needed data:
var xml_text = "<buttons>" +
"<button>" +
" <inputButton>#btnLogin</inputButton>" +
" <inputImage>SideMenu.png</inputImage>" +
" <inputIndexOFF>LoginButton</inputIndexOFF>" +
" <inputIndexON>SideMenuButton</inputIndexON>" +
"</button>" +
"</buttons>"
var xml = $.parseXML(xml_text);
function handleClick(inputButton, inputImage, inputIndexOFF, inputIndexON) {
console.log(inputButton +' ' + inputImage +' ' + inputIndexOFF +' ' + inputIndexON);
}
function parseXml(xml) {
jQuery(xml).find("button").each(function() {
var inputButton = jQuery(this).find("inputButton").text();
var inputImage = jQuery(this).find("inputImage").text();
var inputIndexOFF = jQuery(this).find("inputIndexOFF").text();
var inputIndexON = jQuery(this).find("inputIndexON").text();
handleClick(inputButton, inputImage, inputIndexOFF, inputIndexON);
});
}
The XML document can be downloaded from the Web using jQuery GET or POST request:
$.ajax({
type: "POST",
url: "/echo/xml/",
dataType: "xml",
data: {
xml: xml_text
},
success: function(xml) {
console.log(xml);
parseXml(xml);
},
error: function(data) {
console.log(data);
}
})
In this example https://jsfiddle.net/t406v94t/ the XML is downloaded using POST request. The sample xml_text is posted to the jsfiddle server to receive it back as Web data. The document is parsed once the download is successfully finished.

fetching xml data into a div via ajax and javascript

Building a chat app and I am trying to fetch all logged in user into a div with ID name "chat_members". But nothing shows up in the div and I have verified that the xml file structure is correct but the javascript i'm using alongside ajax isn't just working.
I think the problem is around the area of the code where I'm trying to spool out the xml data in the for loop.
XML data sample:
<member>
<user id="1">Ken Sam</user>
<user id="2">Andy James</user>
</member>
Javascript
<script language="javascript">
// JavaScript Document
var getMember = XmlHttpRequestObject();
var lastMsg = 0;
var mTimer;
function startChat() {
getOnlineMembers();
}
// Checking if XMLHttpRequest object exist in user browser
function XmlHttpRequestObject(){
if(window.XMLHttpRequest){
return new XMLHttpRequest();
}
else if(window.ActiveXObject){
return new ActiveXObject("Microsoft.XMLHTTP");
} else{
//alert("Status: Unable to launch Chat Object. Consider upgrading your browser.");
document.getElementById("ajax_status").innerHTML = "Status: Unable to launch Chat Object. Consider upgrading your browser.";
}
}
function getOnlineMembers(){
if(getMember.readyState == 4 || getMember.readyState == 0){
getMember.open("GET", "get_chat.php?get_member", true);
getMember.onreadystatechange = memberReceivedHandler;
getMember.send(null);
}else{
// if the connection is busy, try again after one second
setTimeout('getOnlineMembers()', 1000);
}
}
function memberReceivedHandler(){
if(getMember.readyState == 4){
if(getMember.status == 200){
var chat_members_div = document.getElementById('chat_members');
var xmldoc = getMember.responseXML;
var members_nodes = xmldoc.getElementsByTagName("member");
var n_members = members_nodes.length;
for (i = 0; i < n_members; i++) {
chat_members_div.innerHTML += '<p>' + members_nodes[i].childNodes.nodeValue + '</p>';
chat_members_div.scrollTop = chat_members_div.scrollHeight;
}
mTimer = setTimeout('getOnlineMembers();',2000); //Refresh our chat members in 2 seconds
}
}
}
</script>
HTML page
<body onLoad="javascript:startChat();">
<!--- START: Div displaying all online members --->
<div id="chat_members">
</div>
<!---END: Div displaying all online members --->
</body>
I'm new to ajax and would really appreciate getting help with this.
Thanks!
To troubleshoot this:
-- Use an HTTP analyzer like HTTP Fiddler. Take a look at the communication -- is your page calling the server and getting the code that you want back, correctly, and not some type of HTTP error?
-- Check your IF statements, and make sure they're bracketed correctly. When I see:
if(getMember.readyState == 4 || getMember.readyState == 0){
I see confusion. It should be:
if( (getMember.readyState == 4) || (getMember.readyState == 0)){
It might not make a difference, but it's good to be absolutely sure.
-- Put some kind of check in your javascript clauses after the IF to make sure program flow is executing properly. If you don't have a debugger, just stick an alert box in there.
You must send the xmlhttp request before checking the response status:
function getOnlineMembers(){
getMember.open("GET", "get_chat.php?get_member", true);
getMember.onreadystatechange = memberReceivedHandler;
getMember.timeout = 1000; //set timeout for xmlhttp request
getMember.ontimeout = memberTimeoutHandler;
getMember.send(null);
}
function memberTimeoutHandler(){
getMember.abort(); //abort the timedout xmlhttprequest
setTimeout(function(){getOnlineMembers()}, 2000);
}
function memberReceivedHandler(){
if(getMember.readyState == 4 && getMember.status == 200){
var chat_members_div = document.getElementById('chat_members');
var xmldoc = getMember.responseXML;
var members_nodes = xmldoc.documentElement.getElementsByTagName("member");
var n_members = members_nodes.length;
for (i = 0; i < n_members; i++) {
chat_members_div.innerHTML += '<p>' + members_nodes[i].childNodes.nodeValue + '</p>';
chat_members_div.scrollTop = chat_members_div.scrollHeight;
}
mTimer = setTimeout('getOnlineMembers();',2000); //Refresh our chat members in 2 seconds
}
}
To prevent caching response you can try:
getMember.open("GET", "get_chat.php?get_member&t=" + Math.random(), true);
Check the responseXML is not empty by:
console.log(responseXML);
Also you might need to select the root node of the xml response before selecting childNodes:
var members_nodes = xmldoc.documentElement.getElementsByTagName("member"); //documentElement selects the root node of the xml document
hope this helps

Categories

Resources