Using AJAX and a huge text file - javascript

I have a huge text file and I am going to pick 5 aléatoir ligne to read and store the content into an array but when I'm testing the response that I get with an alert() it doesn't show all the content.
function loadWords(){
var xhr = new XMLHttpRequest();
xhr.open('GET', "dico/francais.txt");
xhr.onreadystatechange = function(){
if(xhr.readyState == xhr.DONE && xhr.status == 200){
alert(xhr.responseText);
}
}
xhr.send(null);
}
is there any other way more powerful to get the job done?

You cannot put massive data into alert();
alert will always strip it after a certain length (sometimes when your screen resolution is not big enough to display it all etc.)
What you could do, is to put all of it into a textarea in HTML in order to take a look at it.

Related

How to get a specific element from a page to another using JS and Ajax?

I need to build a script (fully JS, no jQuery allowed) that will perform some actions on a page, let's call it the Active page, based on data that are stored on a different page (same domain), call it the Passive page.
These data are stored in specific HTML elements in the Passive page.
I'm totally new to Ajax, so before starting out I tried to make research on the internet, but found nothing useful (or, maybe, nothing I could understand).
How can I retrieve the specific data I need?
I'm stuck with this little code, which however only returned me the page 'skeleton':
javascript:
var myAttempt = new XMLHttpRequest();
myAttempt.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myAttempt = this.responseText;
}
}
myAttempt.open("GET", "https://www.website.com/passivepage.html", true);
myAttempt.send();
Where should I tell the script to look for a specific element of the Passive page?
Thanks
With your ajax request you receive a string as response, to find an specific element inside it you can create a dummy DOM element and add the string to it, then find every element you are looking for inside dummy element. like this:
var myAttempt = new XMLHttpRequest();
myAttempt.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var div = document.createElement('div');
div.style.display = 'none';
div.innerHTML = this.responseText;
document.body.append(div);
const theElement = div.querySelector('selector');
alert(theElement.getAttribute('x'));
}
}
myAttempt.open("GET", "/url", true);
myAttempt.send();

How do I send user to a link upon successful xhr POST?

I have a working web page, complete with a JavaScript function that displays text messages based on the "non-successful" results, within the same page. Everything is working except this last step.
I need to send a JSON string to my server in a POST, and regardless of outcome, I need the user's browser to navigate to the page returned in the POST. (Just as if it were an ordinary link ( href ="" type of thing.) I am using the custom tag [OK_RESULT_URL] that my server replaces with the real URL just before the page is downloaded.
You see in my code below, that I set the URL to [OK_RESULT_URL] AND the window.location to [OK_RESULT_URL] as well, which seems wrong. That means I'm making two hits to [OK_RESULT_URL], one is a POST with a body (which is correct) and the other one a GET without a body (which is wrong).
I'm a total newbie to JavaScript, so I'm probably missing something obvious. It's as if instead of using xhr.Send() I want to say xhr.SendAndNaviateTo() ... or something like that.
Thanks for any help you can provide.
onApproval: function (response) {
showResult("Approved", JSON.stringify(response, null, ''\t''));
let xhr = new XMLHttpRequest();
let url = "[OK_RESULT_URL]";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {if (xhr.readyState === 4 && xhr.status === 200){
window.location = "[OK_RESULT_URL]"};
var data = JSON.stringify(response);
xhr.send(data);
}

How can I stop caching when using AJAX to read a file?

I'm currently building a website that uses AJAX to dynamically update sections of the page without the need to refresh, however, when I change aspects of the file that AJAX reads the website sometimes takes minutes to update even though the file is read about once per second. Whilst looking for the issue I found that I can turn caching off by using the developer tools and this then allowed the website to update at the appropriate speed.
Here's the code I am using:
var path = "Path of the json file i am reading"
var state;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
state = JSON.parse(this.responseText);
}
};
xhttp.open("GET", path, true);
xhttp.send();
I've been looking for a while now and the only advice I can see about what to do about the cache is to use the developer tools to turn it off. Is there any way I can implement some code to automatically tell the browser to not cache the file being read?

cannot manipulate response from xmlHttpRequest 2

I'm using XHR 2 to upload/save files.
According to the response of the server I want to perform an action. For example if the responce is "Saved" I want to hide a div or if the response is "Not Saved" I want to show another div etc...
I implemented what appears to be a simple code that should be working , but is not
Here is the snippet of the XHR
//initialize
var xhr = new XMLHttpRequest();
xhr.open('POST', 'upload.php');
xhr.responseType="text";
xhr.onload = function() {
//if all ok....
if (xhr.status === 200)
{
//update html5 progress bar
progress.value = progress.innerHTML = 100;
//get the respnse
var data=xhr.response;
//convert it to sting - kind of overkill, I know, but I'm stack
var data2=data.toString();
//alert it -- works
alert('data2 '+data2);
//now, do something, according to the response -- NOT working, never alert anything
if (data2=="Not Saved"){alert('Ooops, not saved');}
if(data2=="Saved"){alert('It's all good');}
if(data2=="File too big"){alert('hey, you are watching Jake and Amir');}
document.getElementById('imagesaved').innerHTML=data;
}
//refers to if (xhr.status === 200)
else {document.getElementById("imagesaved").innerHTML="Connect to server failed";}
What is wrong here? This should be working right? Any suggestions?
Thanks
EDIT
I put the alerts for testing. What I actually want to do is call some functions.
If I put
if (data2=="Not Saved"){functionOne();}
if(data2=="Saved"){functionTwo();}
if(data2=="File too big"){functionThree();}
the functions never get called
if I put
if (data2!="Not Saved"){functionOne();}
if(data2!="Saved"){functionTwo();}
if(data2!="File too big"){functionThree();}
ALL the functions are called!!!
I still dont get it...Maybe its something with the response? Or the onload function?
Thanks again
What I finally did is make the server response with numbers, not text. So encoding does not matter any more...
This is the code
var xhr = new XMLHttpRequest();
xhr.onload = function() {
if (xhr.status == 200)
{
var data=xhr.response;
if(data==1)
//say to the user is saved
{document.getElementById('imagesaved').innerHTML="Saved";}
//say to the user, there was an error
else{document.getElementById('imagesaved').innerHTML="Error";}
}
//say to the user that connection to the server failed
else {document.getElementById("imagesaved").innerHTML="Cannot connect";}
};
xhr.open('POST', 'upload.php');
xhr.send(formData);
This is a workaround. I dont know if its the right way to solve this problem , technically. I decided to post it anyway, to help others to quickly solve similar problems. If anyboy else has a better way to suggest , please do.
In this line : if(data2=="Saved"){alert('It's all good');}, you have to escape " ' ".
So convert it to : if(data2=="Saved"){alert('It\'s all good');}
Are you sure that the response of your ajax is text/plain ?
Look on the console (ctrl+shift+i on chrome, F12 on firefox), on net or network tab.
Look on console tab if you got some javascript errors too.

Javascript: Do a GET request and parse Response

I'm writing a MacOs widget that have to explain the bus arrive retrive info from a website like this:
http://www.5t.torino.it/5t/it/trasporto/arrivi-fermata.jsp
i have to make a Get request and parse the response.. i try with:
var xmlHttp = null;
var theUrl = "http://m.gtt.to.it/m/it/arrivi.jsp?n=876";
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET",theUrl,false);
xmlHttp.send( null );
xmlDoc=xmlHttp.responseXML;
but i don't know the structure of document how i can do to navigate it?
but i don't know the structure of document how i can do to navigate it?
You either walk the tree and poke at the note type and node name of the nodes in it, or you examine the XML document manually in order to learn the structure.
It is better to make your Ajax call asynchronous imo by doing:
xmlhttp.open("GET", theUrl, true);
This will prevent your users from interfering an annoying "blocked" period on your website.
If you do so you have to add a onreadystatechange handler so you can parse the incoming data there and display the data you want to display.
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4 && xmlhttp.status == 200) {
var content = xmlhttp.responseText;
//Parse your content here...
}
}
Clearly you have to know what data you are retrieving to be able to parse it. But for that you can just analyze the responseText and find the elements that always contain your data. Then simply retrieve the values from those <html> tags and display it accordingly.
For instance if you want to retrieve the data in a <label> with id set to arrival-time do:
content.getElementById('arrival-time').innerHTML;

Categories