Getting xmlhttp response empty when json object accessed through server path - javascript

I have a js function which goes to a spring controller class returning a json object with data like :
{"prop1":"val1",
"prop2":"val2"}
The js function is something like :
accessValue(a,b,c){
var xmlhttp = new XMLHttpRequest();
alert("This works 1");
xmlhttp.onreadystatechange = function() {
alert("This works 2");
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
alert("This works 3" + xmlhttp.status);//line 1
if (xmlhttp.status == 200) {
var jsonobj = JSON.parse(this.responseText); //line 1
alert("Hi ");
document.getElementById(b).innerHTML = jsonobj.prop1;
document.getElementById(c).innerHTML = jsonobj.prop2;
console.log(jsonobj.prop2);
}
else if (xmlhttp.status == 400) {
alert('There was an error 400');
}
}
};
xmlhttp.open("GET", a + "--spring controller class path --");
xmlhttp.send(null);
}
In the function parameters b and c are div ids which I want to update with the data which comes in the json object. Parameter a is a URL which is appended with spring path of the controller class, this class returns json object which runs perfectly fine.
At line 1, I am getting status for xmlhttp.status as 0 which is empty response. After searching online I found out that this may happen bcz the file may be accessed locally properly but through server its not happening. The same code when used on localhost works great. Is there a way I could access this spring controller returned json object on server using proper http url and parse the data to update my divs ?

Related

I can't get a response from the server

I followed some guides on how to send json objects to the server(written using node.js) and it doesn't work, I have no idea what is wrong. I know that my server works fine since I tested it on postman so it's my js code that's the problem, all the tutorials I see follow a similar XMLHttpRequest format.
this is my code
var ing = new Ingredient(name, date, qty, rp);
var url = "http://localhost:8081/addIngredient";
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
//Send the proper header information along with the request
// application/json is sending json format data
xhr.setRequestHeader("Content-type", "application/json");
// Create a state change callback
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
// Print received data from server
result.innerHTML = this.responseText;
}
};
// Converting JSON data to string
var data = JSON.stringify(ing);
document.write(data);
// Sending data with the request
xhr.send(data);
I used document.write to check where the code stops working but everything passes (since the document.write prints something), I suspect that there is something wrong/missing from xhr.send(data) but I can't tell what. Finally, nothing gets printed from the callback.
It's better to use onload instead of onreadystatechange
xhr.onload = function() {
if (xhr.status == 200) {
console.log(`Response length = ${xhr.response.length}`);
// store xhr.response here somewhere
}
};

Variable does not work outside of function

I have a function that loads a JSON file and gives it to a variable called articles. When i log articles inside of the function, it shows my json file, but when i log it outside of my function it doesn't show anything at all
I have tried to use let and var before articles inside of the function but that doesn't seem to work
var articles = ""
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.status == 200 && xmlhttp.readyState == 4){
articles = xmlhttp.responseText;
console.log(articles);
}
};
console.log(articles);
console.log(xmlhttp);
xmlhttp.open("GET","articles.json",true);
xmlhttp.send();
I want to be able to call my json file outside of my function by using articles, so that i don't have ot type xml.responseText each time.
In short, JavaScript does not synchronously wait for I/O operations to finish (network call in this case).
What this means is that when you log articles "outside of the function", the articles variable has not yet been set (the http request has not been completed).
Why are you hoping to have access to articles globally?
You could optionally pass your articles into a processing method after the http request has responded like so:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.status == 200 && xmlhttp.readyState == 4){
var articles = xmlhttp.responseText;
processArticles(articles)
}
};
xmlhttp.open("GET","articles.json",true);
xmlhttp.send();
function processArticles(articles) {
// Do something with articles here
}

Is it possible to return value from PHP to Ajax after error 500?

This Ajax is sending some data to php file and getting back the response that is showed in my html. Everything is working fine but sometimes I have been getting Error 500 response from php file. I know why and it is ok because as you can see after error 500 I'm calling the Ajax function again.
My question is. Is it possible to return from php file also some data after getting error 500? By data I mean variable returned from php file when the error occured.
function tr() {
var vysledok = document.getElementById('vysledok_body');
var text= document.getElementById('source').value;
var languageFrom = document.getElementById("src").value;
var languageTo = document.getElementById("dst").value;
vysledok.innerHTML="";
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', "https://.... someurl.php?
from=" + languageFrom + "&to=" + languageTo + "&text=" + text, true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
var obj = JSON.parse(xmlhttp.responseText);
console.log(obj.ip);
vysledok.innerHTML = "<p class='bdr'>"+obj.text+"</p>";
}
if(xmlhttp.status == 500) {
//console.log('nejde');
tr();
}
}
};
xmlhttp.send(null);
}
That depends entirely on what is causing the error. What you can do is catching the error if it is caused by an exception and in the catch block handle it the way you want.
For example you can return a value in the catch block and set the response code to 500 from PHP.
If however your script crashes with a fatal error that is not handled you can't change the return value there, but could still configure your web server to deliver a custom error page that can be read by your JS.

How to pass all the params as a single object while making ajax call

I have the below js code:
xmlhttp = GetXmlHttpObject();
if (xmlhttp != null) {
var url = "/support/residential/outage/serviceOutage?cbrnum=" + cbrnum + "&btn=" + btn + "&outagetkt=" + outagetkt;
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("thankyoucontent").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", url, true);
xmlhttp.send(null);
}
This calls a servlet by passing certain params in query string. Now my question is , can we bind all the params into a single object , send that object alone in query string and use the object in the servlet to retrieve the param values? Is it possible?
Yes, you can send the data as JSON to the server:
var data = {cbrnum: cbrnum, btn: btn};
var url = "...?data=" + encodeURIComponent(JSON.stringify(data));
Then on the server side, retrieve the value of data and parse the JSON into native data types (Converting JSON to Java).
Note though that browsers often impose a length limit on the URL. If you have a lot of data, do a POST request instead.

Why old red value persist in the browser, using XMLHttp request object?

I am reading a comma separated text file from the server, i get the valuse but when i chage the comma seprated variables in the file, it doesn't load the correct result int the browser
while browser persist the first time variable list only, whlile it works correct in IE, in firefox i am facig this proble.
How to sort it out
var arrUserTags = new Array();
var txt;
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "/TinyEditor/TextFile.txt", true);
xmlhttp.send();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
txt = xmlhttp.responseText;
arrUserTags = txt.split(",");
alert(arrUserTags.length);
parse();
}
}
// Add some values to the list box
function parse() {
for (i = 0; i < arrUserTags.length; i++) {
mlb.add(arrUserTags[i], arrUserTags[i]);
alert('hi');
}
}
You server is presumably sending caching instructions that tell browsers the URI for the text file won't change for a while.
Either configure the server to send no cache headers, or change the URI (e.g. by adding a rand() query string to it).

Categories

Resources