I am facing a problem in synchronizing my CGI with web-page. I have one CGI which is written in C Language and is responsible for creating XML file and continuously updating it. My web page reads that XML and displays the content on the page. And Both (CGI and Web-page) are continuously running. Some times when my CGI writing the data in to the xml file, web-page tries to read it at the same time and my function which is written in java script fails to read Data. Is there any way to synchronize this. (Like in linux we use mutex) Something like that.
Some snap of my code which i am using to read XML file:
<xml ID="noteXML"
SRC="note.xml"></xml>
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","note.xml?"+ Math.random(),false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
document.getElementById("to").innerHTML=
xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue;
Part Of my CGi to create XML
void CreateXMLFile()
{
char buffer[300];
sprintf(buffer,"<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?> \n <note> \n <to>%d</to> \n <status>%s</status> <upgraded>%d</upgraded> <remaining>%d</remaining> \n </note>",100,"Welcom to XML",10,15);
FILE *xml = fopen("/var/www/html/note.xml","w");
if(xml)
{
fprintf (xml,"%s",buffer);
fclose(xml);
}
When debugging its giving error in following line (Java Script):
"document.getElementById("to").innerHTML= xmlDoc.getElementsByTagName("to") [0].childNodes[0].nodeValue;"
Use file locking (flock) to mark when a file is in use so you block reading from it until it is updated. You'll probably have to read it through another CGI application so that you can respect the lock.
Better yet - don't store your data in an XML file in the first place. Use an RDBMS and generate the XML on the fly.
Related
I've been searching around for answers to this particular problem for about two days now. I can't seem to figure out what's going on with it. All this seemed to have worked in the past but isn't working anymore.
XML:
<ZipCodes>
<results>
<city>Chicago</city>
<state>IL</state>
<timezone>-6</timezone>
</results>
javascript:
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","_checkzip.php?zip="+str,true);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
x=xmlDoc.getElementsByTagName("results");
i=0;
document.forms["signup"]["City"].value=(x[i].getElementsByTagName("city")[0].childNodes[0].nodeValue);
document.forms["signup"]["states"].value=(x[i].getElementsByTagName("state")[0].childNodes[0].nodeValue);
document.forms["signup"]["TimeZone"].value=(x[i].getElementsByTagName("timezone")[0].childNodes[0].nodeValue);
and the error I get is
Cannot read property 'getElementsByTagName' of null
when I try x=xmlDoc.getElementsByTagName("results"); The xml is deffinetly coming in on the network response when I look at the debug in Chrome.
You can use an event handler on an XMLHttpRequest's onreadystatechange to make sure the request is done. If the status of readyState is 4, the operation is complete.
Currently you're asking for data that hasn't been transmitted yet.
Apart from ensuring that xmlhttp.readyState==4 && xmlhttp.status==200, this error can also occur if you outputed any content, letter, character or string before sending your xml data from the server. For instance Assuming that in java you have a method/function called sendXMLdata, and then in your servlet you printed the string "connected" before calling the method:
....
out.println("Connected");
String data="My Name"
sendXMLdata(response,data);
....
Then the output when viewed from browser source will be this:
Connected
My Name
So this will certainly give you an error since the browser would not be able to parse the string "connected" since it is not the write format to render xml data.
I want to fetch the content of a file in server without extension using AJAX. Simple demonstration of code is as follows:
<html>
<head>
<script>
function read_my_file(){
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById ("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","MYFILE",true);// MYFILE HAS NO EXTENSION
xmlhttp.send();
}
</script>
</head>
<body>
<h2>THIS FETCHES DATA FROM SERVER IF WORKS!!!!!!</h2>
<button type="button" onclick="read_my_file()">Request data</button>
<div id="myDiv"></div>
</body>
</html>
As the file MYFILE has no extension, I think it is interpreted as folder name and I get 404 error. How can I fix this?
If chris's answer does not work you could also try and specify what mime-type your page should have using:
xmlHttp.overrideMimeType("application/xml");
or
xmlHttp.setRequestHeader("Accept", "text/html");
and simply replace "application/xml" or "text/html" with the type you need.
If you want to load a file directly, it must be located within the web server's document root. That is, if the document root is /var/www/example.com/public, then you can access files like this:
/var/www/example.com/public/json/myfile.json
xmlhttp.open("GET","json/myfile.json",true);
xmlhttp.open("GET","http://www.example.com/json/myfile.json",true);
It can't, however, be accessed if the file is located at /var/files/json/myfile.json, since that lies outside the document root! You'd have to use a server-side language (such as PHP) to read the file.
I want to create a Login-Screen in HTML where the user can fill out his username and password. After that he sends the Data with a submit to the server which validate the data. If the Login is correct he sends back a message in JSON format with an id, like this:
{"id":"37"}
Now my question: How can i get this information in Javascript? I want to check the id and, if it's OK, redirect the user to a new HTML screen.
I'm working with PhoneGap to create a Android Application, so the only things I can use are HTML, CSS and JavaScript. To send the POST i use the HTML <form> tag, not a special JavaScript. If I test it in Firefox it works, I fill out my Username and Password and then the Message with the id is shown. Now I want to react on this response with JavaScript. Can somebody help me?
AJAX Code:
function loadXMLDoc() {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4) {
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
};
xmlhttp.open("POST",url,true);
xmlhttp.send(login);
A JSON parser will recognize only JSON text, rejecting all scripts. In browsers that provide native JSON support, JSON parsers are also much faster than eval. It is expected that native JSON support will be included in the next ECMAScript standard.
var myObject = JSON.parse(myJSONtext, reviver);
The optional reviver parameter is a function that will be called for every key and value at every level of the final result.
now access the id property like myObject.id
on $(document).ready(function() in index.php, the below AJAX is executed, running the file getData.php:
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("dataSuccess").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getData.php",true);
xmlhttp.send();
In the getData.php file, data is gathered from MySQL and put in JS-arrays:
var guestData = new Array("<? for ($j=0;$j< sizeof($guestData);$j++) { print ($guestData[$j]); ?>","<?php } $j = $j+1; ?>");
And finally, store the data in my js arrays into LocalStorage:
var guestDataCols = new Array();
guestDataCols = guestData[0].split(",")
var arrayIndex=0;
for(arrayIndex=0;arrayIndex<guestData.length-1;arrayIndex++)
{
localStorage.setItem(arrayIndex, guestData[arrayIndex]); // storing
}
EVERYTHING works! But the problem is that my AJAX code doesn't seem to run through the entire getData.php file since LocalStorage in yet empty after the php-file is executed via AJAX. However (and this is a big one), if I simply refresh getData.php in another window, data is stored perfectly and evernything works. I've also tried using jQuery for this as suggested in another Stack Overflow question
$('#dataSuccess').load('getData.php'); //instead for the AJAX code
but with the exact same and somewhat mediocre result. So my questions is, why isn't the AJAX script running the entire php file and HENCE, why is no data stored in LocalStorage?
JavaScript on an HTML page is not run when called by an XMLHttp request. The browser doesn't parse the pages that JavaScript receives over XMLHttp requests and therefore does not run the JavaScript. You would have to output to the browser for it to be run. Your best bet would be do have the PHP return the data you need and then extract it from the XMLHttp request. For example, the getData.php could return a JSON string containing the data you need. Then on the page with the XMLHttp request, you could parse that JSON string and save it to the localStorage on that page.
I think you're looking for jQuery.getScript
I knew exposing web service is a obvious option, is there any other quick method?
That question is too general to answer in any sort of useful way. But that said: a lot of people are using JSON for data interchange these days. If you're willing to use jQuery or another library, it's extra-easy to use AJAX to grab JSON and act on it. Otherwise, I imagine it's not that difficult with plain JavaScript either.
Your question is very vague, so I will try to answer it before some trigger happy mod closes it (sweet sweet reputation points!)
One option is Ajax. This lets you ask the server for information using PHP scripts
Client (HTML/Javascript)[1]:
<html>
<head>
<script type="text/javascript">
function loadXMLDoc(){
var xmlhttp;
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
console.log(xmlhttp.responseText);
}
}
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
}
</script>
</head>
It looks intimidating, but all you're doing is saying GET me the stuff in ajax_info.txt on the server, and when you do get it (onreadystatechange) write it out for me (console.log).
You can use the above and tweak it so instead of reading a text file it reads a PHP file. That way you could ask it to execute a PHP script, which reads the contents of the server (server type, database elements...) and returns it to the user. Here is How I do it (I use Dojo instead of pure javascript)
On the Client:
dojo.xhrGet({
url: 'getUser.php',
handleAs: "text",
content: {
title: "Mr. "
},
load: function(data) {
console.log(data);
}
}
on the server ('getUser.php'):
<?php
echo $_GET['title'] . get_current_user();
?>
The server will concatenate 'Mr.' with the current user and return it to the client which will print out something like so
Mr. www-data
Finally another way is to embed directly into javascript/html so when you load the page, the server automatically updates the source code (warning, this requires quite a bit of tweaking)
index.html/index.php [2]:
<html>
<head></head>
<body class="page_bg">
Hello, today is <?php echo date('l, F jS, Y'); ?>.
</body>
</html>