How display JSON output in html page using JQuery? - javascript

This is how I made API request using Python request :
mainurl = 'http://gw.api.alibaba.com/openapi/param2/2/portals.open/api.listPromotionProduct/'
api_key = '9420'
fields = '?fields=productId,productUrl,productTitle,salePrice,originalPrice,imageUrl'
payload = {
'keywords': "women",
'pageSize': "40",
'language': 'en',
'sort': 'volumeDown',
'isFreeShip': 'y',
'isFavorite': 'y',
'pageNo': "1"
}
urlx = mainurl + api_key + fields
r = requests.get(urlx, params=payload)
print(r.content)
when run it returns long JSON outputs :
{'result': {'commissionRate': '5.00%', 'originalPrice': 'US $1.21', ......}, 'currentPageNum': 0, 'errorCode': 20010000, 'totalPageNum': 0}
and this is how I try to make an API request using JQuery :
## index.html ##
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="orders">
</div>
<script src="js/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
<script src="js/main.js" type="text/javascript" charset="utf-8" async defer></script>
</body>
</html>
## main.js ##
$(function (){
var $orders = $('#orders');
$.ajax({
type: 'GET',
url: 'http://gw.api.alibaba.com/openapi/param2/2/portals.open/api.listPromotionProduct/9420?fields=productUrl,originalPrice,productTitle&keywords=women',
success: function(orders){
$.each(orders, function(i, order){
$orders.append('<li> products :' + order.totalResults + '</li>');
});
}
});
});
I got this result in my browser :
products :5291514
This is the JSON output :
{"result":{"totalResults":5275965,"products":[{"productTitle":"S-XL Plus Size Tunic Autumn ...}
How can display productTitle in my html page ?

If I understood the question well, this is what you wanted to show?
$.each(orders, function(i, order){
$orders.append('<li> products :' + order.products[0].productTitle + '</li>');
});

Related

How to display API data using Ajax?

I want to be able to use the API from the code below to display data in a formatted way such as this example.
Job Title: Agricultural and Related Trades
Percentage of Occupancies in Area: 15.41%
You can find my poor attempt to display the data below. I am very new to Ajax, jQuery, JavaScript, etc.
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$(function() {
$.ajax({
url: "http://api.lmiforall.org.uk/api/v1/census/jobs_breakdown?area=55.9895989531941,-3.796229726988194",
type: "get",
dataType: "json",
success: function(data) {
console.log(data[0].area);
outputString= data[0].description.percentage;
var paragraph = $("<p />", {
text: outputString
});
$("body").append(paragraph);
}
});
});
</script>
After successfully execute your GET request you will get your response at data variable now you can run a for loop to populate your expected outcome 'HTML' TEXT
than you can append it on your HTML body
I have used here JavaScript toFixed() Method keeping only two decimals
$(function() {
$.ajax({
url: "http://api.lmiforall.org.uk/api/v1/census/jobs_breakdown?area=55.9895989531941,-3.796229726988194",
method: "GET",
dataType: "json",
success: function(data) {
var str = "";
for(var i= 0; i < data.jobsBreakdown.length; i++){
str +='Job Title : '+data.jobsBreakdown[i].description+' and Related Trades <br> Percentage of Occupancies in Area : '+data.jobsBreakdown[i].percentage.toPrecision(2)+'% <br><br>';
}
$("body").html(str);
}
});
});
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
</head>
<body>
<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
Something like this is likely what you want:
<script>
$(function() {
$.ajax({
url: "http://api.lmiforall.org.uk/api/v1/census/jobs_breakdown?area=55.9895989531941,-3.796229726988194",
type: "get",
dataType: "json",
success: function(data) {
data.jobsBreakdown.forEach(function(job) {
var job_text = "Job Title: " + job.description;
var percentage_text = "Percentage of Occupancies in Area: " + job.percentage.toFixed(2) + "%"
$("body").append("<div style='margin-bottom: 10px;'><div>" + job_text + "</div><div>" + percentage_text + "</div></div>")
})
}
});
});
</script>
You can use string templates to create your paragraph content.
Use the <br /> HTML element to make a new line in the paraghraph.
let data = [{
area: 'Agricultural and Related Trades',
percentage: 15.41
}]
var paragraph = document.createElement('p');
paragraph.innerHTML = `Job Title: ${data[0].area}<br/>
Percentage of Occupancies in Area: ${data[0].percentage}%"`;
document.body.appendChild(paragraph);
You need to define a function to render a single item of description and percentage.
For parsing the percentage, you can use Number object
When you get the data back from Ajax, you need to loop on the items and pass each one of them to your render function you defined earlier (here I used forEach).
Generally, as rule of thumb, you have to split your code into functions each with single responsibility.
function renderItem(itemData) {
const title = $('<p/>').text('Job Title: ' + itemData.description);
const percentage = $('<p/>').text('Percentage of Occupancies in Area: '+ new Number(itemData.percentage).toFixed(2) + '%');
const item = $('<li/>').append(title, percentage);
$('#result').append(item);
}
$(function() {
$.ajax({
url: "http://api.lmiforall.org.uk/api/v1/census/jobs_breakdown?area=55.9895989531941,-3.796229726988194",
type: "get",
dataType: "json",
success: function(data) {
data.jobsBreakdown.forEach(renderItem);
}
});
});
Job Title: Agricultural and Related Trades
Percentage of Occupancies in Area: 15.41%
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="result"></ul>

Use Ajax response script into a Django HttpResponse

I am trying to pass the ajax response obtained from view to the template using HttpResponse but I don't have any idea, how to do that?
view.py
analyzer=SentimentIntensityAnalyzer()
def index(request):
return render(request, "gui/index.html")
#csrf_exempt
def output(request):
sentences = request.POST.get('name',None)
senti = analyzer.polarity_scores(sentences)
context_dict = {'sentiment': senti}
return render(request,"gui/index.html", context = context_dict
I want the senti to be printed after the score on the page but I am unable to obtain it.
template file
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
</head>
<body>
<form action = Post>
Enter Sentence:<input id = "name" type = "text" name = "EnterSentence" encoding = "utf-8"><br>
<input onclick = "testfunction()" type = "button" value = "Submit" >
</form>
<div><strong>Score is {{ sentiment }}</strong></div>
</body>
<script>
var testfunction = () => {
var test = document.getElementById("name").value
console.log(test)
$.ajax({
type: "POST",
dataType: "json",
url: 'output/',
data:{
csrfmiddlewaretoken: '{{ csrf_token }}',
'name': test
},
success: function(response) {
console.log("Succesful return firm ajax call");
},
error: function(result){
console.log("Failure");
}
});
}
</script>
</html>
In your view.py return render(request,"gui/index.html", context = context_dict code is missing ending paranthesis.
This is the correct order of jQuery ajax:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
Your success and error fields are inside of data.
<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({url: "demo_test.txt", success: function(result){
$("#div1").html(result);
}});
});
});
</script>
</head>
<body>
<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
<button>Get External Content</button>
</body>
This is an example of how to use .html method of ajax jquery. You can adjust for your own.
Additionally, use below code to loop through response:
$.each( data, function( key, val ) {
HTMLString += <li id='" + key + "'>" + val + "</li>
});
and this should be inside of the function of success and then pass HTMLString into .html method
To make it clearer how to $.each works:
var numbers = [1, 2, 3, 4, 5, 6];
$.each(numbers , function (index, value){
console.log(index + ':' + value);
});

try to get data fro json

I will try to get data from url json but nothing append
this is my code vere simple:
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("#driver").click(function(event){
$.getJSON('http://api.walmartlabs.com/v1/items/54732749?format=json&apiKey=fc5cku3vruymkhxhvtenm9bk', function(jd) {
$('#stage').html('<p> Name: ' + jd.item.name + '</p>');
$('#stage').append('<p>Age : ' + jd.item.itemId+ '</p>');
$('#stage').append('<p> Sex: ' + jd.item.salePrice+ '</p>');
});
});
});
</script>
</head>
<body>
<p>Click on the button to load result.html file:</p>
<div id = "stage" style = "background-color:#cc0;">
STAGE
</div>
<input type = "button" id = "driver" value = "Load Data" />
</body>
</html>
some can know why I don't see nothing?
Your data is not contained in item object you need to access it directly.
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("#driver").click(function(event){
$.getJSON('http://api.walmartlabs.com/v1/items/54732749?format=json&apiKey=fc5cku3vruymkhxhvtenm9bk', function(jd) {
$('#stage').html('<p> Name: ' + jd.name + '</p>');
$('#stage').append('<p>Age : ' + jd.itemId+ '</p>');
$('#stage').append('<p> Sex: ' + jd.salePrice+ '</p>');
});
});
});
</script>
The problem is with a cross domain Request.
You could make an ajax with dataType: "jsonp" to solve your issue.
Look here for better explanation.
note
as already pointed out, you should access to your response data without the .item, so jd.item.name become jd.name
$(document).ready(function() {
$("#driver").click(function(event) {
$.ajax({
url: 'http://api.walmartlabs.com/v1/items/54732749',
data: {
format: 'json',
apiKey: 'fc5cku3vruymkhxhvtenm9bk'
},
dataType: 'jsonp',
success: function(jd) {
console.log(jd);
$('#stage').html('<p> Name: ' + jd.name + '</p>');
$('#stage').append('<p>Age : ' + jd.itemId + '</p>');
$('#stage').append('<p> Sex: ' + jd.salePrice + '</p>');
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Click on the button to load result.html file:</p>
<div id="stage" style="background-color:#cc0;">
STAGE
</div>
<input type="button" id="driver" value="Load Data" />

Json.getproperty giving undefined

I have the following code where I need do draw a table using sap ui5 JSON Model. When I run the program I'm getting no data in the output table. I json.getProperty alert I'm getting alert output as undefined.
<!DOCTYPE html>
<html>
<head>
<!-- Load UI5, select gold reflection theme and the "commons" and "table" control libraries -->
<script id="sap-ui-bootstrap"
type="text/javascript"
src="https://sapui5.netweaver.ondemand.com/resources/sap-ui-core.js"
data-sap-ui-theme="sap_bluecrystal"
data-sap-ui-libs="sap.ui.commons,sap.ui.table"></script>
<script>
jQuery.ajax({
url: "/XMII/Illuminator?QueryTemplate=ZTest/QueryTemplates/table%20list&content-type=text/json",
dataType: "json",
success: function(data, textStatus, jqXHR) { // callback called when data is received
var jsonModel = new sap.ui.model.json.JSONModel();
jsonModel.loadData(data);
sap.ui.getCore().setModel(jsonModel);
var weatherTable = new sap.ui.table.Table({
title : "Current Weather Details",
visibleRowCount : 20
});
weatherTable.addColumn(new sap.ui.table.Column({
label : new sap.ui.commons.Label({text : "Tablename"}),
template : new sap.ui.commons.TextView().bindText("TableName")
}));
var oModel1 = new sap.ui.model.json.JSONModel();
var aData = jsonModel.getProperty("/Rowsets/Rowset/Row");
oModel1.setData({modelData : aData});
weatherTable.setModel(oModel1);
weatherTable.bindAggregation("rows","/modelData");
weatherTable.placeAt('content');
var dataLayout = new sap.ui.layout.HorizontalLayout({
id : "dataLayout", // sap.ui.core.ID
});
var Tablename = new sap.ui.commons.TextView({
id : "Tablename",
text : '{TableName}'
})
dataLayout.addContent(Tablename);
dataLayout.placeAt("content");
}
});
</script>
</head>
<body class='sapUiBody'>
<div id='content'></div>
</body>
</html>

ajax-loading doesn't stop or infinite loop?

I'm not sure if it is an ajax issue or if I have an infinite loop, I'm trying to get the values of one page to another.
My 1st page is a cakephp contoller:
$arr = ($this->Phone->find('all'));
$arr2 = json_encode($arr);
echo $arr2;
$_GET ['var1'] = $arr2;
die();
My 2nd page that gets and displays the output is this one
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="sizeof.js"></script>
<script type="text/javascript">
var results;
{
$.ajax({
type: 'GET',
url: 'http://localhost/restdemo/',
data: {
var1: results
},
success: function(data) {
console.log('success');
var output = JSON.parse(data);
for (x = 0; x <= output.length - 1; x++) {
var hello = (output[x]["Phone"]["name"]);
document.write('<table border="1" cellspacing="1" cellpadding="5">');
document.write('<tr>');
document.write('<td>' + hello + '</td>');
document.write('</tr>');
document.write('</table>');
}
}
});
}
</script>
</head>
<body>
</body>
</html>
I am getting my desired results however the page doesn't stop loading which makes me think that I have an error in my code to cause such an action. What causes this?and how can I fix it?. any feedback, comments and suggestion is highly appreciated.

Categories

Resources