Forum in maintenance, we will back soon 🙂
Tool not functioning
I need some help with my tool. On the FreeAIKit website, I created my tool and it works fine, but on my WP website, I tried to follow the step-by-step guidance from the course but looks like I missed something and thus the doesn't work and I am not sure why. I copied the codes provied by you. Will you be kind enough to take 10 minutes out and check it for me please?
- I have attached the code in the word file.
- Here is the http://whattocook.club/sample-page/recipe-generator-tool/&source=gmail&ust=1708083589717000&usg=AOvVaw3VOn-x9Iw49b2yynYPENI E">link to the tool page
- I have mentioned the API key.
- Attached file has the Code Snippet, HTML, Java Script
file so that I don't have to bother you again. I do have some IT background and experience with codes and websites but It was many years ago.
@vickywm33 it's best to share your code with a public GitHub link or use the insert code icon (<>) above. Can you demonstrate how you tried to insert the code into your project? Give screenshots of the process.
Regards,
Earnie Boyd, CEO
Seasoned Solutions Advisor LLC
Schedule 1-on-1 help
Join me on Slack
@ssadvisor Firstly, thank you so much for your prompt response.
Step 1 was to create a PHP code Snippet - Download the plugin and activated it
Allowed it to run everywhere
used the below code which I copied from Hasan's course page - I changed the name from openai_generate_text to openai_generate_recipe and also added $ingredients = $_POST['prompt'] code, it was in Hasan's video but not in the code that was provided for copying.
function openai_generate_recipe() { // Get the ingredients from the AJAX request $ingredients = $_POST['prompt']; $prompt = "Generate 2 yummy recipes and provide a step-by-step guide on how to cook these. Do not use any other ingredients, for every step also list down the ingredient quantity required" . $ingredients; // OpenAI API URL and key $api_url = 'https://api.openai.com/v1/chat/completions'; $api_key = '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'; // Replace with your actual OpenAI API key // Headers for the OpenAI API $headers = [ 'Content-Type' => 'application/json', 'Authorization' => 'Bearer ' . $api_key ]; // Body for the OpenAI API $body = [ 'model' => 'gpt-3.5-turbo', 'messages' => [['role' => 'user', 'content' => $prompt]], 'temperature' => 0.7 ]; // Args for the WordPress HTTP API $args = [ 'method' => 'POST', 'headers' => $headers, 'body' => json_encode($body), 'timeout' => 120 ]; // Send the request $response = wp_remote_request($api_url, $args); // Handle the response if (is_wp_error($response)) { $error_message = $response->get_error_message(); wp_send_json_error("Something went wrong: $error_message"); } else { $body = wp_remote_retrieve_body($response); $data = json_decode($body, true); if (json_last_error() !== JSON_ERROR_NONE) { wp_send_json_error('Invalid JSON in API response'); } elseif (!isset($data['choices'])) { wp_send_json_error('API request failed. Response: ' . $body); } else { wp_send_json_success($data); } } // Always die in functions echoing AJAX content wp_die(); } add_action('wp_ajax_openai_generate_recipe', 'openai_generate_recipe'); add_action('wp_ajax_nopriv_openai_generate_recipe', 'openai_generate_recipe');
Then I created the new page and added the HTML and Java Script codes (code below). I think I didn't link the code snippet with the JS.
<div id="recipe-generation-tool"> <br> <input type="text" id="Type Your Ingredients" placeholder="Ingredients..."> <br> <br> <button id="generate-button">Generate Recipe!</button> <div id="result-container" style="display: none;"> <div class="result-wrapper"> <div class="result-content"> <textarea id="result" readonly></textarea> </div> <div class="copy-button-container"> <button id="copy-button">Copy</button> </div> </div> </div> <div id="loading" class="loader" style="display: none;"></div> </div> <style> /* Basic styles for the recipe generation tool */ #recipe-generation-tool { width: 100%; height: 400px; max-width: 600px; margin: 0 auto; font-family: Arial, sans-serif; } #recipe{ width: 200%; padding: 20px; margin-bottom: 20px; font-size: 16px; border-radius: 9px; border: 2px solid #fff; } #generate-button { display: block; width: 100%; padding: 15px; margin-bottom: 20px; font-size: 16px; border: none; border-radius: 5px; color: #fff; background-color: #000000; cursor: pointer; transition: background-color 0.3s ease; } #generate-button:hover { background-color: #2980b9; } #result-container { display: none; margin-bottom: 20px; } .result-wrapper { position: relative; overflow: hidden; } .result-content { display: flex; } #result { flex: 1; height: 400px; padding: 15px; font-size: 16px; border-radius: 5px; border: 1px solid #ddd; background-color: #f9f9f9; } .copy-button-container { margin-top: 10px; text-align: right; } #copy-button { padding: 8px 12px; font-size: 14px; border: none; border-radius: 5px; color: #fff; background-color: #3498db; cursor: pointer; transition: background-color 0.3s ease; } #copy-button:hover { background-color: #2980b9; } /* CSS for the loader */ .loader { display: block; margin: 50px auto; border: 16px solid #f3f3f3; /* Light grey */ border-top: 16px solid #3498db; /* Blue */ border-radius: 50%; width: 50px; height: 50px; animation: spin 1s linear infinite; } @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } </style> <script> document.getElementById("generate-button").addEventListener("click", function(e){ e.preventDefault(); var generateButton = document.getElementById("generate-button"); if (generateButton.disabled) { return; // Prevent multiple clicks while content is being generated } generateButton.disabled = true; var Ingredients = document.getElementById('Ingredients').value; var prompt = "Generate 2 yummy recipes and provide a step-by-step guide on how to cook these. Do not use any other ingredients, for every step also list down the ingredient quantity required " + ingredients; var loading = document.getElementById('loading'); var result = document.getElementById('result'); var resultC = document.getElementById('result-container'); loading.style.display = 'block'; result.style.display = 'none'; // hide result textarea resultC.style.display = 'none'; var formData = new FormData(); formData.append('action', 'openai_generate_recipe'); formData.append('prompt', prompt); fetch('/wp-admin/admin-ajax.php', { method: 'POST', body: formData }) .then(response => response.json()) .then(data => { loading.style.display = 'none'; if(data.success) { result.value = data.data.choices[0].message.content; result.style.display = 'block'; // show result textarea resultC.style.display = 'block'; generateButton.disabled = false; } else { result.value = 'An error occurred: ' + data.data; result.style.display = 'block'; // show result textarea resultC.style.display = 'block'; generateButton.disabled = false; } }) .catch(error => { loading.style.display = 'none'; result.value = 'An error occurred: ' + error.message; result.style.display = 'block'; // show result textarea resultC.style.display = 'block'; generateButton.disabled = false; }); }); var copyButton = document.getElementById('copy-button'); copyButton.addEventListener('click', function() { var result = document.getElementById('result'); result.select(); document.execCommand('copy'); alert('Copied to clipboard!'); }); </script>
I also added the API Key to code snippet as advised.
Many thanks & Kind regards
Waqas
@vickywm33 I'm not seeing what the problem is. What did you expect that isn't occurring?
Regards,
Earnie Boyd, CEO
Seasoned Solutions Advisor LLC
Schedule 1-on-1 help
Join me on Slack
@vickywm33 The problem is in this line :
var Ingredients = document.getElementById('Ingredients').value;
You defined the input as
<input type="text" id="Type Your Ingredients" placeholder="Ingredients...">
the ID must be 'Ingredients'
@admin Thank you Hasan,
Tried after changing, nothing happens after clicking generate button.
var Ingredients = document.getElementById('Ingredients').value;
I am losing hope in myself. lol 😊
Here is the link to the tool.
http://whattocook.club/recipe-generator-tool/
@admin Hasan do you think it could be Wp code snippet activation issue?
When I activated the plug in and created new snippet, Wp code didn't allow me to run it everywhere so I went back to Wp code list and duplicated a defual snippet which was configured to run everywhere.
So I modified the copy and put my code into the duplicated / copied snippet.
What do you think? I was avoiding to buy premium cut Wp sbippf but it only allowed specific pages
Please advise.
Waqas
@vickywm33 Below is what ChatGPT gave me when I asked about the code.
There are a few issues and improvements that can be made to your HTML, CSS, and JavaScript code to ensure it works correctly with the WordPress snippet you've provided. ### HTML Issues 1. **Input ID Mismatch**: The `input` element for ingredients has an `id` that seems to be intended as a placeholder rather than an actual ID. You should assign a proper ID to this element that matches what your JavaScript expects. ```html <!-- Before --> <input type="text" id="Type Your Ingredients" placeholder="Ingredients..."> <!-- After --> <input type="text" id="Ingredients" placeholder="Ingredients..."> ``` 2. **ID and Variable Name Mismatch in JavaScript**: In your JavaScript code, you're trying to access the input element using `document.getElementById('Ingredients')`, which is correct after the above change. However, there's an inconsistency in the variable name (`Ingredients` vs. `ingredients`) which is case sensitive in JavaScript. ### CSS Issues 1. **Unused ID Selector**: The CSS contains a selector `#recipe` which doesn't correspond to any element in your HTML. Ensure all CSS selectors correctly target the existing HTML elements. ### JavaScript Issues 1. **Case Sensitivity**: JavaScript is case-sensitive, so `Ingredients` (capital I) and `ingredients` (lowercase i) are considered two different variables. Your code snippet shows an attempt to use both, which would result in an error since `ingredients` (lowercase i) is not defined anywhere. ```javascript var Ingredients = document.getElementById('Ingredients').value; // The variable should then be used consistently ``` 2. **Correct Data in AJAX Response**: The way you're trying to access the response data (`data.data.choices[0].message.content`) does not align with the typical structure of an OpenAI API response. It's more likely to be `data.choices[0].text` based on the OpenAI API's response format. 3. **Error Handling Improvement**: Your error handling could be improved by providing more specific feedback to the user based on the type of error encountered. ### Security Concerns - **Hardcoded API Key**: You've included a hardcoded OpenAI API key in your WordPress PHP snippet, which is a significant security risk. It's better to store sensitive information like API keys in a secure location, such as WordPress' options table, and retrieve it securely within your code. ### Revised JavaScript Snippet Considering the above points, here is a revised part of your JavaScript related to handling the AJAX request: ```javascript var ingredientsInput = document.getElementById('Ingredients'); // Corrected ID var prompt = "Generate 2 yummy recipes and provide a step-by-step guide on how to cook these. Do not use any other ingredients, for every step also list down the ingredient quantity required " + ingredientsInput.value; // Consistent variable use // ... AJAX request and response handling logic ... .then(data => { if(data.success) { // Assuming data structure is corrected in the PHP snippet result.value = data.choices[0].text; // Corrected access to response data // Show result container logic... } else { // Handle error... } }) // ...rest of the AJAX handling logic... ``` Make sure you test your code after making these changes, and adjust any server-side logic if necessary to ensure the response data structure matches what your JavaScript expects.
There are a few issues and improvements that can be made to your HTML, CSS, and JavaScript code to ensure it works correctly with the WordPress snippet you've provided.
### HTML Issues
1. **Input ID Mismatch**: The `input` element for ingredients has an `id` that seems to be intended as a placeholder rather than an actual ID. You should assign a proper ID to this element that matches what your JavaScript expects.
```html
<!-- Before -->
<input type="text" id="Type Your Ingredients" placeholder="Ingredients...">
<!-- After -->
<input type="text" id="Ingredients" placeholder="Ingredients...">
```
2. **ID and Variable Name Mismatch in JavaScript**: In your JavaScript code, you're trying to access the input element using `document.getElementById('Ingredients')`, which is correct after the above change. However, there's an inconsistency in the variable name (`Ingredients` vs. `ingredients`) which is case sensitive in JavaScript.
### CSS Issues
1. **Unused ID Selector**: The CSS contains a selector `#recipe` which doesn't correspond to any element in your HTML. Ensure all CSS selectors correctly target the existing HTML elements.
### JavaScript Issues
1. **Case Sensitivity**: JavaScript is case-sensitive, so `Ingredients` (capital I) and `ingredients` (lowercase i) are considered two different variables. Your code snippet shows an attempt to use both, which would result in an error since `ingredients` (lowercase i) is not defined anywhere.
```javascript
var Ingredients = document.getElementById('Ingredients').value;
// The variable should then be used consistently
```
2. **Correct Data in AJAX Response**: The way you're trying to access the response data (`data.data.choices[0].message.content`) does not align with the typical structure of an OpenAI API response. It's more likely to be `data.choices[0].text` based on the OpenAI API's response format.
3. **Error Handling Improvement**: Your error handling could be improved by providing more specific feedback to the user based on the type of error encountered.
### Security Concerns
- **Hardcoded API Key**: You've included a hardcoded OpenAI API key in your WordPress PHP snippet, which is a significant security risk. It's better to store sensitive information like API keys in a secure location, such as WordPress' options table, and retrieve it securely within your code.
### Revised JavaScript Snippet
Considering the above points, here is a revised part of your JavaScript related to handling the AJAX request:
```javascript
var ingredientsInput = document.getElementById('Ingredients'); // Corrected ID
var prompt = "Generate 2 yummy recipes and provide a step-by-step guide on how to cook these. Do not use any other ingredients, for every step also list down the ingredient quantity required " + ingredientsInput.value; // Consistent variable use
// ... AJAX request and response handling logic ...
.then(data => {
if(data.success) {
// Assuming data structure is corrected in the PHP snippet
result.value = data.choices[0].text; // Corrected access to response data
// Show result container logic...
} else {
// Handle error...
}
})
// ...rest of the AJAX handling logic...
```
Make sure you test your code after making these changes, and adjust any server-side logic if necessary to ensure the response data structure matches what your JavaScript expects.
Regards,
Earnie Boyd, CEO
Seasoned Solutions Advisor LLC
Schedule 1-on-1 help
Join me on Slack
@vickywm33, Hi
the problem now moved to this line:
var prompt = "Generate 2 yummy recipes and provide a step-by-step guide on how to cook these. Do not use any other ingredients, for every step also list down the ingredient quantity required " + ingredients;
+ Ingredients and not ingredients;
it is capital I.
you can check the errors in the browser console
@vickywm33 the problem till now is in javascript; we can see this clearly in the browser console.
When we pass JS, then we can see if there are any problems in the code snippet.
@ssadvisor Thank you so much for investing your time and effort. We are getting so close now.
I did go a bit back and forth even after applying the fix and asking chat gpt multiple times. I have taken your feedback and @Hasan's feedback and applied it. There is one error now after I used JSFiddle.
Here is the one error I am getting, Chat Gpt says I have some code line which is HTML but is Bothering Java as its in its area.
"<a class='gotoLine' href='#158:1'>158:1</a> Uncaught SyntaxError: Unexpected token '<'"
Here is the code
//HTML & Java Script <div id="recipe-generation-tool"> <br> <input type="text" id="ingredients" placeholder="ingredients..."> <br> <br> <button id="generate-button">Generate Recipe!</button> <div id="result-container" style="display: none;"> <div class="result-wrapper"> <div class="result-content"> <textarea id="result" readonly></textarea> </div> <div class="copy-button-container"> <button id="copy-button">Copy</button> </div> </div> </div> <div id="loading" class="loader" style="display: none;"></div> </div> <style> /* Basic styles for the recipe generation tool */ #recipe-generation-tool { width: 100%; height: 400px; max-width: 600px; margin: 0 auto; font-family: Arial, sans-serif; } #recipe{ width: 200%; padding: 20px; margin-bottom: 20px; font-size: 16px; border-radius: 9px; border: 2px solid #fff; } #generate-button { display: block; width: 100%; padding: 15px; margin-bottom: 20px; font-size: 16px; border: none; border-radius: 5px; color: #fff; background-color: #000000; cursor: pointer; transition: background-color 0.3s ease; } #generate-button:hover { background-color: #2980b9; } #result-container { display: none; margin-bottom: 20px; } .result-wrapper { position: relative; overflow: hidden; } .result-content { display: flex; } #result { flex: 1; height: 400px; padding: 15px; font-size: 16px; border-radius: 5px; border: 1px solid #ddd; background-color: #f9f9f9; } .copy-button-container { margin-top: 10px; text-align: right; } #copy-button { padding: 8px 12px; font-size: 14px; border: none; border-radius: 5px; color: #fff; background-color: #3498db; cursor: pointer; transition: background-color 0.3s ease; } #copy-button:hover { background-color: #2980b9; } /* CSS for the loader */ .loader { display: block; margin: 50px auto; border: 16px solid #f3f3f3; /* Light grey */ border-top: 16px solid #3498db; /* Blue */ border-radius: 50%; width: 50px; height: 50px; animation: spin 1s linear infinite; } @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } </style> <script> document.getElementById("generate-button").addEventListener("click", function(e){ e.preventDefault(); var generateButton = document.getElementById("generate-button"); if (generateButton.disabled) { return; // Prevent multiple clicks while content is being generated } generateButton.disabled = true; var ingredients = document.getElementById('ingredients').value; var prompt = "Generate 2 yummy recipes and provide a step-by-step guide on how to cook these. Do not use any other ingredients, for every step also list down the ingredient quantity required " + ingredients; var loading = document.getElementById('loading'); var result = document.getElementById('result'); var resultC = document.getElementById('result-container'); loading.style.display = 'block'; result.style.display = 'none'; // hide result textarea resultC.style.display = 'none'; var formData = new FormData(); formData.append('action', 'openai_generate_recipe'); formData.append('prompt', prompt); fetch('/wp-admin/admin-ajax.php', { method: 'POST', body: formData }) .then(response => response.json()) .then(data => { loading.style.display = 'none'; if(data.success) { result.value =data.choices[0].text; result.style.display = 'block'; // show result text area resultC.style.display = 'block'; generateButton.disabled = false; } else { result.value = 'An error occurred: ' + data; result.style.display = 'block'; // show result textarea resultC.style.display = 'block'; generateButton.disabled = false; } }) .catch(error => { loading.style.display = 'none'; result.value = 'An error occurred: ' + error.message; result.style.display = 'block'; // show result textarea resultC.style.display = 'block'; generateButton.disabled = false; }); }); var copyButton = document.getElementById('copy-button'); copyButton.addEventListener('click', function() { var result = document.getElementById('result'); result.select(); document.execCommand('copy'); alert('Copied to clipboard!'); }); </script>
@vickywm33 I'm not seeing this in YOUR code. Maybe from a different WordPress module?
Regards,
Earnie Boyd, CEO
Seasoned Solutions Advisor LLC
Schedule 1-on-1 help
Join me on Slack
I see now the problem is in your backend, did you test the openai_generate_recipe function before you publish the tool, as I tested from my side, and it is not working
@admin Thank you Hasan, for your help. No I didn't test it because I wasn't sure how to test it especially when I was not able to install open ai on my VS and Python termina. My Python and VS Code skills are underdeveloped. Although I am learning by doing and also going through your course it is a bit naive stage for me. PLease advise
At least after yesterday's fitures, the generate button did something this time and gave me this error.