json standards for structure of responses - javascript

I'm trying to decide on a standard for json responses for my applications going forwards.
So I'm thinking something along the lines of
Fake Json
{
Message:"hello, this is a reponse",
action: 0 or 1, or "Good" or "bad",
statusCode: 234,
}
I'm wondering if there is a good standard for this already, and also how I can keep my standards in sync between my front and back end?
Is there a clever way to do this?

I'm using a structure similar to this:
{ status: ("ok", "error" or "redirect"), message: "some message goes here.", fields: "field selectors goes here in case some highlighting is needed", url: "url to open or redirect to if needed" }
The status property is the key to tell what to do next;
The message can be used to show a popup message or an inline message, etc. Can also be a list of messages separated by a '|' character to split;
The field property is used to select (with jQuery or other JS library) the fields or other objects that need an action (think of this for field validation);
The url property is used to change the page, open a popup or post something back, depending on your needs.

Related

Why doesn't diffbot see the price here?

I'm using diffbot to scrape products. It gets things right on most sites, and if it doesn't the custom API usually allows me to easily tweak until correct. However there are a few cases that are baffling me.
I know diffbot doesn't execute javascript in the custom API preview window, but for the product endpoint, it should always execute it when a request is made to the API (e.g. from the diffbot client in a Python shell).
Foot asylum
For products on this website, e.g. https://www.footasylum.com/hugo-boss-three-pack-tshirt-103678/, the offerPrice field is empty. I can see the price is in a div#priceFrm, so I try to edit and add a custom selector on that field to this effect. However even when making a new API call from the Python shell, the response is 'offerPrice': ''.
This price is obviously being added by Javascript, but why can't diffbot deal with that? What can I do about it?
I can also see the price I want can be found in some JSON data inside a <script>. Normally I could just scrape it from there, with //script[contains(text(), "dataLayer")]/text() followed by a regex. However in another diffbot custom field I defined a selector script:contains(dataLayer) and even this is blank.
Any ideas on getting the price from this product with diffbot?
Nike
I'm also trying to get the price from https://www.nike.com/gb/t/flyknit-trainer-shoe-GBXjsV/AH8396-600
The first problem is the preview window of custom API just gives a 500 error weirdly.
Next I edit the offerPrice field with a custom selector of div[data-test=product-price], however this field doesn't hit anything - even when called from client in Python shell.
Footlocker
Finally on this site https://www.footlocker.co.uk/en/p/jordan-1-flight-2-men-shoes-6671?v=314100340604#!searchCategory=all diffbot cannot seem to get product image.
The images are loaded by "scene7", and with XPATH can be found with //div[#class="s7thumb"][#data-namespace="s7classic"]/#style and then parsing out the "background-url".
I tried to at least get the style attribute with diffbot using the selector div.s7thumb div[data-namespace=s7classic] and then adding the Attribute filter "style", but again nothing at all is returned.
In some cases, specific rendering of certain elements will be blocked either by Diffbot's renderer or by a target site's anti-block measures. That's why Diffbot has X-eval functionality which lets you add custom JavaScript into calls which will get executed on a target site, as if running from the console. In this case, something like the following helps:
function() {
start();
setTimeout(function() {
price = document.querySelector("[itemprop="
Offers "] [itemprop="
price "]");
currency = document.querySelector("[itemprop="
Offers "] [itemprop="
priceCurrency "]").getAttribute("content");
price.parentElement.setAttribute("style", "");
price.parentElement.innerHTML += '<h1 class="thePrice">' + price.innerText + " " + currency + '</h1>';
setTimeout(function() {
end();
}, 500);
}, 500);
}
This has been applied as a fix and the price returns now.

Altering the DOM with the Play! Framework

Hello again StackOverflow.
I've been tasked with modifying a website that runs on Scala's Play! framework and Twitter Bootstrap. I've hit a roadblock concerning altering the DOM. I need to accomplish the following:
(The page being talked about takes user input and passes the server a Form, which if
valid writes the mapped Data in the Form to a database.)
Have the user choose a category from a drop-down. This particular drop-down has nothing to do with the Form.
Based on their choice, query the database for all objects of a certain type that relate to the chosen category via a foreign key.
Alter the DOM (that is, show without reloading the page) to display those objects for the user to select them. Their selections are added to the Form.
Submit the Form, write to the database, etc.
Questions:
Is this a good way to go about what I'm trying to accomplish?
If so, is there a way to alter the DOM via Scala/Play HTML templates without reloading the page?
If that's not possible, what ilk of manually written Javascript is necessary?
Admissions:
I have very little experience with web development other than Play.
I have very little experience with Javascript.
Resources I've been looking at:
This SO post
Play docs on Javascript routing
Scala.js
Thank you!
For anyone who might come upon this in future, the short answer is Javascript.
Long answer:
To do any AJAX work, you'll need a method like the following in your top-level Controller to set up Javascript routing:
def javascriptRoutes = Action { implicit request =>
Ok(
Routes.javascriptRouter("jsRoutes")(
SomeOtherController.someMethod // Returns a JsValue!
)
).as("text/javascript")
}
Then in the HTML template (*.scala.html) which will contain some AJAXy Javascript:
<script type="text/javascript" src="#routes.ApplicationController.javascriptRoutes"></script>
And finally in your actual JS file (assuming you're using jQuery):
$("someSelector").click(function() {
// Notice that this matches the method name that exists in Scala!
// Make sure to pass `someMethod` what it needs.
var req = jsRoutes.controllers.SomeOtherController.someMethod(...)
$.ajax({
url: req.url,
type: req.type,
success: function(json) {
// DOM manipulation, etc., here.
},
error: function(xhr, status, errorThrown) {
console.log( "Error: " + errorThrown );
console.log( "Status: " + status );
console.dir( xhr );
}
}); // ajax
}); // handler

How effectively updatie complex large object in REST?

Suppose I have a complex object from html page which is mapped to this JSON structure:
{
id:"", //is not shown to user
title : "",
description: "",
summary: "",
// other too many fields
}
To update this record with "common" REST approach I should use:
- POST rest/record/{id}
With "common" approach entirely record object is marshalled to JSON object and is passed to REST service, then this entirely object is validated, passed to SQL query to data base and DB engine updates a record with all data. But what if user just update one symbol in the title?
In that case I should split this object into several:
{
id:"", //is not shown to user
{ recordId:"", title : "", } ,
{ recordId:"", description: "", } ,
{ recordId:"", summary: "", } ,
// other too many fields
}
How I should reorganize rest URLs? Like that:
- POST rest/record/{id}/title
- POST rest/record/{id}/description
- POST rest/record/{id}/summary
- others
Is this approach with URL good or bad (I mean both for javaScript from end and REST back end programming)? Is there any other approaches to handle this problem?
Instead of using POST, use PATCH and send only what's been changed:
PATCH rest/record/{id}
Data: { title: "new title" }
URLs such as rest/record/{id}/title, rest/record/{id}/summary, etc. aren't really RESTfull since they are not resources but properties of a resource.
See this past question for some exploration of options here (include PATCH).
Best practice for partial updates in a RESTful service
You have the following options:
use PATCH and send only the title
use PUT and send the whole data again
use PUT and use the property as a sub-resource with url: /resource/title
(POST is not idempotent, so you should not use that for update)

Send a user to a certain URL depending on his text field input

Basically I want the ff. done:
User inputs a text in my text field. If his text matches a text in my "list," he is sent to a certain URL once he hits the submit button.
I found a similar code on this site but his is just one specific text value. [ Get input text field from HTML into JavaScript and go to URL ]
I want mine to determine the user's text input from a list I provide. My list will have a lot of texts/urls and it will continue to grow, so manually inputting values into the script won't work for me.. I want to be able to edit the list (possibly in an admin panel or something?) instead of the js code.
Example:
input text: aaaa, go to URL1
input text: mmne, go to URL2
input text: lhfj, go to URL3
input text: tigf, go to URL4
input text: gred, go to URL5
Can anyone help me with this please? Thanks!
Hope this helps you
var Something =$("#TextBoxID").val();
if(Something == "aaaa")
{
window.location.href = 'URL1'; //Will take you to URL1
}
......
......
if you want to configure the list on an admin console you need to have some kind of server side technology like php (or node.js if you want to keep using javascript). You need to think of where this data will be stored. A possibility would be fetching the list of text/url pairs using ajax (e.g. with jQuery) and storing the data in some database or in your case also a plain text file probably would suffice. The functionality you are looking for is not possible with plain HTML and JavaScript on cient side.
Use a function like this, if you store your URLs on the client side (HTML/JS page):
function determineAndGoToURL(text) {
var url = "#";
switch(text) {
case "aaaa":
url="www.google.com";
break;
case "bbbb":
url = "www.bing.com";
break;
default:
url = "www.yahoo.com";
break;
}
window.location.href = "http://" + url;
}
If you have an updated list of URLs on the server side, get them from server-side to client side, and iterate over them with a for statement.
I'd suggest, you'd get them from the server as JSON, and use JSON.parse(text) to create an object out of them, and then iterate.

Why does my checkout button not work all of a sudden?

I have an app that I have been developing, that used to work up until some recent changes.
I ran a bundle update, and a bunch of gems updated. Since then (or around that time) my checkout process doesn't work and I can't figure out what is causing the issue.
I don't have any errors in my development.log file and no errors in my JS console.
You can check out the site here.
For login credentials, use: abc#test.com/testing123 (where the email is user, and the latter is pw).
Add that item to your cart, then go through the checkout process.
Enter some fake credentials, and use the credit card number: 4111111111111111 (verification number can be any 3 digit number, expiry any date after today).
Once you click checkout, you will see that the form isn't submitted.
For the life of me, I can't figure out why.
Would love to hear some thoughts on how I may either further troubleshoot this or tell me what is causing this.
Thanks.
P.S. This isn't a Heroku issue - I have this problem locally too. I am using the piggybak shopping cart gem, and the gem maintainers have not been able to replicate this error on their end. So I am further flummoxed :(
I followed your instructions and I got the error on clicking 'Create Order'.
sjsonp1369201390573({
"error": {
"message": "The 'exp_year' parameter should be an integer (instead, is undefined).",
"type": "card_error",
"param": "exp_year",
"code": "invalid_expiry_year"
}
}
, 402)
This is not coming in JS console. Instead your app is creating additional JS script file like:
https://api.stripe.com/v1/tokens?card[number]=undefined&card[cvc]=undefined&card[exp_month]=undefined&card[exp_year]=undefined&key=pk_u0E6vMzPGDJlYmyLqr83LCahMTL5e&callback=sjsonp1369201390573&_method=POST
Even though the error seems to be straight-forward, since I have not used AJAXQ or any other piggyback JS system, I guess you need to step through your program to catch this exception.
HTH.
It seems like the piggybak_stripe gem is looking for credit card details using class selectors that you don't have:
number: $('.card-number').val(),
cvc: $('.card-cvc').val(),
exp_month: $('.card-expiry-month').val(),
exp_year: $('.card-expiry-year').val()
so, after I added appropriate classes to the inputs (adding a card-number class to the piggybak_order[line_items_attributes][0][payment_attributes][number] input and so on), and using "4242424242424242" as the card number the form submits. Validation still fails on lots of stuff.
The JSON answer is:
"error": {
"message": "The 'exp_year' parameter should be an integer...",
"type": "card_error",
"param": "exp_year",
"code": "invalid_expiry_year"
}
Follow up the error message and add the appropriate class to html elements on page. As an example, in line 427 (html code) you have:
<select id="piggybak_order_line_items_attributes_0_payment_attributes_year" name="piggybak_order[line_items_attributes][0][payment_attributes][year]">
Add the follow selector "exp_year":
<select class="exp_year" id="piggybak_order_line_items_attributes_0_payment_attributes_year" name="piggybak_order[line_items_attributes][0][payment_attributes][year]" >
The elements with missing selectors are:
card[cvc]
card[exp_month]
card[exp_year]
card[number]
Add these 4 classes and be happy

Categories