Why does local storage save last after javascript - javascript

Im currently trying to save the tab.url into html5 local storage when the programme loads then update a css file into the header based on a rule, which are all easy to do. But for some reason the popup.html loads the previous local storage variable and not the recent one.
I was wondering if anyone can help me on this, the code that im using is this;
<script language="javascript">
var rule;
var links;
var search;
function loadcssfile(filename, filetype)
{
if (filetype == "css")
{
var fileref=document.createElement("link");
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", filename);
}
if (typeof fileref != "undefined")
{
document.getElementsByTagName("head")[0].appendChild(fileref);
}
}
function loaded()
{
chrome.tabs.getSelected(null,function(tab)
{
var temp;
temp = tab.url;
localStorage['tab'] = temp;
console.log(temp);
});
links = localStorage['tab'];
rule = localStorage['ok0'];
search = links.indexOf(rule);
if(search != -1)
{
loadcssfile("./css/styles.css","css");
loadcssfile("./button/styles2.css","css");
}
else
{
// or load other css file
}
}
document.getElementById('datacontent').innerHTML = rule + "<br>" + links + "<br>" + search;
function createXMLHttpRequest()
{
if (window.ActiveXObject)
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest)
{
xmlHttp = new XMLHttpRequest();
}
}
function createXMLHttpRequest2()
{
if (window.ActiveXObject)
{
xmlHttp2 = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest)
{
xmlHttp2 = new XMLHttpRequest();
}
}
function handleStateChange1()
{
if(xmlHttp.readyState == 4 && xmlHttp.status == 200 )
{
var data;
data = xmlHttp.responseText;
document.getElementById('container').innerHTML = data;
}
}
function senddata(id)
{
createXMLHttpRequest();
xmlHttp.onreadystatechange = handleStateChange1;
xmlHttp.open("GET", "http://weblinkchecker.forum-source.tk/crawler.php?link=" + links.replace('&','0123456789abcdef'), true);
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttp.send("&type=anythinghere&anothervar=datahere");
document.getElementById(id).innerHTML = "Successful !";
}
function handleStateChange2()
{
if(xmlHttp2.readyState == 4 && xmlHttp2.status == 200 )
{
var data;
data = xmlHttp2.responseText;
document.getElementById('container2').innerHTML = data;
}
}
function sendForLinks()
{
createXMLHttpRequest2();
xmlHttp2.onreadystatechange = handleStateChange2;
xmlHttp2.open("GET", "http://weblinkchecker.forum-source.tk/links.php?link=" + links.replace('&','0123456789abcdef'), true);
xmlHttp2.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttp2.send("type=anythinghere&anothervar=datahere");
}
window.onload = function()
{
loaded();
}
</script>
As you can see its a web link checker, there is a bit css that I didn't upload, also there a lot of php using ajax but none of that is having an affect on the code and I also removed any innerHTML functions. Sorry for having such a large piece of code.
if any one could tell me why html5 local storage is saving last it would be a huge help. I tried echoing out data and it just gives out the old data and not the recent. I feel like I hit a brick wall with this one.

First off, your code is quite hard to read, please work on your coding style, for example:
Use more than 1 space for per indent
Don't place stuff on the same line with opening and closing curly braces
Use spaces around ==, != etc.
This will make your code a lot more readable :)
But on to your problem:
// this looks like a callback....
chrome.tabs.getSelected(null,function(tab) {
var temp;
temp = tab.url;
localStorage['tab'] = temp;
console.log(temp);
});
// this will most likely get executed BEFORE the callback gets called
// therefore the values just hasn't been changed yet
links = localStorage['tab'];
rule = localStorage['ok0'];
search = links.indexOf(rule);
You most likely need to move the rest of the loaded function into the callback.

Related

Fetch result from database when link clicked

I'm using this HTML code;
if ($forum['type'] != 'c' && !$forum['linkto'] && $forum['posts'])
{
$forum['collapsed_image'] = '
<div class="expcolimage">
<a id="forum_name" fid="'.$fid.'">
<img src="images/collapse_collapsed.gif" id="ann_'.$forum['fid'].'_img" class="expander" alt="[-]" title="[-]" />
</a>
</div>';
}
else
{
$forum['collapsed_image'] = '';
}
What I want to do is to make it so when this link is clicked then an sql query should be run on a PHP page which fetches a result from database show that result in a <div> on an HTML page (or to show that result just under that link on the same page)
Due to limited knowledge in javascript I'm unable to code a javascript function which do that process, can you please provide me an example? I'll be very thankful to you.
Thank you!
PLEASE NOTE: I only want to use javascript and not jQuery
This is how you can do this:
test.php - the entire script is to be placed on this single script.
<?php
// Handle GET Request
if (isset($_GET['loadData']) && isset($_GET['id']))
{
// Dummy Response
// you should query the database here
exit("hello #". $_GET['id']);
}
?>
<script type="text/javascript">
function ajaxCall(url, callback) {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 ) {
if(xmlhttp.status == 200){
callback(xmlhttp.responseText);
}
else if(xmlhttp.status == 400) {
alert('There was an error 400')
}
else {
alert('something else other than 200 was returned')
}
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function loadData(id)
{
ajaxCall('test.php?loadData&id='+ id, function(result) {
document.getElementById('result').innerHTML = result;
});
}
</script>
Click any of these links: <br>
Result: <div style="display: inline;" id="result"></div>
<br><br>
<?php
// this is your initial database query result with links
for ($i = 1; $i <= 3; $i++)
{
echo "• Hello, I am #$i. <a href='#' onclick='loadData($i);'>Click here<a> to load data.<br>";
}
?>
Demo:
The problem here is the way you're creating your html object. By doing it in one line you can't attach a listener for the click event.
I suggest to create elements in the javascript style:
var container = document.createElement("div");
container.className = "expcolimage";
var link = document.createElement("a");
link.setAttribute("fid", $fid);
var img = document.createElement("img");
img.src = "images/collapse_collapsed.gif";
img.id = "ann_" + $forum['fid'] + "_img";
img.className = "expander";
link.appendChild(img);
container.appendChild(link);
$forum['collapsed_image'] = container;
link.click(function(event){
event.preventDefault();
//AJAX code
});
Then I suggest you to look at these examples for choosing the best for you:
http://www.w3schools.com/ajax/ajax_examples.asp

Display server message after form submission without JQuery

I have a form that is supposed to display a feedback message from the server once it is submitted in <div id="resposta"></div>
I can't use JQuery on my page because it is also using Mootools and it's really a mess to avoid the conflicts with those two (I tried all sorts of things I don't to bother you with). Therefore, I must use pure JavaScript here.
Once the form is submitted (after validation) it calls the function getResposta below:
function getXmlHttp() {
var xmlhttp;
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
};
function getResposta(){
var resposta = document.getElementById("resposta");
var request = getXmlHttp();
request.open("POST", "thanks.php", true);
request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
request.onreadystatechange = function () {
if (request.readyState != 4) return;
if (request.status == 200) {
resposta.innerHTML = '<p>' + request.responseText + '</p>';
} else {
alert("Erro: "+request.statusText);
}
};
}
}
thanks.php:
<?php
echo "thank you";
?>
It seems that thanks.php isn't being called, although the form is correctly filled in and sent to the server.
I've tried typing in the absolute path to the file but it didn't work. So, what is wrong with this code?
Thanks for any help!

same domain xmlhttprequest access denied ie8

I'm fairly new to the world of web development and am trying to read a txt file in internet explorer 8 and compare it to source code of a website to see if they are equal. This is so I can work out if the web page is functioning correctly.
I managed to get the source code with an xmlhttprequest and have tried the same to get the text file (which is in the same domain as my web page) and I am getting an access denied error.
After some research I can see that cross-domain xmlhttprequests won't work but that's not what I'm trying to do so I'm not sure how to proceed.
Having run the same code in Firefox(current version). It will read the file but not the web page!
I don't mind which of the two browsers I end up using but at the moment each does half of what I want it to.
my code is:
function source1(){
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET", "http://website",true);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
document.getElementById('textzone').value = xmlhttp.responseText
var inputString = xmlhttp.responseText;
alert(inputString);
comparison(inputString)
}
}
xmlhttp.send(null)
}
function comparison(inputString){
xmlhttp1=new XMLHttpRequest();
xmlhttp1.open("GET", "comparisondoc.txt", false);
xmlhttp1.onreadystatechange=function() {
if (xmlhttp1.readyState==4) {
var compareString = xmlhttp1.responseText;
alert(compareString)
if(inputString==compareString){
alert("Strings are equal");
}
}
}
xmlhttp.send(null)
}
All I need to know is why either the file won't open in ie8, or why the website source code shows up blank (in the alert) in firefox. Any help would be appreciated.
It could be a browser support issue.
Try the following code to initialize your XMLHttpRequest :
function createRequest() {
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = false;
}
}
}
if (!request)
alert("Error initializing XMLHttpRequest!");
}
Check your comparison function. You should you xmlhttp1 instead of xmlhttp at 2 places
function comparison(inputString){
xmlhttp1=new XMLHttpRequest();
xmlhttp1.open("GET", "comparisondoc.txt", false);
xmlhttp1.onreadystatechange=function() {
if (xmlhttp1.readyState==4) {
<!--alert(xmlhttp1.responseText)-->
var compareString = xmlhttp1.responseText;
alert(compareString)
if(inputString==compareString){
alert("Strings are equal");
}
}
}
xmlhttp1.send(null)
}
Try to add the if(xmlhttp.status == 200) { } stuff. Remember both of these are looping through status' "AND" readystates.
Technically you could be erroring somewhere (I'd rather not speculate on) halting progress to next request or whatever without the status check.
Also you "should" try other request techniques. ie.. xmlhttp.onreadystatechange = function(){itsReady(inputString)}; // we keep this line short and simple calling to another func that contains your status and readystate checks, response stuff, and more func.
On a pretty normal run the Loop looks like:
hi rdySte:1///status 0////////
hi rdySte:2///status 200////////
hi rdySte:3///status 200////////
hi rdySte:4///status 200////////
I ran into a lot of weird issues trying the long onreadystatechange = function (){ ... All stuff..} I successfully run a crazy set of request functionalities using the short onreadystatechange technique.
I noticed at the last minute->
is there a reason why the async flags are different between your funcs? I'd set them all to true unless you have a great reason.
This will work: (to test: 2 pages t1.php contains a num or whatever and t2.txt that has a num in sam dir as the funcs are called in)
function source1(){
var avar = 1;
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET", "t1.php",true); // shortened f-names for ease of test
xmlhttp.onreadystatechange = function(){jsg_snd(avar)};
xmlhttp.send(null)
}
function jsg_snd(avar){
if (xmlhttp.readyState==4) {
if (xmlhttp.status == 200) {
var inputString = xmlhttp.responseText;
document.getElementById('text_zone').innerHTML = inputString;
document.getElementById('text_zone1').value = inputString;
// alert(inputString);//
comparison(inputString)
}
}
}
function comparison(inputString){
xmlhttp1=new XMLHttpRequest();
xmlhttp1.open("GET", "t2.txt", true);
xmlhttp1.onreadystatechange= function(){jsg_snd1(inputString);};
xmlhttp1.send(null)
}
function jsg_snd1(inputString){
if (xmlhttp1.readyState==4) {
if (xmlhttp1.status == 200) {
var compareString = xmlhttp1.responseText;
//alert(compareString)
if(inputString==compareString){
//alert("Strings are equal");
document.getElementById('text_zone').innerHTML += "; Ok "+inputString+"=="+compareString+"";
}
}
}
}
Now the html in your body should look like:
<tt id = 'text_go' onMouseUp="source1();" >Go!</tt>
<tt id = 'text_zone' onMouseUp="text_zone.innerHTML = '';" >Click to clear!</tt>
<input type ='text' id = 'text_zone1' onMouseUp="text_zone1.value = '';" value = 'Click to clear!' >
The extra stuf is for ___s & giggles.

letting user open an xml file on client and parse it using javascript

I'm trying to let a users on my site to save and XML file one the local machine and then later to load them using the HTML file element.
Saving the file what done with iFrame.
When trying to let the user load the file i am getting exceptions all the time.
I've tried every thing i could find over the web and can't seem to find the way to do it.
I am getting all kind of exception, like cross domain or XMLHttpRequest cannot load file:///C:/fakepath/Regions.xml. Cross origin requests are only supported for HTTP.
Depending on the code i tried.
I read that HTML5 standard replace the url with "fakepath", and can't find solution for this. Is there no way to let the user load a file from his own computer to be edited? loading a specific file from server is not a problem but i want to give this freedom to the user and not decide for them what file to load, and also to let them save and load the xml on their computer and not the server
Is there a solution for this problem?
Found this codes but neither helped (and I've tried few other veriations of this):
1)
var error = "";
strFile = document.frmLoadFile.selectedFile.value;
intPos = strFile.lastIndexOf("\\");
strDirectory = strFile.substring(0, intPos);
//alert(strDirectory);
document.frmLoadFile.selectedFile.value = strDirectory;
var file = 'file:\\\\\\' + document.frmLoadFile.selectedFile.value;
try //Internet Explorer
{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.load(file);
}
catch (e) {
try //Firefox, Mozilla, Opera, etc.
{
xmlDoc = document.implementation.createDocument("", "", null);
xmlDoc.async = false;
xmlDoc.load(file);
}
catch (e) {
try //Google Chrome
{
var xmlhttp = new window.XMLHttpRequest();
xmlhttp.open("GET", file, false);
xmlhttp.send(null);
xmlDoc = xmlhttp.responseXML.documentElement;
}
catch (e) {
error = e.message;
}
}
}
2)
var xmlDoc;
var xmlloaded = false;
function xml_initLibrary(file) {
importXML(file);
}
function importXML(xmlfile) {
try {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", xmlfile, false);
}
catch (Exception) {
var ie = (typeof window.ActiveXObject != 'undefined');
if (ie) {
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
while (xmlDoc.readyState != 4) { };
xmlDoc.load(xmlfile);
xmlloaded = true;
readXML();
}
else {
xmlDoc = document.implementation.createDocument("", "", null);
xmlDoc.onload = readXML;
xmlDoc.load(xmlfile);
xmlloaded = true;
}
}
if (!xmlloaded) {
xmlhttp.setRequestHeader('Content-Type', 'text/xml')
xmlhttp.send("");
xmlDoc = xmlhttp.responseXML;
xmlloaded = true;
readXML();
}
}
function readXML() {
//console.log(xmlDoc);
}
does any one knows if there is a way to fix this? of do you need to save the files on the server?
Thank you all very much
Erez
I think you're looking for FileReader, new in HTML5. For IE < 10 you'll need to use the ActiveX FileSystemObject.
This code works for me on Chrome.
<script type="text/javascript">
function doit(e) {
var files = e.target.files;
var reader = new FileReader();
reader.onload = function() {
var parsed = new DOMParser().parseFromString(this.result, "text/xml");
console.log(parsed);
};
reader.readAsText(files[0]);
}
document.getElementById("selectfile").addEventListener("change", doit, false);​
</script>
<input type="file" id="selectfile" />
http://jsfiddle.net/xKuPV/

add javascript get function to a href

I am very new to this
I have this link:
<a onclick = sendRequest('GET','room_chart.jsp') href=#>Show Chart</a>
but I need to generate dynamic address inside that link.
I created javascript:
<script language="javascript">
var selectedOption;
var ROOM;
var BUILDING;
function GetLink(){
selectedOption = document.getElementById("roomandbuildingid").options[e.selectedIndex].text; //getting selected option
ROOM = selectedOption.split("|")[0].trim().split(":")[1].trim(); //parsing text
BUILDING = selectedOption.split("|")[1].trim().split(":")[1].trim(); //parsing text
return "'room_chart.jsp?room="+ROOM+"&building="+ BUILDING+"'"; //returning url
}
</script>
but when I paste the function into it- it does not work!
<a onclick = sendRequest('GET',GetLink()) href=#>Show Chart</a>
Now, after debug, I found out that actually it creates the proper srting, but somehow my function is not willing to accept it as URL! It is quite a paradox- it creates correct string- if I hardcode it into the code- it works! But dynamic links from variables - don't work!
please help!
see below:
my js file:
function createRequestObject(){
var req;
if(window.XMLHttpRequest){
//For Firefox, Safari, Opera
req = new XMLHttpRequest();
}
else if(window.ActiveXObject){
//For IE 5+
req = new ActiveXObject("Microsoft.XMLHTTP");
}
else{
//Error for an old browser
alert('Your browser is not IE 5 or higher, or Firefox or Safari or Opera');
}
return req;
}
//Make the XMLHttpRequest Object
var http = createRequestObject();
function sendRequest(method, url){
if(method == "get" || method == "GET"){
http.open(method,url);
http.onreadystatechange = handleResponse;
http.send(null);
// alert( document.URL );
// document.write (GetLink());
}
}
function handleResponse(){
if(http.readyState == 4 && http.status == 200){
var response = http.responseText;
if(response){
document.getElementById("ajax_res").innerHTML = response;
}
}
}
OK, the function was returning everything correctly, the parsing was not done right. I fixed it. JavaScript is hard for me to debug.

Categories

Resources