Cannot execute alert - javascript

I am writing a javascript code wherein a alert is to be provided when a condition gets executed
I referred some youtube videos on ajax and json and wrote a code wherein i successfully log data from a website and send an automated alert message. My issue is that whenever I add the same alert message in the if statement the alert does not get executed.
I tried using the developer tools for f12 and debugged the code it seems the data does not enter the loop.
Please help me on this
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'https://learnwebcode.github.io/json-example/animals-1.json');
ourRequest.onload = function() {
var ourData = JSON.parse(ourRequest.responseText);
console.log(ourData);
if (ourData = "cat") {
alert(" take action");
};
ourRequest.send();
}
The alert should be generated as cat is found in the json file located at the link https://learnwebcode.github.io/json-example/animals-1.json

I'm posting my answer there instead of comment because it's too long.
Your if is not well formatted it should use the comparison operator == or === (which is "better"). Correct your if with the right operator because you used = which is the affectation operator.
By the way I checked the data and you should iterate over the object list and check the "species" attribute. Like this if(ourData.species == "cat").
Your code should look like :
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'https://learnwebcode.github.io/json-example/animals-1.json', true);
ourRequest.onload = function () {
// Request finished. Do processing here.
var ourData = JSON.parse(ourRequest.responseText);
console.log(ourData);
// loop over each "animal" element
ourData.forEach(function (element) {
if (element.species === "cat") {
alert(" take action");
};
});
};
ourRequest.send();
Hope it helps.

Related

why does xmlHttpRequest.Open only work when I input a string?

I'm trying to call a Restful service on my localhost. I am doing it this way because It's an asynchronous call. The appropriate Url plus the Uri-template to call my service is this:
"http://localhost:65016/Service1.svc/SN?lower=200&upper=300"
on the line where I try to open ( xhttp.open ), my client page only receives the proper data whenever I literally insert the url like this:
xhttp.open("GET", "http://localhost:65016/Service1.svc/SN?lower=200&upper=300" , true);
but I need the 200 and 300 numbers to be user input so I tried these two things:
I first tried grabbing the user input and simply concatenating it to the base URL in between the URi template like this:
<script>
function ServiceCall()
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function ()
{
if (xhttp.readyState == 4 && xhttp.status == 200) {
var ans = document.getElementById("secretNum");
ans.innerHTML = xhttp.responseText;
}
}
var base_uri = "http://localhost:65016/Service1.svc/";
// grab the lower number
var ln = document.getElementById("LN").firstChild;
var LN = ln.nodeValue;
// grab upper number
var un = document.getElementById("UN").firstChild;
var UN = un.nodeValue;
//complete
var URL = base_uri + "SN?lower=" + LN + "&upper=" + UN;
xhttp.open("GET", URL, true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send();
}
</script>
Doesn't work. So i tried looking at the documentation for the xmlHttpRequest.open, and I saw that the parameter had to be a URL. so I tried using the URL(string) function and using the output as a parameter and that didn't work either.
Any help please?
Thank you. I it helped to look at the network request. I was simply using the wrong syntax to obtain the value inside of the html input tag.
var ln = document.getElementById("LN").value;
returns the real value inside of html input tag given by the user input.
I'm answering my own question because this is a homework assignment.
(Not that I was cheating. Answering this is far from solving the homework)

How to get live row count as Jasper prints reports

I've developed a web application using jsp that has a list of contents which are placed in an ArrayList. I've tried various methods to implement this, tried the AsynchronousFillHandle , AJAX , Scriptlet. But I just can't get it done properly.
What I'm trying to achieve here is, while the JasperExportManager is filling records row by row, I want to display the number of rows that have been printed (say Live status of number of records printed) in the webpage.
For Example
267 out of 645588 records printed
5692 out of 645588 records printed
34677 out of 645588 records printed
After two days of unsuccessful attempts, I decided to use a shortcut, I wrote a scriptlet file, which will print the count of records being printed to a txt file in the same directory,
Scriptlet code:
public void afterDetailEval() throws JRScriptletException{
count = (Integer) this.getVariableValue("count");
BufferedWriter br = null;
try {
br = new BufferedWriter(new FileWriter(new File("C:/jasperreports-5.6.0/test/viewTasks/WebContent/value.txt")));
br.write(new String(""+count));
br.close();
Thread.sleep(200);
}catch (Exception e) {
e.printStackTrace();
}
}
and then used another ajax request to read data from the text file and display it in the browser, which was again unsuccessful as the ajax request returned only the previously stored value (i.e. Although the changes take place in the .txt file, AJAX request returned only the value which was there before the program execution took place. I guess it is because, the changes happen in the local directory and doesn't get reflected in the server). The AJAX code is as follows,
Webpage code:
<script>
function startPrinting() {
xhttp1 = new XMLHttpRequest();
xhttp1.onreadystatechange = function() {
if (this.readyState >= 1) {
document.getElementById('total')style.display = "";
setTimeout(function() { getStat(); }, 6000); //calls the function to start updating status
}
};
xhttp1.open("POST", "statusServlet", true);
xhttp1.send();
} //This function is to start the printing processes
function getStat(){
myvar=setInterval(function() {reval()}, 3000);
function reval(){
if(xhttp1.readyState>2){
xhttp1.abort();
}
var rawFile = new XMLHttpRequest();
var prev = "";
rawFile.open("GET","value.txt" , true);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
allText = rawFile.responseText;
if(prev===allText){
document.getElementById("status").innerHTML = allText;
return;
}
prev = allText;
document.getElementById("status").innerHTML = allText;
}
}
}
rawFile.send();
}
}
</script>
While using this code, If the file .txt is kept active inside the eclipse IDE, the values get reflected in the webpage, I really don't know why or how, but when the text file is kept active (I know it's weird), somehow the AJAX request returns the values correctly. Is there anyway to get this code to work without having to keep the .txt file active? Is there any other way to achieve the live row status of Jasper export other than writing and reading from a file?
NOTE: I'm using JAVA EE IDE from Eclipse with Tomcat 7.0 as server
Thanks in advance!

Data Cant Display in Rest API call by Javascript

I am using rest API in Javascript, Jquery to gepcoding. in this code i cant get data outside from xmlhttp.onreadystatechange = function() function
There is my Code to get data From Google API
var postdata = '{"cellTowers":[{"cellId": '+cid+',"locationAreaCode": '+lac+',"mobileCountryCode": '+mcc+',"mobileNetworkCode": '+mnc+'}]}'
xmlhttp = new XMLHttpRequest();
var url = "https://www.googleapis.com/geolocation/v1/geolocate?key=YOURKEY";
xmlhttp.open('POST',url,true);
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.send(postdata);
var lat;
var lng;
var data = '';
var json;
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
if (xmlhttp.responseText)
{
var data = xmlhttp.responseText;
var json = JSON.parse(data);
lat = json.location.lat;
lng = json.location.lng;
alert(lat+""+lng); //Working [1 operation]
}
}
};
alert(lat+""+lng); //Not Working [2 operation]
in this Code i am trying to get postdata out side xmlhttp.onreadystatechange = function() function and but i get null value. because when i run program i see first [2 operation] operation after then i see [1 operation]
have any problem in my code? or give me suggestion about that problem. or can any different way to use that API
Your code works just fine. Function runs asynchronous, when event happens. It is normal that 2 operation gets executed before the answer gets back from remote API. Please let me know what makes you unhappy. Code is fine, works as intended, gets the answer from remote API when available. The answer can only be received inside the function, then you should continue calling followup code, as for you app logic from there.

Setting server response data to a variable to work with

Hey guys I am using a executePostHttpRequest function that looks exactly like the code posted below. Currently when I run the function I get a server response with the appropriate data but I am not sure how I can work with the response data? how do I store it in to a variable to work with?
Javascript executePostHttpRequest
function executePostHttpRequest(url, toSend, async) {
console.log("====== POST request content ======");
console.log(toSend);
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
xmlhttp.open("POST", url, async);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.setRequestHeader("Content-length", toSend.length);
xmlhttp.send(toSend);
console.log("====== Sent POST request ======");
}
Here is what I am doing to execute it. Using Javascript
var searchCriteria = JSON.stringify({
displayName : search_term
});
console.log("Search: "+searchCriteria) //Search: {"name":"John, Doe"}
var response = executePostHttpRequest("/web/search", searchCriteria, true);
console.log(response) //undefined
So currently the console.log for response shows undefined. But if I take a look at the network tab on Chrome Dev Tools and look at the /web/search call I see a JSON string that came back that looks something like this.
[{"id":"1","email":"john.doe#dm.com","name":"John, Doe"}]
I'd like to be able to display the data from this response to a HTML page by doing something like this.
$("#id").html(response.id);
$("#name").html(response.name);
$("#email").html(response.email);
I tried taking another route and using Jquery POST instead by doing something like this.
var searchCriteria = JSON.stringify({
displayName : search_term
});
console.log("Search: "+searchCriteria) //Search: {"name":"John, Doe"}
$.post("/web/search", {
sendValue : searchCriteria
}, function(data) {
$.each(data, function(i, d) {
console.log(d.name);
});
}, 'json').error(function() {
alert("There was an error searching users! Please contact administrator.");
});
But for some reason when this runs I get the "There was an error" with no response from the server.
Could someone assist me with this? Thank you for taking your time to read it.
Your executePostHttpRequest function doesn't do anything with the data it's receiving. You would have to add an event listener to the XMLHttpRequest to get it:
function getPostData(url, toSend, async, method) {
// Create new request
var xhr = new XMLHttpRequest()
// Set parameters
xhr.open('POST', url, async)
// Add event listener
xhr.onreadystatechange = function () {
// Check if finished
if (xhr.readyState == 4 && xhr.status == 200) {
// Do something with data
method(xhr.responseText);
}
}
}
I've added the method parameter for you to add a function as parameter.
Here's an example of what you were trying to do:
function displayStuff(jsonString) {
// Parse JSON string
var data = JSON.parse(jsonString)
// Loop over data
for (var i = 0; i < data.length; i++) {
// Get element
var element = data[i]
// Do something with its attributes
console.log(element.id)
console.log(element.name)
}
}
getPostData('/web/search', searchCriteria, true, displayStuff)

JavaScript : Add time loading function for form

Im working on a native JavaScript/Ajax based sign-up form. The form uses an ajax function to send the data to a PHP engine which queries the database and what-not.
I'm wondering how to add loading function using JavaScript that allows me to show a loading animation while the PHP is being queried.
Ideally, I'd like to setup some sort of if statement checks how long the query takes and will only return the result after at least a minimum amount of time (like 3 seconds). Otherwise the loading animation will just flash on/off because the data-base query is too quick.
The JS looks like this:
function xmlhttpPost(strURL) {
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
updatepage(self.xmlHttpReq.responseText);
}
}
self.xmlHttpReq.send(getquerystring());
}
// send form data
function getquerystring() {
var form = document.getElementById('register-form');
var firstname = document.getElementById('firstname').value;
qstr = 'firstname=' + escape(firstname);
return qstr;
}
// return form data
function updatepage(str){
var result = document.getElementById("result");
result.innerHTML = str;
}
So what I want to do, is while updatepage(str) runs, the loading animation (which can just be gif) is run for a minimum of 3 seconds, then the result is displayed.
What I have at the moment is this:
function updatepage(str){
var result = document.getElementById("result");
// display gif;
setTimeout(function(){
// remove GIF
result.innerHTML = str;
},3000);
}
The issue I see with how I have it setup at the moment is that if DB query takes 5 seconds, the result will actually be displayed in 8 seconds.
Is this the best way of handling this? Or is there a more elegant solution? What's the standard way of doing this kind of thing?
You can do that all in your xmlhttpPost() function:
Set a variable with the current time at the start;
Add / show your image;
In the onreadystatechange compare the current time with the time set at the start, if the difference is 3 seconds or more, remove the image. Otherwise set a timeout for the remaining time and remove the image then.

Categories