not entering in "xmlhttp.onreadystatechange=function() {" - javascript

I am following my old question post that I suddenly enter in a new problem that is: my code is not entering in this line "xmlhttp.onreadystatechange=function()". I also checked by marking alert. so I unable to understand. can somebody tell me why this is not happening?
<html>
<head>
<script>
function changeThis(){
xmlHttp = new XMLHttpRequest();
var formInput = document.getElementById('theInput').value;
/* formInput will be undefined */
document.getElementById('newText').innerHTML = formInput;
/* also undefined */
// var xmlHttp = null;
xmlhttp.onreadystatechange=function() //help
{
alert("y"); // not entering help?????
if (xmlhttp.readystate==4 && http.status==200)
{
document.getElemenById('newText').innerHTML=xmlhttp.reponseText;
}
if(xmlhttp.status == 404)
{
var temp = "NO file found";
document.getElementById('newText').innerHTML=temp;
}
xmlHttp.open( "GET", "file2.php", true);
xmlHttp.send();
}
}
</script>
</head>
<body>
<p>You wrote: <span id='newText'></span> </p>
<textarea id="theInput" style="height:200px;">Write Here</textarea>
<input type='button' onclick='changeThis()' value='See what you wrote'/>
</body>
</html>

Move this:
xmlHttp.open( "GET", "file2.php", true);
xmlHttp.send();
outside of the onreadystatechange handler; your current code won't try to submit the HTTP request until after the HTTP request is already making progress. (Hat-tip to judder for editing your question to indent your code properly, making this problem obvious.)
Edited to add: Also, as Pavlo points out, you need to consistently write xmlHttp. JavaScript variable-names are case-sensitive, so xmlhttp is a completely different variable.

Related

How to use CORS?

I am trying to implement Ajax calling and i came across the follwing code:
<!DOCTYPE html>
<html>
<body>
<p id="demo">Let AJAX change this text.</p>
<button type="button" onclick="loadDoc()">Change Content</button>
<script>
function loadDoc() {
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
}
xhttp.open("GET", "www.google.com", true);
xhttp.send();
}
</script>
</body>
</html>
I am tring to access the URl but ended up in error saying "XHR cannot load".
I know it is something related with CORS. I went through several pages but i am finding it difficult to understand the issue. can somebody please explain and resolve this issue?? Will be helpul
Google dont allow cross domain access to their search engine. Your method seems ok, its just the url you are trying to access doesn't allow your domain.
Try it with a file hosted on your local machine

loading servlet from jsp and trying to pass multiple parameters

im trying to load a servlet using java script from a jsp. i am also trying to pass two parameter. the page loads but now im printing a sytem out from the servlet it suppose to give me the id and the vehicle vaules but it gives the vehicle felid as null.
ScanServlet doGet was called id = 1 vehicle= [object HTMLParagraphElement]vehicle=null
this is the code
<body onload="notifyOnLoad(<%=request.getParameter("imgid")%>)">
<img id="imgBarcode" src="ImageServlet?imgid=<%=request.getParameter("imgid")%>&vehicle=<%=request.getParameter("vehicle")%>" width=<%=request.getAttribute("Width")%> height=<%=request.getAttribute("Height")%>><br/>
<h4>Barcode Details</h4>
<p>Name :- <%=request.getAttribute("name")%></p>
<p>Type :- <%=request.getAttribute("type")%></p>
<p>Value :- <%=request.getAttribute("value")%></p>
<p id="wtf">type :- <%=request.getParameter("vehicle")%></p>
<script type="text/javascript">
function notifyOnLoad(imgid) {
var xmlhttp;
var vehicle =document.getElementById("wtf");
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) {
window.location = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "ScanServlet?imgid="+imgid+"vehicle="+vehicle, true);
xmlhttp.send();
}
</script
>
</body>
You cant directly access the request parameters in the javascript in the way you are trying.
<input type='hidden' name='field1' id='imgid' value='<%=request.getParameter("imgid")%>' />
access the variable in the javascript with its id,
<script type="text/javascript">
function notifyOnLoad(imgid,vehicle) {
var xmlhttp;
var imgid=document.getElementById("imgid");
xmlhttp.open("GET", "ScanServlet?imgid="+mgid+"&vehicle="+vehId, true);
xmlhttp.send();
}

What is wrong with this code using ajax?

I'm new to coding and now I'm trying to write a code that gets the text data form a file and replace the present text with the new one. I'm using AJAX to do the task but the problem is first I'm getting the error message and then expected answer The error message is what I have included in the code to display when there is error. Even though i'm getting the desired answer I want to know why the error message is displayed. Here is my code
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js"></script>
<script>
function loadXML() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest;
}
else {
xmlhttp = new ActiveXObject("MICROSOFT.XMLHTTP")
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("p1").innerHTML = xmlhttp.responseText;
}
else {
alert(" there is a error in your code");
}
}
xmlhttp.open("GET","robots.txt", true);
xmlhttp.send(null);
}
</script>
</head>
<body>
<p id="p1">This is Text</p>
<button id="b1" onclick="loadXML()">Click me </button>
</body>
</html>
The problem is your if-block in onreadystatechange. During the request and response, xmlhttp.readyState changes multiple times and onreadystatechange is called every time this happens.
If you do it like this, it may work:
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 ) {
if( xmlhttp.status == 200 ) {
document.getElementById("p1").innerHTML = xmlhttp.responseText;
} else {
alert(" there is a error in your code");
}
}
It is simpler, however, to use the other event-methods like onload and onerror, as described here.
1- include 1 jQuery file jquery-1.9.0.js same as jquery-1.9.0.min.js but jquery-1.9.0.min.js is minified file
2- what is the Error message from javaconsole log ?
3- you are using jQuery so why you are working with XMLHttpRequest when jQuery $.get already using best of HttpRequest for all browsers
you can replace your JS code with this
<script type="text/javascript">
$( document ).ready(function() {
$.get('robots.txt',function(data){ $('#p1').html(data) });
});
<script>
Are you using a webserver ? Ajax doesn't work from local file url : 'file://...'
alert(" there is a error in your code");
Actually there is no error in your code. xmlhttp.onreadystatechange is called in different states of the request. Thats why you check for xmlhttp.readyState == 4. Learn more about the different stages here: http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp
So your code is running fine, you just alert an error message, that is not an error at all.

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

onreadystatechange function not being called

For some reason, onreadystatechange call back function is not being called in asynchronous mode. I tested the post in synchronous mode and confirmed that post itself is working fine (commented out testing code I used to check post in synchronous mode). The problem occurs both in safari and firefox latest version. Can someone please tell me what I am doing wrong here? Thank you.
<html>
<head>
<script>
function recordScore(str)
{
if (str.length==0)
{
return;
}
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
var url="http://hellworld3.appspot.com/findcountry";
var params = "screenname="+document.getElementById("screenname1").value+"&score="+document.getElementById("score1").value;
alert("params: "+params);
xmlHttp.open("POST",url,true);
xmlHttp.onreadystatechange = function()
{
alert("entered call back function. readstate value is: "+xmlHttpreadyState+". Response Text is: "+xmlHttp.responseText);
if (xmlHttp.readyState==4)
{
document.getElementById("message").innerHTML=xmlHttp.responseText;
}
}
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
xmlHttp.send(params);
//Testing code for synchronous mode
//alert("Http get status is: "+xmlHttp.status);
//alert("Http ready state value is: "+xmlHttp.readyState);
//alert("Http get response text is: "+xmlHttp.responseText);
//document.getElementById("message").innerHTML=xmlHttp.responseText;
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
</script>
</head>
<body>
<form name="testform">
Screename:
<input type="text" id="screenname1" name="screenname">
<br/>
Score:
<input type="text" id="score1" name="score" onchange="recordScore(this.value)">
<br/>
<p id="message">test</p>
<input type="submit" value="Submit">
</form>
</body>
</html>
you have an error in the onreadystatechange function:
alert("entered call back function. readstate value is: "+xmlHttpreadyState+". Response Text is: "+xmlHttp.responseText);
xmlHttpreadyState should be xmlHttp.readyState
After I fixed that, it worked for me in FF3
Correct me if I'm wrong, but for POST don't you need to do a setRequestHeader for Content-Length like so;
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader('Content-length',(params?params.length:0));
xmlHttp.send(params);
This might correct your problem.

Categories