javascript code is not working in browser? - javascript

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();
}

Related

Request to external domain

I want to make a request to external domain,
parameter is sent correctely to php file (on external server)
but "request.responseText" allways empty,
thanks in advance (an example will be very apreciate)
<script type="text/javascript">
function get_XmlHttp() {
var xmlHttp = null;
if(window.XMLHttpRequest) { // for Forefox, IE7+, Opera, Safari, ...
xmlHttp = new XMLHttpRequest();
}
else if(window.ActiveXObject) { // for Internet Explorer 5 or 6
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp;
}
function ajaxrequest() {
var request = get_XmlHttp(); // call the function for the XMLHttpRequest instance
var url = 'http://www.mydomain.fr/connexion.php?term=3334';
request.open("GET", url, true); // define the request
request.send(null); // sends data
request.onreadystatechange = function() {
if (request.readyState == 4) {
//response allways empty
document.getElementById("context").innerHTML = request.responseText;
}
}
}
window.onload = ajaxrequest();
</script>
<div id="context"></div>
by default you cannot just load data from another server, however if the server is configured to allow cross origin requests then you'll be good to go.
Take a read through the info here
http://www.html5rocks.com/en/tutorials/cors/

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.

Getting the responseText from XMLHttpRequest-Object

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.

Username and Password in URL

I am trying to load an XML file that asks for a username and password.
The code I'm using is as follows that I am trying to send the username and password in the URL:
xmlhttp.open("POST","http://admin:admin#192.168.0.5/myfile.xml",false);
The full code of my page looks like this:
<html>
<body>
<textarea id="test1" name="test1" cols="90" rows="30">
XML file will be displayed here
</textarea><br>
<script type="text/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.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("test1").value=xmlhttp.responseText;
} else
{
alert('Panel not communicating.Reason: '+xmlhttp.status);
}
}
xmlhttp.open("POST","http://admin:admin#192.168.0.5/myfile.xml",false);
xmlhttp.send();
</script>
</body>
</html>
Anyone know what I am doing wrong?
First, add this function to create the authorization header contents:
function make_base_auth(user, password)
{
var tok = user + ':' + pass;
var hash = Base64.encode(tok);
return "Basic " + hash;
}
Then, call the function and store the return value in a separate variable:
var auth = make_basic_auth('admin', 'admin');
Lastly, pass the value of auth to the XMLHttpRequest object:
xmlhttp.setRequestHeader('Authorization', auth);
xmlhttp.send();
Attribution: http://coderseye.com/2007/how-to-do-http-basic-auth-in-ajax.html
I ended up getting it working by doing the following:
Change:
xmlhttp.open("POST","http://admin:admin#192.168.0.5/myfile.xml",false);
To:
xmlhttp.open("POST","http://admin:admin#192.168.0.5/myfile.xml",false,"username","password");
See this question for a similar scenario. How to use Basic Auth with jQuery and AJAX? Note one answer states that IE does not support credentials in a URL (as you are attempting to do).

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