In this article, I'll be providing a detailed explanation of a recent change I added to a social media app, which leverages AI to plot graphs using JavaScript. This process involves generating JavaScript code and injecting it into HTML to render the graph.
To integrate the graph-plotting functionality, I re-used an existing API endpoint initially designed for checking grammar. The limited space in the app's post area necessitated this approach. Therefore, I included logic to distinguish between grammar checks and graph plotting based on the input content.
Here's a step-by-step breakdown of how I achieved this:
Extending Grammar API:
API Response Processing:
Injecting JavaScript Code:
setTimeout
. This delay allows the DOM to fully load the canvas element before the JavaScript code runs.Error Handling and Debugging:
Below is a sample walk-through of the implementation process:
if (caption.startsWith('graph:') || caption.startsWith('graph2:')) (
const rawResponse = callAPIWithCaption(caption);
const jsCode = processRawResponse(rawResponse);
setTimeout(() => injectJavaScriptCode(jsCode), 1000);
)
callAPIWithCaption
sends the caption to the watsonx API and retrieves the raw response.processRawResponse
converts the raw response into executable JavaScript code.function processRawResponse(response) (
const splitResponse = response.split('some_character');
const jsCodeSegment = splitResponse.find(segment => segment.startsWith('JavaScript') && segment.length > 5);
return jsCodeSegment.replace('JavaScript', '');
)
function injectJavaScriptCode(jsCode) (
const canvas = document.getElementById('canvas_id');
setTimeout(() => {
new Function(jsCode)();
), 1000);
}
This brings us to the end of the explanation. The final code fixes are committed to the project repository.
1. What triggered the need to reuse the grammar API for graph plotting?
2. How do you identify that the input request is for graph plotting?
3. How do you handle the API response on the frontend?
4. What issue was faced during the initial testing?
5. What changes were made to fix the error in code processing?
6. Why was a setTimeout
required in the code?
setTimeout
ensures the canvas element is fully loaded in the DOM before executing the JavaScript code.In addition to the incredible tools mentioned above, for those looking to elevate their video creation process even further, Topview.ai stands out as a revolutionary online AI video editor.
TopView.ai provides two powerful tools to help you make ads video in one click.
Materials to Video: you can upload your raw footage or pictures, TopView.ai will edit video based on media you uploaded for you.
Link to Video: you can paste an E-Commerce product link, TopView.ai will generate a video for you.