I'm trying to make basic HTML Server connection, therfore I want to call and JS function which should call an PHP file just schoing "hello world". Everything is working so far but the response I get seems to be null.
I've read through various tutorials but I did not find an answer, hope someone can help me.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == XMLHttpRequest.DONE && xhttp.status==200 && xhttp.responseText!=null) {
alert("Responestext: " + xhttp.responseText + " ENDE");
}else if(xhttp.status==403){
alert("forbidden");
}else if(xhttp.status==404){
alert("not found");
}else if(xhttp.responseText==null) {
alert("response text = null");
}else{
alert("Error");
}
};
xhttp.open("GET", "http://URL/fahrgemeinschaft/login.php", true);
xhttp.send(null);
I expect the output to be "Responsetext: hello world ENDE" but all I get is "Error".
I get two alert boxes saying "Error" as well.
The problem is your onreadystatechange handler is called for every ready state change event, not just when it is done.
You should skip the events that are not done:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState != XMLHttpRequest.DONE) {
return;
}
if (xhttp.status==200 && xhttp.responseText!=null) {
alert("Responestext: " + xhttp.responseText + " ENDE");
}else if(xhttp.status==403){
alert("forbidden");
}else if(xhttp.status==404){
alert("not found");
}else if(xhttp.responseText==null) {
alert("response text = null");
}else{
alert("Error");
}
};
xhttp.open("GET", "http://messenger.hopto.org:8080/fahrgemeinschaft/login.php", true);
xhttp.send(null);
Or to make it easier on yourself, so long as you don't need to support obsolete browsers, just use the onload event.
var xhttp = new XMLHttpRequest();
xhttp.onload = function() {
if (xhttp.status==200 && xhttp.responseText!=null) {
alert("Responestext: " + xhttp.responseText + " ENDE");
}else if(xhttp.status==403){
alert("forbidden");
}else if(xhttp.status==404){
alert("not found");
}else if(xhttp.responseText==null) {
alert("response text = null");
}else{
alert("Error");
}
};
xhttp.open("GET", "http://messenger.hopto.org:8080/fahrgemeinschaft/login.php", true);
xhttp.send(null);
Related
Hi I have this code that for some reasons I don't understand just refuse to work. I really don't know what I will do anymore.
This is my code:
<script>
function findMatch() {
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}else {
xmlhttp = new ActiveXObject('Microsoft.XMLHttp');
}
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('results').innerHtml = xmlHttp.responseText;
}else {
console.log('not ready yet');
}
}
xmlhttp.open('GET','aindex.php',true);
xmlhttp.send();
}
</script>
<form>
Enter a name<br>
<input type="text" id="search" name="keyword"
onkeydown="findMatch();">
</form>
<div id="results"></div>
//THE PHP FILE TO OUTPUT
<?php
echo 'Did it work';
?>
It prints not ready in the console indicating that the readystate and status test failed. I am working with xamp.
Please pals, any help will be highly appreciative.
Thank.
You're not sending the search keyword to the PHP script.
var keyword = document.getElementById("search").value;
xmlhttp.open("GET", "aindex.php?keyword=" + encodeURIComponent(keyword)", true);
xmlhttp.send();
There's also little point in reporting an error when xmlhttp.state is not 4, other states are normal as intermediate steps. If you want to report an error, do it when xmlhttp.status is not 200.
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
document.getElementById('results').innerHtml = xmlHttp.responseText;
} else {
console.log("Bad status: " + xmlhttp.status);
}
}
I have a script that sends an AJAX request to a server and if the answer is just text it is gonna put it in a div but if its json it should handle it different.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.body.innerHTML = xhttp.responseText;
}
};
xhttp.open(method, "/controller.php?url=" + location, true);
xhttp.send(data);
now how can i check if xhttp.responeText is json?
In Javascript you can can use getResponseHeader('content-type') method to check the content type of returned JSON response
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
if(this.getResponseHeader('content-type') == 'application/json'){
//do something with the json
}
else{
document.body.innerHTML = xhttp.responseText;
}
}
};
xhttp.open(method, "/controller.php?url=" + location, true);
xhttp.send(data);
In Jquery you can try something like this
$.ajax({
type: "POST",
url: "www.yourURL.com",
data: "data which you want to sent to server",
success: function(response, status, xhr){
var ct = xhr.getResponseHeader("content-type") || "";
if (ct.indexOf('text') > -1) {
//do something
}
if (ct.indexOf('json') > -1) {
// handle json here
}
}
});
Basically it will check the string 'html' or 'json' exist in the response header
What is the issue in below script.Here alert "33here" is coming but am not getting my json object.alert(jsontext) is coming blank.if i hit this URL in browser then i am getting JSON object.
xmlHttp = new XMLHttpRequest();
xmlHttp.overrideMimeType("application/json");
alert('11here');
xmlHttp.open( "GET", "http://<hostname>/appsuite/api/login", true );
alert('22here');
alert(xmlHttp);
xmlHttp.send();
alert('33here');
var jsontext= xmlHttp.responseText;
alert(jsontext);
Tried as per suggestions but not working.I am new in javascript / ajax.Any issue in this ?
xmlHttp = new XMLHttpRequest();
xmlHttp.overrideMimeType("application/json");
alert('Hi 11here');
xmlHttp.open( "GET", "http://<hostname>/appsuite/api/login", true );
alert('Hi 22here');
alert(xmlHttp);
xmlHttp.send();
alert('Hi 33here');
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
alert(xmlHttp.responseText);
}
}
Ajax runs asynchronously. You can't depend on when the request from .open will complete or even if it will complete. Any code that depends on the value of an ajax request must be done in the request callback.
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
alert(xmlHttp.responseText);
}
}
A good place to start is looking at the examples provided by MDN: https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started
function alertContents(httpRequest) {
try {
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
alert(httpRequest.responseText);
} else {
alert('There was a problem with the request.');
}
}
}
catch( e ) {
alert('Caught Exception: ' + e.description);
}
}
After the request status reached 200 and the ready state is 4 the response is filled.
I am trying to send some parameters through xmlHttpRequest.send(params) written in a JS file to my servlet where I try to get the parameters by req.getParameter("some_Parameter"); it returns null on the servlet. though if i send the parameters by appending them in url it works fine. but when the url will be large it will break the code. so please someone help me out.
Thanks in advance.
function doHttpPost(theFormName, completeActivity)
{
var xmlhttp = new ActiveXObject("MSXML2.XMLHTTP");
var xmlMessage = buildPOST(theFormName, completeActivity);
var responseTxt;
try {
xmlhttp.Open(document.forms[theFormName].method, document.forms[theFormName].action+'?'+xmlMessage, false);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
responseTxt = xmlhttp.responseText;
}
}
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
enableDisableLinks(true);
setPointer();
xmlhttp.Send();
if(xmlhttp.Status != 200) {
alert("Post to server failed");
}
} catch (e) {
responseTxt = "Exception while posting form data: Error No: " + e.number + ", Message: " + e.description;
}
resetPointer();
enableDisableLinks(false);
var expectedTxt = "Form Data had been successfully posted to the database."
if(responseTxt.toString() == expectedTxt.toString()) {
// MNP: New requirement from Jeanne, should not refresh CM page, commenting it off for now
//if(completeActivity) {
// if (typeof (ViewCaseDetailBtn) != 'undefined') {
// ViewCaseDetailBtn.click();
// }
//}
return true;
} else {
alert (responseTxt);
}
return false;
}
BUGS
//IE only - shooting yourself in the
// Not all IE versions use ActiveX!
var xmlhttp = new ActiveXObject("MSXML2.XMLHTTP"); foot.
//JavaScript case sensitive, open !== Open
xmlhttp.Open(document.fo...
//JavaScript case sensitive, send !== Send
xmlhttp.Send();
//JavaScript case sensitive, status !== Status
xmlhttp.Status
AND if you are using synchronous, it does not call the onreadystatechange.
If you are using POST, the value needs to be in send("valuestosendup") not on the querystring.
This code shows why you should really use a framework to make Ajax calls and to not roll your own.
function gettime(str) {
var strURL="/Doctor/booking/gettime.jsp?datepicker="+str;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('d11').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
<b>Date:<input id="d11" type="text" name="datepicker" onClick="WdatePicker()" onchange="gettime(this.value)"/></b>
When I click the textbox, alert a datepicker and choose a date, the textbox should change its value. But it doesn't. What way can I solve it?
Moreover, when I directly enter this url: /Doctor/booking/gettime.jsp?datepicker=2012-02-02 I see the output that I want.
instead of:
document.getElementById('d11').innerHTML=req.responseText;
try:
document.getElementById('d11').value=req.responseText;