Getting the responseText from XMLHttpRequest-Object - javascript

I wrote a cgi-script with c++ to return the query-string back to the requesting ajax object.
I also write the query-string in a file in order to see if the cgi script works correctly.
But when I ask in the html document for the response Text to be shown in a messagebox i get a blank message.
here is my code:
js:
<script type = "text/javascript">
var XMLHttp;
if(navigator.appName == "Microsoft Internet Explorer") {
XMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
} else {
XMLHttp = new XMLHttpRequest();
}
function getresponse () {
XMLHttp.open
("GET", "http://localhost/cgi-bin/AJAXTest?" + "fname=" +
document.getElementById('fname').value + "&sname=" +
document.getElementById('sname').value,true);
XMLHttp.send(null);
}
XMLHttp.onreadystatechange=function(){
if(XMLHttp.readyState == 4)
{
document.getElementById('response_area').innerHTML += XMLHttp.readyState;
var x= XMLHttp.responseText
alert(x)
}
}
</script>
First Names(s)<input onkeydown = "javascript: getresponse ()"
id="fname" name="name"> <br>
Surname<input onkeydown = "javascript: getresponse();" id="sname">
<div id = "response_area">
</div>
C++:
int main() {
QFile log("log.txt");
if(!log.open(QIODevice::WriteOnly | QIODevice::Text))
{
return 1;
}
QTextStream outLog(&log);
QString QUERY_STRING= getenv("QUERY_STRING");
//if(QUERY_STRING!=NULL)
//{
cout<<"Content-type: text/plain\n\n"
<<"The Query String is: "
<< QUERY_STRING.toStdString()<< "\n";
outLog<<"Content-type: text/plain\n\n"
<<"The Query String is: "
<<QUERY_STRING<<endl;
//}
return 0;
}
I'm happy about every advice what to do!
EDIT: the output to my logfile works just fine:
Content-type: text/plain
The Query String is: fname=hello&sname=world
I just noticed that if i open it with IE8 i get the query-string. But only on the first "keydown" after that IE does nothing.

You don't have to use javascript: in on___ handler, just onkeydown="getresponse();" is enough;
IE>=7 supports XMLHttpRequest object, so directly checking if XMLHttpRequest exists is better than checking whether navigator is IE. Example:
if(XMLHttpRequest) XMLHttp=new XMLHttpRequest();
else if(window.ActiveXObject) XMLHttp=new ActiveXObject("Microsoft.XMLHTTP");
inside your getresponse() function, try to add below code at the beginning (before open):
try{XMLHTTP.abort();}catch(e){}
Because you're using a global object, you may want to "close" it before opening another connection.
Edit:
Some browser (maybe Firefox itself?) do not handle non-"text/xml" response very well in default state, so to ensure things and stuffs, try this:
function getresponse () {
try{XMLHttp.abort();}catch(e){}
XMLHttp.open("GET", "http://localhost/cgi-bin/AJAXTest?" + "fname=" +
document.getElementById('fname').value + "&sname=" +
document.getElementById('sname').value,true);
if(XMLHttp.overrideMimeType) XMLHttp.overrideMimeType("text/plain");
XMLHttp.send(null);
}

My problem had nothing to do with the code...
I was testing my script on the local IIS7 and I opened the html-page with double-clicking on the file. But you have to open the webpage via browser (localhost/mypage.htm) because otherwise for the browser the html and the executable have different origins. which is not allowed.

Related

javascript code is not working in browser?

Here is my code it will send get request and renders some content of the response in html.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Mytitle</title>
</head>
<body>
<script type="text/javascript">
function httpGet() {
var xmlHttp = null;
var x = document.getElementById("city").value;
var url = "http://api.openweathermap.org/data/2.5/find?q=chennai&units=metric&mode=json";
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", url, false);
xmlHttp.send();
var obj1 = JSON.parse(xmlHttp.responseText.toString());
document.getElementById("placeholder").innerHTML = obj1.message
+ " " + obj1.list[0].name;
}
</script>
<input type="text" id="city" />
<input type="button" value="submit" onclick="httpGet()" />
<div id="placeholder"></div>
</body>
</html>
this code is working perfectly when i run in eclipse browser. but its failing in Browser.
I have checked browser configuration for script enabling and its enabled. and also no issue with browser configuration.
Im new to javascript http requests.
Please suggest
I read somewhere that the Eclipse browser doesn't adhere to the same origin policy [Wikipedia]. That's why it is possible to make an Ajax request to an external URL, something that is not possible by default in a "normal" browser.
And indeed if I try to run your code [jsFiddle], I get the following error:
XMLHttpRequest cannot load http://api.openweathermap.org/data/2.5/find?q=chennai&units=metric&mode=json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://fiddle.jshell.net' is therefore not allowed access.
There are multiple ways to work around the same-origin policy [SO]. In your case it seems that the service supports JSONP [SO].
With JSONP, your not making an Ajax call to the server, but instead you are using the URL with a dynamically created script element. Script elements are not restricted by the same-origin policy and therefore can load data (code) from other servers.
The server will return a JavaScript file which contains a single function call. The name of the function is specified by you via a query parameter. So, if the JSON response is usually:
{"message":"accurate","cod":"200", ...}
by adding the argument callback=foo to the URL, the server returns
foo({"message":"accurate","cod":"200", ...});
(follow this URL to see an example for your service)
This response can be evaluated as JavaScript. Note that you can not turn every JSON response into JSONP. JSONP must be supported by the server.
Here is a complete example:
// this function must be global since the script is executed in global scope
function processResponse(obj1) {
document.getElementById("placeholder").innerHTML =
obj1.message + " " + obj1.list[0].name;
}
function httpGet() {
var url = "http://api.openweathermap.org/data/2.5/find?q=chennai&units=metric&mode=json";
// the following line is just to explictly show the `callback` parameter
url += '&callback=processResponse';
// ^^^^^^^^^^^^^^^ name of our function
var script = document.createElement('script');
script.src = url;
document.body.appendChild(script);
}
DEMO
If you google for JSONP, you will find more information [Wikipedia] and tutorials.
I think ur xmlhttprequest instance is not getting created. It is some time browser dependent try this..
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)
{ your code }
In addition to needing a cross browser xmlhttpquest (which for that alone I'd use jQuery), you also need to wait for the document ready before accessing the city by id... that is, move your script block after your city definition (and I think you may need a form, depending on browser).
Perhaps something like this
<body>
<form>
<input type="text" id="city" />
<input type="button" value="submit" onclick="httpGet()" />
</form>
<script type="text/javascript">
function httpGet() {
if (typeof (document.getElementById("city")) == 'undefined') {
alert("Maybe console.log our alarm... but the sky appears to be falling.");
}
var xmlHttp = null;
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) {
var obj1 = JSON.parse(xmlHttp.responseText.toString());
document.getElementById("placeholder").innerHTML = obj1.message
+ " " + obj1.list[0].name;
}
}
var x = document.getElementById("city").value;
var url = "http://api.openweathermap.org/data/2.5/find?q=chennai&units=metric&mode=json";
xmlHttp.open("GET", url, false);
xmlHttp.send();
}
</script>
<div id="placeholder"></div>
</body>
function httpGet() {
var xmlHttp = null;
var x = document.getElementById("city").value;
var url = "http://api.openweathermap.org/data/2.5/find?q=chennai&units=metric&mode=json";
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", url, false);
xmlHttp.onreadystatechange = function(){
var obj1 = JSON.parse(xmlHttp.responseText.toString());
document.getElementById("placeholder").innerHTML = obj1.message
+ " " + obj1.list[0].name;
}
xmlHttp.send();
}

xmlhttprequest GET in javascript does not give response

I am trying to consume the weather web service provided by wsf.cdyne.com/WeatherWS/Weather.asmx. I am sure that I can get a response in XML format by using the uri " 'http://wsf.cdyne.com/WeatherWS/Weather.asmx/GetCityForecastByZIP?ZIP=' + zipcode".
So what I want to do now is sending the uri above using XmlHttpRequest. I added some alerts to monitor the status. After open() the readyState is 1. After that I can't get any other response. If I remove the statement "xmlHttpRequest.onreadystatechange = processRequest;", I cannot see any response after send(). So I just hope someone can help me to check what is wrong.
<html>
<head>
<title>weather app</title>
</head>
<body>
<script language="JavaScript">
function httpGet()
{
var xmlHttp;
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
if (xmlHttp.overrideMimeType)
xmlHttp.overrideMimeType('text/xml');
}
else if (window.ActiveXObject) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
}
}
}
xmlHttp.open( "GET", "http://wsf.cdyne.com/WeatherWS/Weather.asmx/GetCityForecastByZIP?ZIP=85281", false );
alert("1 " +xmlHttp.readyState);
xmlHttpRequest.onreadystatechange = processRequest;
alert("2 " +xmlHttp.readyState);
xmlHttp.send();
alert("3 " +xmlHttp.readyState);
document.write(xmlHttp.responseText);
return xmlHttp.responseText;
}
httpGet();
</script>
</body>
</html>
As correctly stated by #robertklep this request is cross-domain. Browsers disallow cross-browser requests as a security measure so you don't hijack the user's sessions on their sites etc.
To get it to work you can create a proxy on the local site. If the site offers support to use JSONP cross-domain, you could use that.
For more information lookup some information on cross-domain policies or if they have some API docs, they may have information there on your problem too.

Firefox not passing values from an input text field to a javascript function

I have a problem with firefox passing information into a javascript function. The following code works ok on Chrome, Safari and Opera. It has some issues in IE9 but overall does what it is supposed to.
Firefox however simply ignores the onchange and onclick with the console reporting "query is not defined". If there is a way around this or a different approach I'd love to know.
<div class="viewstory_controls_content">
Search
<input type="text" id="query" onchange="javascript:submitForm('../scripts/php/search.php', 'search_results',query,'main')" name="query"></input>
<button class="viewstory_search" onclick="javascript:submitForm('../scripts/php/search.php', 'search_results', query, 'main')">
<div class="viewstory_search_content">
Search
</div>
</button>
</div>
submit query:
function submitForm(url, target, term, type) {
// native XMLHttpRequest object
term = term.value;
url = url + "?term=" + term + "&type=" + type;
alert("url:" + url + "\ntarget:" + target + "\nterm:" + term);
document.getElementById(target).innerHTML = 'sending...';
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
req.onreadystatechange = function() {
jahDone(target);
};
req.open("GET", url, true);
req.send(null);
}
else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = function() {
submitFormDone(target);
};
req.open("GET", url, true);
req.send();
}
}
}​
I think this is because the browsers said to support your script actually look for a field whose name attribute is equal to query (please note I'm not 100% sure on this). As far as I know, this never worked in Firefox.
Simply replace query in the event handlers with document.getElementById('query'). In the onchange handler of the input, you can use this instead of query as well.
Also, don't use javascript: in inline event handlers. It's obsolete.
term is the third parameter , you are passing query there in function call like a variable. It is not defined anywhere . Pass the value of the field query

GetXmlHttpObject AJAX call to a php file

I am trying to call a php file using GetXmlHttpObject object and having some luck, but seem to have problem with the URL variable.
Is there something I have to do with the URL string differently?
Here is the relevant code:
remoteCounter('marks');//invoking function
document.write("<div id=\"marks\"></div>");//destination div
function GetXmlHttpObject () {
var xmlHttp = null;
try {
// Firefox, Opera 8.0+, Safari, IE 7+
xmlHttp = new XMLHttpRequest();
} catch (e) {
// Internet Explorer - old IE - prior to version 7
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
function remoteCounter(param){
counterObj = GetXmlHttpObject();
var url="HTTP://dnsname/directory/view.php?" + param;
alert(url + " " + counterObj);
counterObj.open("GET", url , true);
counterObj.onreadystatechange=updateCounter;
counterObj.send(null);
}
function updateCounter(){
//alert('updateCounter');
if (counterObj.readyState == 4 || counterObj.readyState == "complete"){
document.getElementById("marks").innerHTML=counterObj.responseText;
}
}
I can replace the counterObj.responseText variable in document.getElementById("marks").innerHTML=counterObj.responseText;
and see the test string correctly in the source document, so I know the html and jscript source is not the problem.
I have commented out code in the view.php file to just echo a simple string, but that is not showing either - which again makes me think the problem is in the request to the file, not in the file, not in the source.
Actual server name and directory have been replaced by dnsname/directory for this post. Including alert for debugging.
thank you for assistance.
Replace order of two first lines:
document.write("<div id=\"marks\"></div>"); //destination div
remoteCounter('marks'); //invoking function
It's necesary declarate div tag with id "marks" first.

Javascript code working in the html file not working when taken as a string in C++

I have html file with javascript code the contents of the file are as under:
I tried this code on Safari and it was working fine. But when I tried this on Firefox, it’s not working. Can any one suggest how to make it working on firefox.
<html><head></head><body><button type="button" onClick="handleButtonClick();">undo</button> <button type="button">redo</button><select><option value="V1">V1</option><option value="V2">V2</option><option value="V3">V3</option><option value="V4">V4</option><option value="V5">V5</option></select> <script type="text/javascript">function handleButtonClick(){var xmlHttp, handleRequestStateChange; handleRequestStateChange = function() {if (xmlHttp.readyState==4 && xmlHttp.status==200) { var substring=xmlHttp.responseText; alert(substring); } }
xmlHttp = new XMLHttpRequest();xmlHttp.open("GET", "http://csce.unl.edu:8080/test/index.jsp?id=c6c684d9cc99476a7e7e853d77540ceb", true);xmlHttp.onreadystatechange = handleRequestStateChange; xmlHttp.send(null);}</script>
</body>
</html>
if you copy the above code to your system on clicking on undo button u will get the contents
but the same code I am inserting through C++ as a string it is not working... what i figured out strange about the above code what that it required enter (return key) to be pressed before xmlHttp = new XMLHttpRequest(); othervise it was not working for html page also. The same thing I implemented in C++ code and the code is not working. The code is as under:
std::string login="<button type=\"button\" onClick=\"handleButtonClick();\">undo</button> <button type=\"button\">redo</button>< select><option value=\"V1\">V1</option><option value=\"V2\">V2</option><option value=\"V3\">V3</option><option value=\"V4\">V4</option><option value=\"V 5\">V5</option></select> ";
std::string jscriptstring1="<script type=\"text/javascript\">function handleButtonClick(){var xmlHttp, handleRequestStateChange; handleRequestStateChang e = function() {if (xmlHttp.readyState==4 && xmlHttp.status==200) { var substring=xmlHttp.responseText; alert(substring); } }";
std::string jscriptstring2="xmlHttp = new XMLHttpRequest();xmlHttp.open(\"GET\", \"http://csce.unl.edu:8080/test/index.jsp?id=c6c684d9cc99476a7e7e853d77 540ceb\", true);xmlHttp.onreadystatechange = handleRequestStateChange; xmlHttp.send(null);}</script>";
std::string ret="\n";
login+=jscriptstring1;
login+=ret;
login+=jscriptstring2;
Please can any one suggest what is going wrong?
First of all if you are going to create an XMLHttp object for requesting the server in different browsers be sure it is valid in the browser you are using (different browser have different manner to refer the XMLHttp object), normally this object is created as follow:
function getRequestObject(){
var xmlHttp;
if (window.ActiveXObject) { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); }
else if (window.XMLHttpRequest) { xmlHttp = new XMLHttpRequest(); }
return xmlHttp;
}
In the other hand, depending on your browser you can debug your script to see what error code is browser returning (if any).

Categories