Seeking refinements for a JQuery based script that interfaces with GraphQL (via the GraphCMS API)

I need some help figuring out how to do a couple of additional things with this JQuery-based script that interfaces with GraphQL (via the GraphCMS API):

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  <style>
  body { font-family:arial; }
  .title { font-weight:bold; padding-top:35px; }
  .id { border-bottom:1px solid #cccccc; padding-bottom:35px; }
  </style>
</head>
<body>
<div id="results"></div>
<script>
$.post({
  url: 'https://api.graphcms.com/simple/v1/cjgp9rqoj21iq0176nzwwecoc',   
  data: JSON.stringify({ "query": " { allBlogs { id date title description featuredImage { url }} } " }),
  contentType: 'application/json'
}).done(function(response) {
  var results = response.data ? response.data.allBlogs || [] : [];
  var container = $('#results');
  results.forEach(function(item) {  	
  	var id = $('<p>', {class: 'id'}).html(item.id);
  	var date = $('<p>', {class: 'title'}).html(item.date);
    var title = $('<p>', {class: 'title'}).html(item.title);
    var description = $('<div>', {class: 'description'}).html(item.description);
    var image = item.featuredImage.url;
    container.append(title, date, image, description, id);
  });
});
</script>
</body>
</html>

Open in new window


Here's the URL for this script for reference: https://egoselfaxis.com/graphql.html

Here are the refinements that I'm seeking:

1) I need to find a way to handle situations where the non-required featured image isn't available.  Currently, if I don't specify a featured image for a post, the script halts and throws a JavaScript error at the precise point where a featured image isn't found for that post.

2) In situations where there IS a featured image for a post, although I am able to return the a URL for the image, I can't seem to figure out how to concatenate things in such a way where I'm generating an img tag (ie: var featuredimage = '<img src="' . item.featuredImage.url . '">';)  Everything I try this, I get an error message. What is the correct way to do this?

3) How would I concatenate things so that I can generate a link to a specific post that passed the id value as a url parameter? (ie: <a href="?id=' . id . '">Read More</a>)

Thanks!
- Yvan
egoselfaxisAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Julian HansenCommented:
I am assuming the failure on the featured image is due to the fact that the featured image property is empty or does not exist, in which case you can use this to extract it if it is there or default it to something else if it is not (in this example - an empty string)
var image = item.featuredImage && item.featuredImage.url ? item.featuredImage.url : '';

Open in new window


2. To create an image dynamically
var img='';
if (image) {
  img = $('<img>',{src: image});
}
container.append(title, date, img, description, id);

Open in new window


3. To create a link
var url = '?id=' + id;
var link = $('<a>',{href: url}).text('Read More');

Open in new window

Updating your original code
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  <style>
  body { font-family:arial; }
  .title { font-weight:bold; padding-top:35px; }
  .id { border-bottom:1px solid #cccccc; padding-bottom:35px; }
  </style>
</head>
<body>
<div id="results"></div>
<script>
$.post({
  url: 'https://api.graphcms.com/simple/v1/cjgp9rqoj21iq0176nzwwecoc',   
  data: JSON.stringify({ "query": " { allBlogs { id date title description featuredImage { url }} } " }),
  contentType: 'application/json'
}).done(function(response) {
  var results = response.data ? response.data.allBlogs || [] : [];
  var container = $('#results');
  results.forEach(function(item) {  	
  	var id = $('<p>', {class: 'id'}).html(item.id);
  	var date = $('<p>', {class: 'title'}).html(item.date);
    var title = $('<p>', {class: 'title'}).html(item.title);
    var description = $('<div>', {class: 'description'}).html(item.description);
    // CHANGES FROM HERE
    var image = item.featuredImage && item.featuredImage.url ? item.featuredImage.url : '';
    var img = '';
    if (image) {
      var img = $('<img>',{src: image});
    }
    // Now append it 
    container.append(title, date, img, description, id);
    // TO HERE
  });
});
</script>
</body>
</html>

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
egoselfaxisAuthor Commented:
Thanks Julian!  That worked great.  I just made 1 slight change. I changed the post titles so that they linked  ...

var title = $('<a>',{href: url, class: 'title'}).text(item.title);

Open in new window


Just one last question .. How would I properly format the dates that are in this format (using jQuery / Javascript)?

2018-05-12T00:00:00.000Z

Ideally, I'd like to be able to do this without having to use an additional JS library, and I'd like to reformat the dates to something either like "May 12, 2018" or "5/12/208".

Thanks,
- Yvan
0
Julian HansenCommented:
You can try the toUTCString() which will give you this
Tue, 22 May 2018 14:49:49 GMT

Otherwise you can define your own formatting function on the date object
Date.prototype.myformat = function() {
  return (1900 + this.getYear()) + '-' + ('00' + (this.getMonth() + 1)).substr(-2) + '-' + ('00' + this.getDay()).substr(-2);
}
var d = new Date();
console.log(d.myformat());

Open in new window

If you want month's and day names you would need to include your own array's of names and use the getDay() and getMonth() functions to index that array.
0
The Ultimate Tool Kit for Technolgy Solution Provi

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy for valuable how-to assets including sample agreements, checklists, flowcharts, and more!

egoselfaxisAuthor Commented:
I'm trying this .. but I'm getting an error:

    Date.prototype.myformat = function() {
      return (1900 + this.getYear()) + '-' + ('00' + (this.getMonth() + 1)).substr(-2) + '-' + ('00' + this.getDay()).substr(-2);
    }    
    var d = item.date;
    var postdate = d.myformat();    
    var date = $('<p>', {class: 'title'}).html(postdate); 

Open in new window


TypeError: d.myformat is not a function
0
Julian HansenCommented:
Because item.date is not a Date object - you need to create a Date object from it first

var d = new Date(item.date);

Open in new window

0
egoselfaxisAuthor Commented:
Thanks Julian!
0
Julian HansenCommented:
You are welcome.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
GraphAPI

From novice to tech pro — start learning today.