Skip to content

Forum in maintenance, we will back soon 🙂

Error with 'Update ...
 
Notifications
Clear all

Error with 'Update the UI'

26 Posts
4 Users
4 Reactions
270 Views
(@paddy)
Posts: 52
Trusted Member
Topic starter
 

when I run the advanced code (following all instructions in video), i enter a topic in UI, generate, and then nothing happens. The below error appears in the console:

 

advanced_script.js:86 Error occurred: SyntaxError: Unexpected token '`', "```json
[
"... is not valid JSON
at JSON.parse (<anonymous>)
at fetchData (advanced_script.js:77:25)

 
Posted : 08/16/2024 4:07 am
(@husein)
Posts: 550
Member Moderator
 

@paddy Where did you get this error? which code are you using? Please explain more your problem and provide screenshots so we can help you more.

 
Posted : 08/16/2024 6:41 am
(@paddy)
Posts: 52
Trusted Member
Topic starter
 

@husein this error appeared in the console.

This course:

I ran the first scripts in the wp UI and the hook generator worked.

I then tried to run these 3 advanced scripts - css, html, js (after changing the URL to my own). The UI opened and I entered the topic, hit generate, and nothing happened. no error messages, just nothing happened.


this was the php snippet I copied from course:

 

function openai_generate_text_basic() {    
	
	// Add CORS headers
     header('Access-Control-Allow-Origin: *'); // Allows all origins
     header('Access-Control-Allow-Methods: GET, POST, OPTIONS'); // Specifies the allowed methods
     header('Access-Control-Allow-Headers: Content-Type, Authorization'); // Specifies the allowed headers 

////check if logged in
	if (!is_user_logged_in()) {
       wp_send_json("LOGIN_FIRST");
    }
	
	//check for balance
	$user_id = get_current_user_id();
    $balance = mycred_get_users_balance($user_id);
    if ($balance < 5) {
        wp_send_json("NO_BALANCE");
    }
	
    // Get the topic from the AJAX request
    $topic = $_POST['topic'];
    $usage = $_POST['usage'];
    $prompt = "As an expert copywriter specialized in hook generation, your task is to analyze the [Provided_Hook_Examples] 
and use the templates that fit most to generate 3 new Hooks for the following topic: {" . $topic . "} and Usage in: {" . $usage . "}. The output should be ONLY valid JSON as follows:
[
  {{
    \"hook_type\": \"The chosen hook type\",
    \"hook\": \"the generated hook\"
  }},
  {{
    \"hook_type\": \"The chosen hook type\",
    \"hook\": \"the generated hook\"
  }},
  {{
    \"hook_type\": \"The chosen hook type\",
    \"hook\": \"the generated hook\"
  }}
]

[Provided_Hook_Examples]:
\"Hook Type,Template,Use In
Strong sentence,\"[Topic] won’t prepare you for [specific aspect].\",Social posts, email headlines, short content
The Intriguing Question,\"What’s the [adjective describing difference] difference between [Subject 1] and [Subject 2]?\",Video intros, email headlines, social posts
Fact,\"Did you know that [Interesting Fact about a Topic]?\",Video intros, email headlines, social posts, short content
Metaphor,\"[Subject] is like [Metaphor]; [Explanation of Metaphor].\",Video intros, email headlines, short content
Story,\"[Time Frame], [I/We/Subject] was/were [Situation]. Now, [Current Situation].\",Video intros, short content
Statistical,\"Nearly 70% of [Population] experience [Phenomenon] at least once in their lives.\",Blog posts, reports, presentations
Quotation,\"[Famous Person] once said, '[Quotation related to Topic]'.\",Speeches, essays, social posts
Challenge,\"Most people believe [Common Belief], but [Contradictory Statement].\",Debates, persuasive content, op-eds
Visual Imagery,\"Imagine [Vivid Description of a Scenario].\",Creative writing, advertising, storytelling
Call-to-Action,\"If you’ve ever [Experience/Desire], then [Action to take].\",Marketing content, motivational speeches, campaigns
Historical Reference,\"Back in [Year/Period], [Historical Event] changed the way we think about [Topic].\",Educational content, documentaries, historical analyses
Anecdotal,\"Once, [Short Anecdote related to Topic].\",Personal blogs, speeches, narrative content
Humorous,\"Why did [Topic] cross the road? To [Punchline].\",Social media, entertaining content, ice-breakers
Controversial Statement,\"[Controversial Statement about a Topic].\",Debates, opinion pieces, discussion forums
Rhetorical Question,\"Have you ever stopped to think about [Thought-Provoking Question]? \",Speeches, persuasive essays, social posts
\"
The JSON object:\n\n";

    // OpenAI API URL and key
    $api_url = 'https://api.openai.com/v1/chat/completions';
    $api_key = 'sk-my-api-key';  // 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-4o-mini',
        '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']) || !isset($data['choices'][0]['message']['content'])) {
            wp_send_json_error('API request failed. Response: ' . $body);
        } else {
            $content = $data['choices'][0]['message']['content'];
            mycred_subtract("Hook Generator", $user_id, 5, 'Point deduction for using hook Generation', time());
            wp_send_json($content);
        }
    }

    // Always die in functions echoing AJAX content
   wp_die();
}

add_action('wp_ajax_openai_generate_text_basic', 'openai_generate_text_basic');
add_action('wp_ajax_nopriv_openai_generate_text_basic', 'openai_generate_text_basic');
 
Posted : 08/16/2024 8:36 am
SSAdvisor
(@ssadvisor)
Posts: 1139
Noble Member
 

@paddy are you executing this locally or online somewhere? If online please give the URL so we can give it a try.

Regards,
Earnie Boyd, CEO
Seasoned Solutions Advisor LLC
Schedule 1-on-1 help
Join me on Slack

 
Posted : 08/16/2024 11:44 am
(@paddy)
Posts: 52
Trusted Member
Topic starter
 

@ssadvisor Hi Earnie I just ran the html file locally, but its connecting to the wp snippet on wordpress, so is that online im not sure?

 
Posted : 08/16/2024 12:45 pm
(@husein)
Posts: 550
Member Moderator
 

@paddy Did you replace the api key with your own API key in the PHP code?

And what @ssadvisor means, is your website online or you're using a local WordPress website. If its online please provide us with the link so we can test it from our side.

 
Posted : 08/17/2024 10:35 am
(@paddy)
Posts: 52
Trusted Member
Topic starter
 

@husein yes I replaced the API key with my own. and yes is online wordpress host.

 
Posted : 08/18/2024 10:07 am
SSAdvisor
(@ssadvisor)
Posts: 1139
Noble Member
 

Make sure your server is setup correctly.

  1. Mod_Rewrite Module: Make sure that the mod_rewrite module is enabled on your Hostinger server. This module is required for WordPress to generate pretty permalinks.
  2. .htaccess File: Check if the .htaccess file in your WordPress installation directory is properly configured. WordPress needs to write rewrite rules to this file to enable pretty permalinks.

Regards,
Earnie Boyd, CEO
Seasoned Solutions Advisor LLC
Schedule 1-on-1 help
Join me on Slack

 
Posted : 08/18/2024 1:01 pm
Hasan Aboul Hasan
(@admin)
Posts: 1276
Member Admin
 

@paddy did you get this to work?

 
Posted : 08/22/2024 7:58 pm
(@paddy)
Posts: 52
Trusted Member
Topic starter
 

@admin Unfortunately not, I cant get through to the Hostinger help desk to enable the mod_rewrite module on the Hostinger server. So cant proceed with this project now which is a shame.

 
Posted : 08/22/2024 9:46 pm
(@paddy)
Posts: 52
Trusted Member
Topic starter
 

and on top of that, the advanced UI html on my wp site is now looking like this. so the problems just keep stacking up.

 
Posted : 08/22/2024 9:56 pm
(@husein)
Posts: 550
Member Moderator
 

@paddy The UI looks like this because there isn't <html> tag at the top and </html> at the bottom of the code.

Try building the tool on a local WordPress to see if your hosting service is causing the problem.

 

 
Posted : 08/23/2024 6:00 am
Hasan Aboul Hasan
(@admin)
Posts: 1276
Member Admin
 

@paddy please send me your website details to hasan@learnwithhasan.com, I want to take a look to see if it is a hosting problem or something else.

 
Posted : 08/23/2024 8:04 am
Hasan Aboul Hasan
(@admin)
Posts: 1276
Member Admin
 

I tested the backend code without the UI, it worked perfectly, but it was returning "Login" and "No_balance" when I commented the lines that do these checks, it worked.

just make sure you implement the UI with authentication after you make sure that you are logged in, and you have points.

 
Posted : 08/24/2024 12:26 pm
Hasan Aboul Hasan
(@admin)
Posts: 1276
Member Admin
 

Also, try always to log the response in the browser console, so you can know if the problem is from the UI or the backend

 
Posted : 08/24/2024 12:27 pm
Page 1 / 2
Share:
[the_ad_group id="312"]