How to display rest api using AJAX in Django? - javascript

I want to be able to use the REST API below and display data on a single HTML page.
This is the API (response) from a database connection function in my Django project.
URL: http://127.0.0.1:8000/api/v1/test/
API output:
{
"message": "Success !",
"server": "Connection established from ('PostgreSQL 12.7, compiled by Visual C++ build 1914, 64-bit',)"
}
I tried to display the data using AJAX. However, the data does not appear on the page. This is my attempt:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>API Calls Demo</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
</head>
<body>
<div class="container-fluid">
<h3>Test Output</h3>
<br></br>
<table class="table table-sm">
<tr>
<th>Output</th>
</tr>
<tbody id="divBody"></tbody>
</table>
</div>
</body>
<script>
$(document).ready(function () {
BindConnection();
});
function BindConnection(){
$.ajax({
type:"GET",
dataType: "JSON",
url: "http://127.0.0.1:8000/api/v1/test",
success: function(data){
console.log(data);
var str = "";
var totalLength = data.length;
for (let i=0; i < totalLength; i++){
str += "<tr>" +
"<td>" + data[i].server + "</td>"
"</tr>"
}
$("#divBody").append(str)
}
});
}
</script>
Note: The result can be displayed on the console and there is no error.
Sorry for my poor attempt, cause I am still new with Django, REST API, and Javascript (AJAX). I have tried several attempts but I cannot make it.
Could you please help me to answer this problem? Thank you!

i think the following line who causing the problem
var totalLength = data.length;
it seems the dictionary has no attribute length as the api response with dictionary so you need to deal with it as a dictionary not array
if you tried to add line
console.log(totalLength)
it will be undifiend value so no looping happening

Related

Accessing Functions From Other JS Files - DOJO

Im trying to call a function from another js file that is located in the same application directory as my main js script and html file. I receive an error claiming that the referenced function does not exist. I have referenced both of the scripts in the main html file in the proper order but cant for the life of me figure out why it cannot detect the function. I can only assume it has something to do with how dojo parses through the files and have experimented with both its dojo/domReady! and dojo/ready modules in hopes to force scripts to load. I feel like this should be much simpler than Im making it out to be. Any help would be greatly appreciated.
html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Asset View</title>
<meta charset="utf-8">
<link rel="stylesheet" href="http://js.arcgis.com/3.14/dijit/themes/claro/claro.css">
<link rel="stylesheet" href="http://js.arcgis.com/3.14/esri/css/esri.css">
<link rel="stylesheet" href= "styles/styles.css">
<script src="http://js.arcgis.com/3.14/"></script>
<script src="scripts/requests-js.js"></script>
<script src="scripts/layout-js.js"></script>
<script src="scripts/xmain-js.js"></script>
</head>
<body class = "claro">
</body>
</html>
requests-js.js
require(["dojo/dom","dojo/on","dojo/request","dojo/json","dojo/parser","dojo/ready"
], function(dom,on,request,JSON,parser,ready) {
ready(function() {
console.log("request start");
function sendRequest (url,assetCode,fromDate,toDate) {
console.log("Request innit");
request(url,{
method: "POST",
handleAs: "json",
headers: {"Content-Type": "application/json"},
data: JSON.stringify(
[
{
"AssetCodes": assetCode,
"FromGasDay": fromDate,
"ToGasDate": toDate
}
]
)
}).then(function(resp){
console.log(JSON.stringify(resp));
var naStorageJSON = resp;
});
}
console.log("request end");
});
});
main-js.js
require([
"dojo/dom","dojo/on","dojo/parser","dojo/json","dojo/request","dojo/ready"
], function(dom,on,parser,JSON,request,ready) {
ready(function() {
console.log("Main Start");
var url = "http://*********";
var assetCode = ["**"];
var toDate = "****";
var fromDate ="*****";
on(dom.byId("senecaLakeBtn"),"click", sendRequest(url,assetCode,toDate,fromDate));
console.log("Main End");
});
});
The issue is scope here. By declaring an empty array at the top of the js script (outside of its successive functions) the function can be accessible to other scripts in the application.
var app = [];
require(["dojo/dom","dojo/on","dojo/request","dojo/json","dojo/parser","dojo/ready"
], function(dom,on,request,JSON,parser,ready) {
ready(function(){
app.sendRequest = function sendRequest (url,assetCode,fromDate,toDate) {
...
...
}
}
it can them be called upon from other scripts by referencing
app.sendRequest(arg1,arg2,arg3);

Pull RSS feed using Jquery .get; cross domain issues?

I have been trying to get the example from How to parse an RSS feed using JavaScript? working. My HTMl/script is below. The get request isn't working. I'm not getting any errors, just nothing happening.
Is this because of cross-domain issues? Can anyone spot the issue? Ultimately, I want to pull treasury prices from government rss feeds such as:
http://www.federalreserve.gov/feeds/Data/H15_H15_RIFSGFSW04_N.B.XML
Am I taking the right approach?
<!DOCTYPE html>
<html>
<head>
<script src="jquery-1.11.1.min.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<script>
$(document).ready(function() {
alert('Jquery working fine');
$.get('https://stackoverflow.com/feeds/question/10943544', function (data) {
$(data).find("entry").each(function () { // or "item" or whatever suits your feed
var el = $(this);
console.log("------------------------");
console.log("title : " + el.find("title").text());
console.log("author : " + el.find("author").text());
console.log("description: " + el.find("description").text());
});
});
});
</script>
</head>
<body>
</body>

$.ajax passing multiple parameters

For some reason passing parameters using ajax is a real problem for me. I checked all of the questions regarding parameters and found the following as the correct way to pass parameters:
var username = $("#email_0000").val(),
password = $("#password_0000").val(),
func = 'emailexists',
bValid = true;
$.ajax({
type: "GET",
url: "php/ajax.php",
data: {
func:func,
email:username
},
success: function(data) {
alert(data);
}
});
The following is my php code:
<?php
$func = $_REQUEST['func'];
echo var_dump($_GET);
switch($func) {
case 'emailexists':
$email = $_REQUEST['email'];
echo 'Email address is='.$email;
break;
default:
return false;
break;
}
The alert is showing the following:
array(1){
["func"]=>
string(11)"emailexists"
}
Email address is=
I know I'm doing something wrong, but if someone has a clue I would appreciate it. Am I missing something in the "head" tag:
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="expires" content="1">
<!--Stylesheets-->
<link rel="stylesheet" href="css/jquery-ui.css">
<link rel="stylesheet" href="css/dhaStyle.css">
<!--JavaScripts -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>
<script src="js/vendor/jquery.simplemodal.1.4.4.min.js"></script>
<script src="js/DHA_forms.js"></script>
Thanks in advance for your help, regards, Rich

jQuery $.getJSON() not returning anything

I have a script that i'm using to experiment a bit with jQuery since i just started learning.
the script is supposed to read a .json file and display some data in a div.
function jQuerytest()
{
$.getJSON( "books/testbook/pageIndex.json", function(result) {
$.each(result, function(i, field) {
$("div").append("<p>" + field + "</p>");
});
});
}
here is the html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<link href="styles/main.css" rel="stylesheet" type="text/css">
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="scripts/book.js"></script>
<script>jQuerytest();</script>
</head>
<body>
<div></div>
<figure id=fig><img onClick="jQuerytest()" src="figures/test620x620.png"/>
</figure>
</body>
</html>
but it doens't display anything.
If your JSON File is valid (You can test here: http://jsonlint.com/)
Use the success and error callback to finally get information why it's not working.
function jQuerytest(){
$
.getJSON( "books/testbook/pageIndex.json")
.success(function(result) {
$.each(result, function(i, field) {
$("div")
.append("<p>" + field + "</p>");
});
})
.error(function(error){
console.log(error);
});
}

Simple way of displaying images from parse.com database using javascript

I was working on a very simple page which just pulls and displays images from a table in parse.com. I do not have much experience with javascript which might be evident from the code below.
I need the images to show up in a chronological order. With the current code, it works fine most of the times but is a little buggy.
There are 2 main problems:
1) Sometimes, randomly, one particular new image might not come on the top and instead show up somewhere in between.
2) This page works on Firefox and Chrome but NOT on IE.
Is there a better way to implement this or is there something that I should change? Any help would be appreciated.
Page source-
<!doctype html>
<head>
<meta charset="utf-8">
<title>My parse images</title>
<meta name="description" content="My Parse App">
<meta name="viewport" content="width=device-width">
<!-- <link rel="stylesheet" href="css/reset.css"> -->
<link rel="stylesheet" href="css/styles.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.parsecdn.com/js/parse-1.2.0.min.js"></script>
</head>
<body>
<div id="main">
<script type="text/javascript">
Parse.initialize("xxxxxxxxxxxxxxxxxx", "xxxxxxxxxxxxxxxx");
var config = {
parseAppId: 'xxxxxxxxxxxxxxxxxxx',
parseRestKey: 'xxxxxxxxxxxxxxxxxx',
streamName: 'parse-demo'
};
var getPhotos = function() {
var userImages = Parse.Object.extend("userImages");
var query = new Parse.Query(userImages);
query.find({
success: function(results) {
$('#photo-container').children().remove();
for(var i=results.length - 1; i>=0; i--){
var img = new Image();
img.src = results[i].get("image").url;
img.className = "photo";
document.body.appendChild( img );
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
};
function refresh (timeoutPeriod){
refresh = setTimeout(function(){window.location.reload(true);},timeoutPeriod);
}
$(document).ready(function() {
getPhotos();
// refresh(10000);
});
</script>
</body>
</html>
Internet Explorer blocks mixed content. Since Parse's JavaScript SDK requires SSL, you need to host your app using HTTPS as well in order to access it from IE.
Hey you made one mistake. it was not working for me. Then i found that it is url() not url.
The amendment is img.src = results[i].get("image").url();
<!doctype html>
<head>
<meta charset="utf-8">
<title>My parse images</title>
<meta name="description" content="My Parse App">
<meta name="viewport" content="width=device-width">
<!-- <link rel="stylesheet" href="css/reset.css"> -->
<link rel="stylesheet" href="css/styles.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.parsecdn.com/js/parse-1.2.0.min.js">
</script>
</head>
<body>
<div id="main">
<script type="text/javascript">
Parse.initialize("xxxxxxxxxxxxxxxxxx", "xxxxxxxxxxxxxxxx");
var config = {
parseAppId: 'xxxxxxxxxxxxxxxxxxx',
parseRestKey: 'xxxxxxxxxxxxxxxxxx',
streamName: 'parse-demo'
};
var getPhotos = function() {
var userImages = Parse.Object.extend("userImages");
var query = new Parse.Query(userImages);
query.find({
success: function(results) {
$('#photo-container').children().remove();
for(var i=results.length - 1; i>=0; i--){
var img = new Image();
img.src = results[i].get("image").url();
img.className = "photo";
document.body.appendChild( img );
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
};
function refresh (timeoutPeriod){
refresh = setTimeout(function(){window.location.reload(true);},timeoutPeriod);
}
$(document).ready(function() {
getPhotos();
// refresh(10000);
});

Categories

Resources