How to read JSON file in angular js - javascript

I am working on a project where i have to read the product and display it on my HTML page
here is my Controller
app.controller('SecondCtrl', function($scope,srvShareCart ,srvShareData,srvAddtoCart,$http) {
$scope.product=[];
$scope.One=function(){
//alert($scope.ids);
$scope.ids= srvAddtoCart.getData();
for (var i=0; i<$scope.ids.length; i++){
$http.get("http://www.ilexsquare.com/JwelTech/wordpress/api.php?function=GetProduct&id="+$scope.ids[i])
.then(function (response) {
srvShareCart.addData(response.data);
});
$scope.cart = srvShareCart.getData();
console.log($scope.cart);
}
}
and here is My HTML page
<div ng-controller="SecondCtrl">
<ul> <li class=oxy-list__item ng-repeat="d in cart">{{d.title}}</li></ul></div>
here is a working API
this the Example API link
it's giving me an error in response.data which is coming as undefined.what is the issue in it ?
I am getting the output but it's not in a form of array.. how do i Add those products in array. i have tried $scope.carts.push($scope.products); but its not storing as an array

The response content type sent from the API is plain text instead of application/json

Try like this.
$http.get({
url: "http://www.ilexsquare.com/JwelTech/wordpress/api.php?function=GetProduct&id="+$scope.ids[i],
dataType: "json",
success: function (response) {
srvShareCart.addData(response.data);
},
error: function (msg) {
alert(msg.d);
}
});

Related

how to pass data to ajax for an express api call

I'm developing a website with express and ejs. I got into a trouble where i need to call an api via ajax. The problem is on a button onclick i'm passing two values to ajax data. but it gives error ,i tried a lot of ways and i'm messed up. i'm a newbie , find my code below.
const parsedData = JSON.parse(localStorage.getItem('myData'));
const container = document.getElementById('s1');
parsedData.data.rows.forEach((result, idx) => {
var a = result.master_id;
var b = result.session_name;
console.log(a,b,"a","b")
var userData = {"pid":a,"session" :b};
console.log(userData,"userData");
sessionStorage.setItem("user", JSON.stringify(userData));
console.log(userData,"data for api");
const card = document.createElement('div');
card.classList = 'card';
const content = `
<div class="row">
<div class="card-body" onclick="graphApi()">
</div>
</div>
`;
container.innerHTML += content;
});
function graphApi(){
var apiValue =JSON.parse( sessionStorage.getItem("user"));
console.log(apiValue, "value from card");
$.ajax({
type: "POST",
data: apiValue,
dataType:"json",
url: "http://localhost:5000/graphFromcsv",
success: function(data) {
console.log(data,"graph api");
}
error: function(err){
alert("graph api failed to load");
console.log(err);
},
});
i'm always getting this pid in api value undefined and 400 badrequest . but if i use raw data like,
{
"pid":"WE6",
"session":"W.csv"
}
instead of apiValue my ajax is success and i'm gettig the data. i'm using this data to plot a multiple line graph. Any help is appreciated.
You need to correct data key and their value(value must be string in case of json data) and also add contentType key like
$.ajax({
type: "POST",
data: sessionStorage.getItem("user") || '{}',
dataType: "json",
contentType: "application/json",
url: "http://localhost:5000/graphFromcsv",
success: function (data) {
console.log(data, "graph api");
},
error: function (err) {
alert("graph api failed to load");
console.log(err);
},
});
Note: In backend(ExpressJS), make sure you are using correct body-parser middleware like app.use(express.json());
Let assume your apiValue contain {"pid":"WE6", "session":"W.csv" } then body: { apiValue } will be equal to:
body: {
apiValue: {
"pid":"WE6",
"session":"W.csv"
}
}
But if you use the link to the object like body: apiValue (without brackets) js will build it like:
body: {
"pid":"WE6",
"session":"W.csv"
}

How to pass the id of the element user clicked on back to Flask using AJAX

I am trying to work on this website that shows a list of records, and when a user clicks on one of them, he will be navigated to another page that shows the details of the record. The logic behind it is, each 'li' tag has an "id" attribute that is unique, and I can use that id to call API and fetch the detailed info for that record. However, it seems that nothing was passed back to Flask...
HTML code:
<ul class="list-group list-group-flush">
{%for i in range(0,length)%}
<li class="list-group-item" id={{res.value[i].id}}>
<h4 class="itemName">Name:{{res.value[i].name}}</h4>
<p class="itemAssetType">{{res.value[i].assetTypes[0]}}</p>
<p class="itemQualifiedName">{{res.value[i].qualifiedName}}</p>
</li>
{%endfor%}
</ul>
JavaScript code:
$(function(){
$('li').click(function(){
var elementID = this.id
var datatosend = JSON.stringify({"guid":elementID})
$.ajax({
url: '/details',
data: datatosend,
type: 'POST',
success: function(response){
window.location.href = '/details'
console.log(response); //for stackoverflow: this shows None in console
},
error: function(ts) { alert(ts.responseText) }
});
});
});
Flask code:
#app.route('/details',methods=['POST','GET'])
def details():
print (request.json) #this gives: None
print (request.data) #this gives: b''
print (request.args.get("guid")) #this gives: None
return str(request.json)
Just wondering how am I supposed to pass that id into flask?? Why is it always empty???
I am kinda new to the front end, any help is greatly appreciated.
i think you remove this part
success: function(response){
window.location.href = '/details'
console.log(response);
}
because you get some data from server and then you go another page? but your data still stands in previous page!
You need to keep stay in current page and use your data like this:
success: function(response){
console.log(response);
}
$(function () {
$('li').click(function () {
var elementID = this.id;
console.log(this.id)//for stackoverflow: this shows the id as I expected
$.ajax({
url: '/details',
data: { guid: this.id },
type: 'POST',
success: function (response) {
console.log(response);
},
error: function (error) {
console.log('failed');
console.log(error);
console.log('element id =======>',elementID)//it is work now!!!
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li id="xyz">##click me##</li>
<script src="app.js"></script>

How to get nested JSON data values with a "data-" attribute?

I'm trying to create an elegant way of binding json data to html using data-attributes without having to write a bunch of custom code or using an external library/framework.
I can get this to work just fine without nested data and re-writing my function a little.
The problem is that it's reading my data-api-value as a string..so I'm trying to find the correct way to convert it. I'm open to other suggestions/ work-arounds though.
Here's the code in a (codepen)
Here's a dumb'd down version of the code
function getApiData(apiUrl, callback) {
apiData = $.ajax({
type: 'GET',
url: apiUrl,
dataType: 'json',
success: function(json) {
callback(json.data);
},
error: function(req, err) {
console.log(err);
},
contentType: "application/json; charset=utf-8"
});
}
function dataAPIrealtime() {
const url = 'https://someapi/v1/exchange/getinstrument/bitmex/XBTUSD';
getApiData(url, function(apidata){
$('[data-api]').each(function() {
let api = $(this).data("api");
let value = $(this).data("apiValue");
let data = apidata + value;
if (data || data != data) {
$(this).html(data);
}
});
});
}
/* Run Functions
*********************************/
$(document).ready(function() {
dataAPIrealtime();
setInterval(dataAPIrealtime, 1000); // Refresh data every 1 second
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span data-api="exchange/getinstrument" data-api-value="[instrument][symbol]"></span>

JSON Data Not showing from to view after retrieving using ajax

I retrieve Json data from controller using ajax. But I am trying to show the result in a specific div and tried so many things but couldn't figure it out what I am doing wrong. I can see in console that it is getting the json Data but it is just not showing in the specific div.
Here is the Json Data -
Object
postage_result:
costs:
cost:{item: "Parcel Post", cost: "15.80"}
delivery_time:"Delivered in 4 business days"
service:"Parcel Post"
total_cost:"15.80"
Ajax Code-
<script>
$.ajax({
url: '/ShoppingCart/GetFreight',
type: 'GET',
success: function (response) {
console.log(response);
weather = ko.mapping.fromJS(response); //populate the weather object
ko.applyBindings(weather);
$.each(response.postage_result, function (i, val) {
$("#cost").append(document.createTextNode(val.total_cost));
})
},
error: function (error) {
$(that).remove();
DisplayError(error.statusText);
}
});
</script>
View Code -
<td>Freight =<div id="cost"> </div></td>
Please suggest How should I do it to work .

Parse JSON data from API

I am new to working with Jquery JSON and API's(this being my first Stack question, so please bear with me). So I am trying to figure out a way in which Im hitting a API and it will return data(city name) in JSON which I have to display on my page in list form. But the cities should be updated and the page should display the city names dynamically.
Here is the fiddle link:
Fiddle File
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>TEST2</title>
</head>
<body>
<button>Submit</button>
<select id="list"></select>
</body>
</html>
<script type="text/javscript" src="jquery-3.1.0.js"></script>
<script type="text/javscript">
$.ajax({
type: 'GET',
url: 'API HERE',
data: { get_param: 'value' },
dataType: 'json',
success: function (data) {
$.each(data, function(index, element) {
$('body').append($('list', {
text: element.detail
}));
});
}
});
</script>
JSON FILE
[
{"id":3,"detail":"Mumbai, Maharashtra, India"},
{"id":10,"detail":"Pune,Maharashtra, India"},
{"id":166,"detail":"Bengaluru"}
]
Requesting for your help, thanks in advance for those who contributed
Provided you receive data from API you can do what you want.
//...
success: function (data) {
$.each(data, function(index, element) {
//$('body').append($('list', {//no comment
// text: element.detail
//}));
//add cities to select id="list"
$('<option/>') //create option
.val(element.id) //set its value
.text(element.detail) //set text
.appendTo('#list'); //and append to the list
});//each
}
this is not a JSON object, its an array, are you sure it comes back like this? try to log it then do one of the following:
if it comes as a string write this
$.ajax({
type: 'GET',
url: 'API HERE',
data: { get_param: 'value' },
dataType: 'json',
accepts: "application/json; charset=utf-8"
/* ... */
the accepts tells the server to send back json, hence you can get it as json. if it is still a string, write JSON.parse(data)
if it comes as an array like youve written, then there should be no problem, except that its an array not a json object. json should be an object not an array.
{results: [
{"id":3,"detail":"Mumbai, Maharashtra, India"},
{"id":10,"detail":"Pune,Maharashtra, India"},
{"id":166,"detail":"Bengaluru"}
]}
something like this will make it a json file.
if it comes like this, then you should write: data.results to access the array you need.
You don't need to parse. JSON is JavaScript Object Notation. you can just asign data to variable and use it in your code like
success: function(result) {
var data = result;
data.forEach(function(data){
$('body').append($('list', {
text: element.detail
}));
}
console.log(data);
//in console you can see tyour data
Object {type: "form-focus", element: "#run"}

Categories

Resources