Why won't Javascript code run? - javascript

I'm new new to javascript. This is my first real attempt to do something besides running hello world. I'm attempting to retrieve information from a url and display it. I checked the url and it returns json. The "Hello World" code runs but as soon as I add the code that retrieves the json inside the script tags nothing happens. I'm getting no syntax errors.
<!DOCTYPE HTML>
<html>
<body>
<p>Header...</p>
<script>
document.write("Hello World");
var getJSON = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open("get", url, true);
xhr.responseType = "json";
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
callback(null, xhr.response);
} else {
callback(status);
}
};
xhr.send();
};
getJSON("http://api.tvmaze.com/schedule?country=US&date=2016-08-31",
function(err, data) {
if (err != null) {
alert("Something went wrong: " + err);
} else {
alert("Your query count: " + data.query.count);
}
});
</script>
<p>...Footer</p>
</body>
</html>

I checked your html and js and one quick look into the console showed me that the problem was this line
alert("Your query count: " + data.query.count);
change the "data.query.count" to "data.length"
alert("Your query count: " + data.length);
Debuging code is one of the easiest ways to find errors.
You can hit F12 in basicly any browser to inspect the things behind the scene

If you examine the console on your browser you will see that your code is throwing the error of Uncaught TypeError: Cannot read property 'count' of undefined.
This is because you are attempting to access the length of the response array by means of data.query.count, when in fact it should be data.length.
So the working code should look like;
<!DOCTYPE HTML>
<html>
<body>
<p>Header...</p>
<script>
document.write("Hello World");
var getJSON = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open("get", url, true);
xhr.responseType = "json";
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
callback(null, xhr.response);
} else {
callback(status);
}
};
xhr.send();
};
getJSON("http://api.tvmaze.com/schedule?country=US&date=2016-08-31",
function(err, data) {
if (err != null) {
alert("Something went wrong: " + err);
} else {
alert("Your query count: " + data.length);
}
});
</script>
<p>...Footer</p>
</body>
</html>

Related

Blogger feed posts showing CORS Error on different site

With reference to this answer of Google, I tried to use the json version of my feeds by using the URL: https://[blog address].blogspot.com/feeds/posts/default?alt=json. My blog is set to public mode, but then also it is throwing CORS policy. And this is the code I used:
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
var getJSON = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status === 200) {
callback(null, xhr.response);
} else {
callback(status, xhr.response);
}
};
xhr.send();
};
getJSON('https://[blog].blogspot.com/feeds/posts/default?alt=json',
function(err, data) {
if (err !== null) {
alert('Something went wrong: ' + err);
} else {
alert('Your query count: ' + data.query.count);
}
});
</script>
Try alt=json-in-script instead:
<script type="text/javascript">
function myFunction({feed}) {
alert('Your query count: ' + feed.entry.length);
}
</script>
<script type="text/javascript" src="https://blog.blogspot.com/feeds/posts/default?alt=json-in-script&callback=myFunction"></script>

Var not found in IF statement, but is set correctly.

I have a var that's value is set, with an if statement to check which value, then deploy depending on the statement.
function Sort() {
var Response = document.getElementById("ResponseDiv").innerHTML;
if (Response == "Verified.") {
alert("Verified");
}
else if (document.getElementById("ResponseDiv").innerText == "Not verified.") {
alert("Not verified");
}
else {
alert("Else: " + Response);
}
}
My code isn't landing on "Verified" or "Not Verified" instead it lands on the else statement. I went through several times thinking I had a typo but isn't the same.
The ResponseDiv is filled by this (which works fine):
function Check() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://' + Http + '/ID_' + ID + '.html', false);
xhr.setRequestHeader("Content-Type", "text/xml");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
document.getElementById("ResponseDiv").innerHTML = xhr.responseText;
//setTimeout(Sort, 200);
Sort();
}
}
};
xhr.send(null);
}
My div gets the correct data, and the alert box in the else even gives me what I'm looking for, but lands on the else.
Debugger shows Response as coming back as "Verified.\n", but in no other way. However statement works fine when coded as if(Response == "Verified.\n").

JavaScript Not Returning Data But No Error Either

I am calling a php file that queries my database and returns a result. I have verified that the php file accurately returns the data as needed, but my calling page is not updated from the JavaScript.
What do I need to alter in my syntax below so that the returned value is returned on page?
<script type="text/javascript">
function boostion()
{
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("GET", "QueryDB.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = display_data;
function display_data() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
document.getElementById("data").innerHTML = xhr.responseText;
} else {
alert('There was a problem with the request.');
}
}
}
}
</script>
EDIT
I have also opened Developer Options in Chrome and checked the Console and there are no errors or issues displayed, everything is a success!
Edit 2
I tried to use the JQuery approach below and used this syntax - but I get the error
Uncaught TypeError: $(...).load is not a function
Syntax:
<script src="https://code.jquery.com/jquery-3.1.1.slim.js"
integrity="sha256-5i/mQ300M779N2OVDrl16lbohwXNUdzL/R2aVUXyXWA="
crossorigin="anonymous" type="text/javascript"></script>
<script type="text/javascript">
$(window).load(function(){
$.get("QueryDB.php", function(data, status){
document.getElementById("data").innerHTML = data;
});
});
</script>
Edit 3
This is my php syntax that runs the sql syntax and echo result that I want to have returned from the javascript
<?php
$option = array();
$option['driver'] = 'mssql';
$option['host'] = 'host';
$option['user'] = 'user';
$option['password'] = 'password';
$option['database'] = 'database';
$option['prefix'] = '';
$db = JDatabase::getInstance( $option );
$result = $db->getQuery(true);
$result->select($db->quoteName(array('trackandfieldresults')));
$result->from($db->quoteName('[TrackData]'));
$db->setQuery($result);
$row = $db->loadRowList();
echo $row['0']
?>
Use xhr.send();
If it is a GET request, you have to apply the query string in in xhr.open and you dont have to set Content-type:application/x-www-form-urlencoded
first, the scripts should be inside the HTML before the ending body tag. then you open another file and write your code in it. JQUERY does not have script tag. Sp you are creating an external javascript file for the script. No script tag needed. Now use this format.
$(window).on('load', function(e){
e.preventDefault();
var dat = //the content you are trying to load
$.get('middleware.php', dat, function(data){
$('#selector').html(data)
});
})
I have a faster approach using JQuery.
$(window).load(function(){
$.get("QueryDB.php", function(data, status){
//Do whatever you want here
});
});
This should do the Job. Your approach is old and kind of complicated to debug
Try this
function boostion(){
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("GET", "QueryDB.php", true);
xhr.send();
xhr.onreadystatechange = function(){
console.log(xhr);
if (xhr.readyState == 4 && xhr.status==200) {
document.getElementById("data").innerHTML = xhr.responseText;
}
}
}
<div id="data"></div>
<button onclick="boostion();">Load</button>

request.responseText receives correct data but JavaScript cannot understand it

I am new to AJAX and presently learning it from Head First AJAX. The problem I am facing is really weird. I developed a simple program that creates a request through JavaScript and then shows the output.
main.js
window.onload = initPage;
function initPage() {
request = createRequest();
if(request == null) {
alert("request could not be created");
}
else {
var url = "requestMe.php";
request.onreadystatechange = showResult;
request.open("GET", url, true);
request.send(null);
}
}
function showResult() {
if(request.readyState == 4) {
if(request.status == 200) {
if(request.responseText == "okay") {
alert("A successful request was returned");
}
else {
alert("ALERT : " + request.responseText);
}
}
else {
alert("Request status received was not correct");
}
}
}
//--function to create request objects--
function createRequest(){
try{
request = new XMLHttpRequest();
}
catch(tryMS){
try{
request = new ActiveXObject("Msxm12.XMLHTTP");
}
catch(otherMS){
try{
request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(failed){
request = null;
}
}
}
return request;
}
Now, here is the php script.
requestMe.php
<?php
echo 'okay';
?>
This code should give the alert A successful request was returned
But instead it gives the result ALERT : okay
The weird thing is this same code was working yesterday for me when I tried it and now it is giving me this result. I tried to create similar programs and they all are showing me this kind of weird behavior. The responseText received is correct because it appends okay after ALERT :. What wrong am I doing here in the code? Why is it going to the else part when the responseText received is correct?
Any Help? Thanks in advance.
I personally would do it using jQuery's Ajax Function in the following way:
document.addEventListener("DOMContentLoaded", function()
{
$.ajax({
"url": "requestMe.php"
}).done(function(data)
{
if(data == "okay")
{
alert("A successful request was returned");
} else
{
alert("ALERT : " + data);
}
}).fail(function()
{
alert("Connection Failed");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I haven't tested this Script, but it should in theory work out well.
Do one thing add exit; after echo 'okay';
Issue in your code is after ?> there is extra space available you can fix it either by removing ?> or removing extra space after ?>.
I hope it will fix your issue.

Why is this JSON query not working?

I am so confused at the moment, as to why this will not work.
<div id="result" style="color:red"></div>
and
var getJSON = function(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
resolve(xhr.response);
} else {
reject(status);
}
};
xhr.send();
});
};
getJSON('https://www.eobot.com/api.aspx?coin=DOGE&json=true').then(function(data) {
alert('Your Json result is: ' + data.DOGE); //you can comment this, i used it to debug
result.innerText = data.DOGE; //display the result in an HTML element
}, function(status) { //error detection....
alert('Something went wrong.');
});
It's exactly the same as: http://jsfiddle.net/RamiSarieddine/HE2nY/1/ but yet that works..
Edit: For the sake of clarity, the script is supposed to take the content at the url (within the DOGE element) and display it within
<div id="result" style="color:red"></div>
I tested it and i get below error, Which means when you try to get the json from https://www.eobot.com/api.aspx?coin=DOGE&json=true , its blocked from receiving the data due to cross browser rules.
No 'Access-Control-Allow-Origin' header
How to fix it ,
You must own https://www.eobot.com and run this script on www.eobot.com , Else you cant get the json due to cross domain policy.Ask the owner to whitelist your domain in his allow-origin header.

Categories

Resources