Why old red value persist in the browser, using XMLHttp request object? - javascript

I am reading a comma separated text file from the server, i get the valuse but when i chage the comma seprated variables in the file, it doesn't load the correct result int the browser
while browser persist the first time variable list only, whlile it works correct in IE, in firefox i am facig this proble.
How to sort it out
var arrUserTags = new Array();
var txt;
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "/TinyEditor/TextFile.txt", true);
xmlhttp.send();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
txt = xmlhttp.responseText;
arrUserTags = txt.split(",");
alert(arrUserTags.length);
parse();
}
}
// Add some values to the list box
function parse() {
for (i = 0; i < arrUserTags.length; i++) {
mlb.add(arrUserTags[i], arrUserTags[i]);
alert('hi');
}
}

You server is presumably sending caching instructions that tell browsers the URI for the text file won't change for a while.
Either configure the server to send no cache headers, or change the URI (e.g. by adding a rand() query string to it).

Related

How can I limit the size of incoming information when using 'GET' for XMLHttpRequest?

I have a JS script that makes a call to a URL which holds a changelog text file, and it reads the text contents of the URL and displays version info for me.
I would like to limit the information received from the GET request to 1000 bytes. Currently, it returns the entire list of text, then uses a regex expression to filter out what I need. My question is, how can I limit the size of the incoming information to 1000 bytes?
<script type="text/javascript">
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(this.readyState === 4 && this.status === 200){
var response = this.responseText;
var regEx = /^[^)]+\)/;
var match = regEx.exec(response);
if(match){
var vers = match[0];
console.log(vers);
} else{
console.log('no match');
}
document.getElementById("version").innerHTML = vers;
}
}
//FIX! Have changelog be passed into parameter
if (window.location.href === "abc123.com/hello") {
xhr.open('GET', 'https://static.abc123.com/hello/changelog.txt', true);
}

Trying to post to a .txt file fails but performing a get does work

My partner and I are trying to get a domain that I own, communicate with a ios app that is run on objective c to work via http. He is using the code that was provided by this link Sending an HTTP POST request on iOS.
He is able to do a GET to receive the data in my .txt page but when he performs a PUT to try and write to that file so that I can get that data it fails. We are both rather new to http so it is possible that we are missing something. A concern we have is that he doesn't have the privileges to write to this file. Any advice would help, thanks!
Here is the javascript I am using on my side. I added a header to my response to try and resolve the cors issue.
(function () {
window.onload = function () {
httpGetAsync("http://students.washington.edu/bharatis/distances.txt", processData)
//alert("hello inside onload");
document.getElementById("first").innerHTML = leader1;
document.getElementById("second").innerHTML = leader1;
document.getElementById("third").innerHTML = leader1;
//window.onbeforeunload = update;
}
function processData(responseText) {
//alert(responseText);
var txt = "";
var x = responseText.getElementsByTagName('Distance'); // Talk to alex about
for(i = 0; i < x.length; i++) {
txt += x[i].childNodes[0].nodeValue;
}
var result = parseDouble(txt);
alert(result);
}
function httpGetAsync(theUrl, callback) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.setRequestHeader("Access-Control-Allow-Origin", "*");
xmlHttp.send("response message");
}
})();

Remove a line from JSON parse

I am working with JIVE JSON RESTFul API and on their API they have a security
(I am referring to the throw 'allowIllegalResourceCall is false.'; )
throw 'allowIllegalResourceCall is false.';
{
"id" : "52104",
}
I am using this code to try to PARSE IT:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("topdisplay").innerHTML = myObj.id;
}
};
xmlhttp.open("GET", "http://mysite/API/",true);
xmlhttp.send();
And I am getting an error because of that starting line.
I looked everywhere to try finding a solution to skip that to the JSON PARSE would work but I can't seem to find a way that works to do it.
Also I know that the parsing code works because when I remove the first line it works perfectly.
Any help?
JIVE REST API introduced this to help prevent against JSON Hijacking back when web browsers were susceptible.
You'll need to first find {, and do a substring from that position to the end of the string.
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = this.responseText
var myObj = JSON.parse(this.responseText.substring(this.response.indexOf('{')));
document.getElementById("topdisplay").innerHTML = myObj.id;
}
};
xmlhttp.open("GET", "http://mysite/API/",true);
xmlhttp.send();
NOTE:
using RegEx, you'll need to find the first line with throw and ending in a semi-colon, if found replace with an empty string.
JSON.parse(response.replace(/throw.*;/, "").trim());

Using a while loop to get rows using PhpExcel

I am looking to create javascript arrays with rows taken from an xlsx spread sheet using PHPExcel.
Here is my code
$document.ready({
var rows = new Array();
var vals = new Array();
var i = 0;
while(){
rows[i] = getRow(i);
vals[i] = getVal(i);
i++;
}
});
function getRow(i){
if(window.XMLHttpRequest){
xmlhttp= new XMLHttpRequest();
}else{
xmlhttp= new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function (){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
return xmlhttp.responseText;
}
}
xmlhttp.open('GET', 'data.inc.php?x='+i, true);
xmlhttp.send();
}
function getVal(i){
if(window.XMLHttpRequest){
xmlhttp= new XMLHttpRequest();
}else{
xmlhttp= new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function (){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
return xmlhttp.responseText;
}
}
xmlhttp.open('GET', 'include.inc.php?x='+i, true);
xmlhttp.send();
}
I am not sure what to check for in the parameter of the while loop (Im assuming we do not know how many rows are in the spreadsheet)
Is that my only issue or this the wrong way to go about it?
Also the function getRow return the entire row and getVal returns one column that will be important elsewhere on the page.
There are different approaches you can use:
1) Synchronise your requests:
function getRow(i, rows){
...
xmlhttp.onreadystatechange = function (){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
if xmlhttp.responseText != '' {
rows[i] = xmlhttp.responseText;
getRow(i+1, rows)
} else {
// call function that works with rows.
}
}
}
...
}
This function is only called with getRows(0, rows) (no loop!).
This is definitely the slowest approach because every request is started as soon as the previous request has finished.
2) Send number of rows first:
You could send the number of rows with the first or with each request, so javascript knows how many rows there are. Then you can loop over the rows and create asynchronous calls as you do now.
3) Send all rows at once:
I don't know your use case, but it looks like a waste of time to call every row separately. Why not make one call and return all of the data at once with linebreaks as delimiters (or something else suiting your data). If your data is really huge you could still break down the data into large chunks and combine this with option 1 or option 2.
4) Send data at page load:
Not sure if this is an option it looks like it is since you execute your function on document.ready. You could consider writing your data into a special hidden div and read the data from there (with javascript) into your variables. That way you avoid all the ajax calls. This is probably the fastest if you want to load all data anyway.
Note: you might consider using jQuery which makes working with ajax a lot easier. Check jQuery get for example.

Send javascript arrays via ajax without using jquery

i have a javascript array with values like "correct", "wrong".
I want to send this array to my php file using ajax. But im not familiar with how.
This is what i have tried so far..and i would like to do this without jquery.
var hold=[];
for(t = 0;t <= 10; t++){
answers_Arr = document.getElementsByName("question"+t);
for (k = 0; k < answers_Arr.length; k++){
if(answers_Arr[k].checked){
hold[t] = answers_Arr[k].value;
//document.getElementById("test"+t).innerHTML = "Value: "+ hold[t];
break;
}else{
hold[t] = "no";
continue;
}
}
}
var jsonString = JSON.stringify(hold);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("test1").innerHTML= xmlhttp.responseText;
}
}
xmlhttp.open("GET","result.php?res="+hold[],true);
xmlhttp.send();
}
Here is an example of sending the json string with POST through AJAX:
var jsonString = JSON.stringify(hold);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
//
}
xmlhttp.open("POST","result.php",true);
xmlhttp.setRequestHeader("Content-type", "application/json");
xmlhttp.send(jsonString);
Avoid sending json strings with GET method because if the request string gets too long, the browser will throw you an error.
Now in your php script you will have all the data in $_POST
Edit: Looks like on some versions of php, the requests that have other Content-type, like application/json, the $_POST has an empty value. To fix this you can do:
$_POST = json_decode(file_get_contents('php://input'));
replace this line
xmlhttp.open("GET","result.php?res="+hold[],true);
with
xmlhttp.open("GET","result.php?res="+jsonString,true);

Categories

Resources