javascript : JSON obj not coming - javascript

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.

Related

Why is XMLHttpRequest failing the readystate and status state in localhost

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

Call to Api Marine Traffic javascript

I'm making this api call and not getting any results. When I make the call from the browser and search with that imo, I get back the vessel information but not in the call from code.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="pr"></div>
<script>
getInfoVessel("9146314");
function httpGetAsync(url, callback) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200){
callback(xmlHttp.responseText);
}
}
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
function getInfoVessel(IMO){
httpGetAsync('http://services.marinetraffic.com/api/exportvessel/v:5/7[herecomesthekey]/protocol:jsono/imo:9146314', function(response) {
document.getElementById('pr').innerHTML = response;
});
}
</script>
</body>
</html>
The response is good Status Code:200 OK but there is an error in the response KEY NOT FOUND.
Try this code:
function httpGetAsync(url, callback) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200){
callback(xmlHttp.responseText);
}
}
}
function getInfoVessel(IMO){
httpGetAsync('http://services.marinetraffic.com/api/exportvessel/v:5/7[herecomesthekey]/protocol:jsono/imo:' + IMO, function(response) {
console.log(response)
document.getElementById('pr').innerHTML = response;
});
}
getInfoVessel("9146314");

Making a Javascript Loop request in rails view

I need to download a file from a link I am given. In order to do this I must make a get request to that link. It can have 3 states:
1. Code 200 and the download will begin once the request landed
2. Code 202 which means I must repeat the request because the file is being uploaded
3. Error code and I must create a dom element that shows that.
How it works:
I make a request to this rails action:
def by_month
export_form = Commissions::ByMonthForm.new(current_user)
if export_form.submit(params)
#export = export_form.export
else
show_errors export_form.errors
end
end
This in turn starts the file upload. Which I don't know when it's ready(depending on how big the file it is). Now I must create a javascript get request to a link that follows the indications I have given at the beginning of the post. And integrate it in the by_month.html.erb view from rails . The javascript I managed to write is:
function httpGetAsync(theUrl){
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
redirect_to_main();
}
else if(xmlHttp.status == 202) {
httpGetAsync(theUrl);
}
else {
make_error_css();
}
}
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
However I don't think it works. Any ideas of how I can do this?(redirect_to_main and make_error_css are functions that I will implement myself later).
Update As per the comments below
Can you try this,
function httpGetAsync(theUrl){
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
redirect_to_main();
}
else if(xmlHttp.status == 202) {
setTimeout(
makeRequest(theUrl),
3000);
}
else {
make_error_css();
}
}
}
//makeRequest(xmlHttp, theUrl);
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
function makeRequest(theUrl){
httpGetAsync(theUrl);
}
makeRequest() is where the request is made again if the status is 202.

Ajax in timer is affecting my server

I am using ajax so that i can read the content of a file from my server .I am calling a function where ajax is , in a timer.And this is affecting my server .It is crashing.If this is the correct way to do it , what's wrong?
Please give a few sugestions,because i don't know what its problem is.
I am calling first the function:"function(ctrl)".
function get(ctrl){
var content;
content=ctrl.id;
var getTextUpdate= setInterval(function () {
readdocument();
}, 1200);
}
function readdocument() {
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("area").value=xmlhttp.responseText;
}
}
xmlhttp.open("GET","../user/test/read-text.php?user="+content,true);
xmlhttp.send();
}
Here it is the read-text.php file:
<?php
$rec_user=$_GET['user'];
echo($rec_user);
$chat = fopen($rec_user.".txt", "r") or die("Unable to open file!");
echo fread($chat,filesize($rec_user.".txt"));
fclose($chat);
?>
The problem with your code is that, you are not waiting for the response to get over. So over the time, you are sending request after request. This is going to use up all memory in due time. So first wait for the response before sending the next request.
How about this ?
function loadXMLDoc(ctrl) {
var content=ctrl.id;
var xmlhttp = new XMLHttpRequest();
var url = "../user/test/read-text.php?user="+content;
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if (xmlhttp.status == 200) {
document.getElementById("area").value=xmlhttp.responseText;
setTimeout(loadXMLDoc(), 1200); //call the function again
} else if (xmlhttp.status == 400) {
console.log('There was an error 400');
} else {
console.log('something else other than 200 was returned');
}
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
};
loadXMLDoc(ctrl);

The web service execution doesn't work in HTML

I am trying to test an exemple of consuming a web service (SOAP) in HTML and JavaScript through this code:
<script type="text/javascript">
function soap() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', 'http://www.webservicex.net/CurrencyConvertor.asmx', true);
var sr =
'<?xml version="1.0" encoding="utf-8"?>' +
'<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://www.webserviceX.NET/">'+
'<soapenv:Header/>'+
'<soapenv:Body>'+
'<web:ConversionRate>'+
'<web:FromCurrency>EUR</web:FromCurrency>'+
'<web:ToCurrency>TND</web:ToCurrency>'+
'</web:ConversionRate>'+
'</soapenv:Body>'+
'</soapenv:Envelope>';
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
alert('done use firebug to see response');
}
}
if (xmlhttp.readyState == 0) {
alert('open() has not been called yet');
}
if (xmlhttp.readyState == 1) {
alert('send() has not been called yet');
}
if (xmlhttp.readyState == 2) {
alert('send() has been called, ...');
}
if (xmlhttp.readyState == 3) {
alert('Interactive - Downloading');
}
else
alert('Consuming Error');
}
// Send the POST request
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.send(sr);
// send request
// ...
}
</script>
The problem is that nothing is shown (I talk about the differents alerts), and the "onreadystatechange" function is not executed!
I didn't figure out the reason?
Thanks in advance!

Categories