Load JSON into Angular - javascript

I am new with Angular.js. I try to get json from my local url http://85.96.243.31/admin.productss/searchwithjson. JSON content is:
[
{
"fullsizeurl": "/uploads/incubout_denemeshop/1/product/3-kdd4eesv-erer-1-cent-1.png",
"productid": "3",
"price": "0.01",
"isactive": 1,
"brandid": "1",
"subcategoryid": "1",
"model": "1 Cent",
"isbundle": 0,
"subcategory": "Cat2",
"taxincluded": 0,
"brand": "erer",
"thumbnailsizeurl": "/uploads/incubout_denemeshop/1/product/3-kdd4eesv-erer-1-cent-1_thumb.png"
},
{
"productid": "1",
"isactive": 1,
"isbundle": 0,
"taxincluded": 0,
"thumbnailsizeurl": "/uploads/incubout_denemeshop/1/product/1-gu60axs2-erer-model-1_thumb.png",
"fullsizeurl": "/uploads/incubout_denemeshop/1/product/1-gu60axs2-erer-model-1.png",
"price": "15.00",
"brandid": "1",
"subcategoryid": "1",
"model": "model",
"subcategory": "Cat2",
"sku": "12",
"brand": "erer"
},
{
"fullsizeurl": "/uploads/incubout_denemeshop/1/product/4-sjy7xxyh-erer-qwert-1.png",
"productid": "4",
"price": "123.00",
"isactive": 1,
"brandid": "1",
"subcategoryid": "2",
"model": "qwert",
"isbundle": 0,
"subcategory": "Cat1",
"taxincluded": 0,
"brand": "erer",
"thumbnailsizeurl": "/uploads/incubout_denemeshop/1/product/4-sjy7xxyh-erer-qwert-1_thumb.png"
},
{
"productid": "2",
"price": "13.65",
"isactive": 1,
"brandid": "1",
"subcategoryid": "1",
"model": "yancı",
"isbundle": 0,
"subcategory": "Cat2",
"taxincluded": 0,
"brand": "erer"
}
]
Here is my code:
<!DOCTYPE html>
<html>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<body ng-app="MyApp">
<div ng-controller="PostsCtrl">
<ul ng-repeat="post in posts">
<li>{{post.fullsizeurl}}</li>
</ul>
</div>
<script>
var app = angular.module("MyApp", []);
app.controller("PostsCtrl", function($scope, $http) {
$http.get('http://85.96.243.31/admin.productss/searchwithjson').
success(function(data, status, headers, config) {
$scope.posts = data;
}).
error(function(data, status, headers, config) {
// log error
});
});
</script>
</body>
</html>
I couldn't get the fullsizeurls of products. What is the wrong with this code ?

I've tried your code and found out that the problem is in violating the rules of pulling data from different domain.
Are you sure you're pulling the JSON file from the same domain name where the html is being executed? - I've tried fetching your JSON file and storing with .html file and ran it perfectly fine from within the same folder.
If you fail to do, you'll be greeted with the following error in console log:
XMLHttpRequest cannot load http://localhost/searchwithjson. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
Or as others suggest enable CROS (Cross-origin resource sharing) to be able to load JSON from different locations.

Related

How to get content inside body and pre tag

In nodejs app I have a code inside body and inside pre tag, how can I parse a code from it?
So contents should look like:
{
"answer": {
"balance": 39926,
"bonus_balance": "0",
"user_id": "5",
"operator_id": "20770",
"currency": "RUB",
"user_nickname": "aaa",
"auth_token": "trahe",
"game_token": "6c73252bc257fe55299d1313cd612cf9",
"error_code": 0,
"error_description": "ok",
"timestamp": "\"1658674814\""
},
"api": "do-auth-user-ingame",
"success": true
}

Google Sheets not receiving json data properly from Woocommerce Webhook

I hope you guys are having a wonderful day.
I have set up a webhook in my woocommerce that sends JSON data to Google sheets. The webhook has been working great for months now, just today, I am having some trouble with it. I have tracked the issue to be in google sheets receiving the JSON data, but I don't know why this is happening.
Let me explain.
https://docs.google.com/spreadsheets/d/18G-yVDjYeccl6kznpZgSuRTysRMAu57pwY2oGf6-KWI/edit?usp=sharing
This is the google sheet, when it gets Woocommerce JSON data, it populates a new row.
The problem
Sometimes google sheets doesn't populate the row upon receiving a new order. The problem doesn't lie with woocommerce, because I have checked woocommerce with reqbin and the webhook fires with every order.
Furthermore, when I send requests from reqbin.com to my sheet, the sheet performs the operation successfully 5-6 out of 10 times. Other times it shows an error.
The Error
The error is due to google sheets not being able to parse JSON data, because the JSON data it receives 5 out of 10 times is not proper JSON data. Other 5 times, it is just as it should be. I have put a catch statement if the sheet is unable to parse JSON. Instead of appending new row with the parsed data, it appends the raw received data to the sheet.
It is clear now that there is some issue with google sheets handling that JSON data because when the same data is sent from reqbin.com to webhook.site, it is perfectly as it should be 10/10 times.
How to reproduce the issue
Open this google sheet. https://docs.google.com/spreadsheets/d/18G-yVDjYeccl6kznpZgSuRTysRMAu57pwY2oGf6-KWI/edit?usp=sharing
Open reqbin.com and webhook.site, and send the following JSON from reqbin.com to webhook.site 10 times to see if any kind of error occurs.
{ "id": 47222, "parent_id": 0, "status": "processing", "currency": "PKR", "version": "5.1.0","prices_include_tax": false, "date_created": "2021-06-10T01:23:46", "date_modified": "2021-06-10T01:23:46", "discount_total": "0", "discount_tax": "0", "shipping_total": "150", "shipping_tax": "0", "cart_tax": "0", "total": "1850", "total_tax": "0", "customer_id": 0, "order_key": "wc_order_7gIuR7px6MX9C", "billing": { "first_name": "Name", "last_name": "", "company": "", "address_1": "Address", "address_2": "", "city": "City", "state": "", "postcode": "", "country": "PK", "email": "email#email.com", "phone": "1234" }, "shipping": { "first_name": "Name", "last_name": "", "company": "", "address_1": "Address", "address_2": "", "city": "City", "state": "", "postcode": "", "country": "Country" }, "payment_method": "cod", "payment_method_title": "Cash on delivery", "transaction_id": "", "customer_ip_address": "8.8.8.8", "customer_user_agent": "Mozilla/5.0 (Linux; Android 11; M2102J20SG) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.88 Mobile Safari/537.36", "created_via": "checkout", "customer_note": "", "date_completed": null, "date_paid": null, "cart_hash": "64d834c72eecc8e32b9d83fd67d10d9c", "number": "47222", "meta_data": [ { "id": 869388, "key": "_shipping_calculator", "value": "" }, { "id": 869389, "key": "is_vat_exempt", "value": "no" }, { "id": 869391, "key": "_wfacp_report_data", "value": { "wfacp_total": "0.00" } }, { "id": 869392, "key": "_woofunnel_cid", "value": "4" }, { "id": 869393, "key": "_wfacp_post_id", "value": "24852" }, { "id": 869394, "key": "_wfacp_source", "value": "https://website.com/checkouts/checkout-page/" }, { "id": 869395, "key": "_wfacp_timezone", "value": "Asia/Karachi" }, { "id": 869396, "key": "order_comments", "value": "" }, { "id": 869412, "key": "_new_order_email_sent", "value": "true" }, { "id": 869424, "key": "_woofunnel_custid", "value": "4" }, { "id": 869425, "key": "_pys_purchase_event_fired", "value": "1" }, { "id": 869426, "key": "_wfob_stats_ids", "value": [] }, { "id": 869427, "key": "_wfocu_thankyou_visited", "value": "yes" } ], "line_items": [ { "id": 35114, "name": "MTECH Ultra Resilient Knife", "product_id": 11074, "variation_id": 0, "quantity": 1, "tax_class": "", "subtotal": "1700", "subtotal_tax": "0", "total": "1700", "total_tax": "0", "taxes": [], "meta_data": [], "sku": "", "price": 1700, "parent_name": null } ], "tax_lines": [], "shipping_lines": [ { "id": 35115, "method_title": "Fast Shipping (2-4 Days)", "method_id": "flat_rate", "instance_id": "1", "total": "150", "total_tax": "0", "taxes": [], "meta_data": [ { "id": 275053, "key": "Items", "value": "MTECH Ultra Resilient Knife × 1", "display_key": "Items", "display_value": "MTECH Ultra Resilient Knife × 1" } ] } ], "fee_lines": [], "coupon_lines": [], "refunds": [], "date_created_gmt": "2021-06-09T20:23:46", "date_modified_gmt":"2021-06-09T20:23:46", "date_completed_gmt": null, "date_paid_gmt": null, "currency_symbol": "₨","_links": { "self": [ { "href": "https://website.com/wp-json/wc/v3/orders/47222" } ],"collection": [ { "href": "https://website.com/wp-json/wc/v3/orders" } ] } }
Now send the same data to the following google sheet to see if it appends the row correctly each time.
https://script.google.com/macros/s/AKfycbxupm9bje86F4PQQkyys_LWtXs_kj279R0ipgnZ-cLd7aiEADf1AN_prhk28vOPW9JsRQ/exec
How do I solve the issue? Please let me know if you need any more information. Thanks.
Edit:
Instead of getting a full JSON body like mentioned above, the google sheets seems to be getting the following JSON.
{contextPath=, queryString=, parameter={}, postData=FileUpload, parameters={}, contentLength=3981.0}
I would like to know why the google sheets default parameter (e) contains this instead of a full JSON body sent to it.
Edit # 2
I would like to know why the google sheets default parameter (e) contains this instead of a full JSON body sent to it.
This is because (e) has a body which will always contain those parameters. The error is due to Google Sheets receiving an empty JSON body. I am still unable to understand why this happens. When I send the same JSON to API testing sites, they always receive full JSON body. Google sheets, in some cases, does not. Why is that?
I managed to solve the issue with some trial and error. For anyone facing the same issue in the future, here is what worked for me.
I was using e.postData.contents to get the JSON body but this seems to have stopped working, which was causing the JSON body to be empty. I tried e.postData.getDataAsString(); which seems to be working just fine and the issue has been resolved.

PayPal Checkout v2 SDK .NET problem with PayPalHttp.HttpResponse

I'm having a problem in the last part of a transaction setup flow:
the client side correctly calls my backend which makes a call to PayPal to create the order and receives a response with status code 200.
The error occurs when the http response is returned to the client, here we realize that the json that was created by the paypal class is incomplete! There are no closing parentheses that invalidate the json. "} ] }"
I asked the paypal team for assistance but it is not helping me. They continue to go around the problem, saying that the bees always return the complete json to me, but I know this too, because in debug mode the result gives me a link that correctly sends me back to the paypal payment.
This makes me understand that in reality the flow that I created is complete but the PayPalHttp.HttpResponse class creates an incorrect body.
I am attaching the code.
Public Shared Async Function CreateOrder(ByVal Optional debug As Boolean = False) As Task(Of PayPalHttp.HttpResponse)
Dim result As New Order
Dim request = New OrdersCreateRequest()
request.Prefer("return=representation")
Dim newRequest As New OrderActionRequest
request.RequestBody(BuildRequestBody(dicNameValue))
Dim response = Await PayPalClient.client().Execute(request)
If debug Then
result = response.Result(Of Order)()
Console.WriteLine("Status: {0}", result.Status)
Console.WriteLine("Order Id: {0}", result.Id)
Console.WriteLine("Links:")
For Each link As LinkDescription In result.Links
Console.WriteLine(vbTab & "{0}: {1}" & vbTab & "Call Type: {2}", link.Rel, link.Href, link.Method)
Next
/*--- HERE THE PROBLEM ----*/
Dim json As String = PayPalClient.ObjectToJSONString(result)
Console.WriteLine("Response JSON: {0}", json)
/*----------*/
Dim amount As AmountWithBreakdown = result.PurchaseUnits(0).AmountWithBreakdown
Console.WriteLine("Total Amount: {0} {1}", amount.CurrencyCode, amount.Value)
End If
Return response
End Function
This is the incomplete json :
{
"create_time": "2020-03-18T14:28:56Z",
"id": "2LW612087K897524T",
"intent": "CAPTURE",
"links": [
{
"href": "https:\/\/api.sandbox.paypal.com\/v2\/checkout\/orders\/2LW612087K897524T",
"method": "GET",
"rel": "self"
},
{
"href": "https:\/\/www.sandbox.paypal.com\/checkoutnow?token=2LW612087K897524T",
"method": "GET",
"rel": "approve"
},
{
"href": "https:\/\/api.sandbox.paypal.com\/v2\/checkout\/orders\/2LW612087K897524T",
"method": "PATCH",
"rel": "update"
},
{
"href": "https:\/\/api.sandbox.paypal.com\/v2\/checkout\/orders\/2LW612087K897524T\/capture",
"method": "POST",
"rel": "capture"
}
],
"purchase_units": [
{
"amount": {
"breakdown": {
"handling": {
"currency_code": "USD",
"value": "10.00"
},
"item_total": {
"currency_code": "USD",
"value": "180.00"
},
"shipping": {
"currency_code": "USD",
"value": "30.00"
},
"shipping_discount": {
"currency_code": "USD",
"value": "10.00"
},
"tax_total": {
"currency_code": "USD",
"value": "20.00"
}
},
"currency_code": "USD",
"value": "230.00"
},
"custom_id": "CUST-HighFashions",
"description": "Sporting Goods",
"items": [
{
"category": "PHYSICAL_GOODS",
"description": "Green XL",
"name": "T-shirt",
"quantity": "1",
"sku": "sku01",
"tax": {
"currency_code": "USD",
"value": "10.00"
},
"unit_amount": {
"currency_code": "USD",
"value": "90.00"
}
},
{
"category": "PHYSICAL_GOODS",
"description": "Running, Size 10.5",
"name": "Shoes",
"quantity": "2",
"sku": "sku02",
"tax": {
"currency_code": "USD",
"value": "5.00"
},
"unit_amount": {
"currency_code": "USD",
"value": "45.00"
}
}
],
"payee": {
"email_address": "sb-bzfcs1123474#business.example.com",
"merchant_id": "55J4WA53G7WRL"
},
"reference_id": "PUHF",
"shipping": {
"address": {
"address_line_1": "123 Townsend St",
"address_line_2": "Floor 6",
"admin_area_1": "CA",
"admin_area_2": "San Francisco",
"country_code": "US",
"postal_code": "94107"
},
"name": {
"full_name": "John Doe"
}
},
PS: the project is in VB.NET 4.6.1 (web forms)
Dim response = Await PayPalClient.client().Execute(request)
What is response here?
And can you debug the value further in, within PayPalClient.client().Execute(request)
PayPal sends JSON over the network. So it seems you are receiving JSON, which is converted into an Object, and then you are calling a function on that object that gives back JSON.
I am not sure why that particular function is giving bad JSON at the moment you call it, but I do know that the original JSON from PayPal is probably complete.

Script error when webbrowser loading html page

I'm trying to load local html page using webbrowser tool in Winforms but I got script error message and my page won't load, when I open that page using any web browser it opens with no problem at all! I tried some solutions as editing registry but no fix.
my html page has jscript code and this is the code in my page:
<html>
<head>
<script type="text/javascript"src="http://static.fusioncharts.com/code/latest/fusioncharts.js"></script>
<script type="text/javascript"src="http://static.fusioncharts.com/code/latest/themes/fusioncharts.theme.fint.js?cacheBust=56"></script>
<script type="text/javascript">
FusionCharts.ready(function () {
var csatGauge = new FusionCharts({
"type": "angulargauge",
"renderAt": "chart-container",
"width": "400",
"height": "250",
"dataFormat": "json",
"dataSource": {
"chart": {
"caption": "Customer Satisfaction Score",
"subcaption": "Last week",
"lowerLimit": "0",
"upperLimit": "100",
"theme": "fint"
},
"colorRange": {
"color": [
{
"minValue": "0",
"maxValue": "50",
"code": "#e44a00"
},
{
"minValue": "50",
"maxValue": "75",
"code": "#f8bd19"
},
{
"minValue": "75",
"maxValue": "100",
"code": "#6baa01"
}
]
},
"dials": {
"dial": [
{
"value": "67"
}
]
}
}
});
csatGauge.render();
});
</script>
</head>
<body>
<div id="chart-container">An angular guage will load here!</div>
</body>
</html>
I've managed to solve it by adding this code:
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
</head>
I'm still not sure if this is only thing needed or it worked with the change of the registry: solution

calling data from nested .json using ajax

I'm new one to work with JSON and getting stuck that how to call JSON data from nested .json file. please check the code below ...
JSON FORMAT
{
"hotels": {
"category": [{
"name": "Exotic and Luxurious",
"products": [{
"name": "Sofitel L'Imperial Resort and Spa",
"budget": "Luxery",
"location": "flic en flac",
"price": "71500"
}, {
"name": "Shanti Maurice a Nira Resort",
"budget": "Luxery",
"location": "Chemin Grenier",
"price": "88500"
}]
},{
"name": "In the Tourist Hub",
"products": [{
"name": "Sofitel L'Imperial Resort and Spa",
"budget": "Luxery",
"location": "flic en flac",
"price": "71500"
}, {
"name": "Shanti Maurice a Nira Resort",
"budget": "Luxery",
"location": "Chemin Grenier",
"price": "88500"
}]
},{
"name": "Close to the Beach and Market",
"products": [{
"name": "Sofitel L'Imperial Resort and Spa",
"budget": "Luxery",
"location": "flic en flac",
"price": "71500"
}, {
"name": "Shanti Maurice a Nira Resort",
"budget": "Luxery",
"location": "Chemin Grenier",
"price": "88500"
}]
},{
"name": "Private and Peaceful",
"products": [{
"name": "Sofitel L'Imperial Resort and Spa",
"budget": "Luxery",
"location": "flic en flac",
"price": "71500"
}, {
"name": "Shanti Maurice a Nira Resort",
"budget": "Luxery",
"location": "Chemin Grenier",
"price": "88500"
}]
}]
}
}
AJAX CODE
jQuery(document).ready(function() {
jQuery.ajax({
url: 'hotels.json',
type: 'GET',
dataType: 'json',
success : function(data){
/*jQuery(data).each(function(index, value){
console.log(value.hotels.name);
})*/
//console.log(data.hotels.category[1].name);
//alert(JSON.stringify(data));
var i = 0;
jQuery(data.hotels.category).each(function(){
jQuery('.theme ul').append('<li data-role="'+data.hotels.category[i].name+'">'+data.hotels.category[i].name+'</li>');
i++;
})
jQuery(data.hotels.category).each(function(){
jQuery('.budget ul').append('<li data-role="'+data.hotels.category[i].name.products[0].name+'">'+data.hotels.category[i].name.products[0].name+'</li>');
i++;
})
}
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
});
HTML
<div class="theme">
<p>Hotel experience theme</p>
<ul>
</ul>
</div>
<div class="budget">
<p>Budget</p>
<ul>
</ul>
</div>
I want to call name data from products which is defined in category in <li> of budget div
Change:
jQuery(data.hotels.category).each(function() {...});
to:
jQuery.each(data.hotels.category, function() {...});
The first form is for looping over DOM elements in a selection, the second form is for looping over Javascript arrays and objects.
And within the function, you can use this to refer to the element, you don't need to use data.hotels.category[i].
But if you continue to use data.hotels.category[i], you need to set i back to 0 before the second loop. Or you could just do everything in one loop. And .each() passes the array index to the function, so you don't need your own variable.
Finally, products is not a sub-property of the name property.
The final result of fixing and simplifying this should be:
jQuery.each(data.hotels.category, function(){
jQuery('.theme ul').append('<li data-role="'+this.name+'">'+this.name+'</li>');
jQuery('.budget ul').append('<li data-role="'+this.products[0].name+'">'+this.products[0].name+'</li>');
});
The products belong to category directly so you don't have to pass by name to get it, you should go directly to it, so try to replace :
data.hotels.category[i].name.products[0].name
BY :
data.hotels.category[i].products[0].name
Hope this helps.

Categories