How to force Nginx to override PHP CGI HTTP Status code?

In Nginx + PHP-FPM configuration I have a .php file with the following content:

<?php
header("HTTP/1.1 405 Method Not Allowed");
echo 'hi';
?>

Now, if I want to force Nginx to ignore such this HTTP Status codes originating from PHP scripts, what should I do in Nginx config file? In other words, I want to Nginx dismiss custom status headers and ignore them (replace them with Status: 200 OK i.e.).
I have read Nginx documentation about fastcgi and didn’t find any useful directive for this purpose. Also, fastcgi_intercept_errors is not the solution.

how to install mongodb php driver on windows

PHP Warning: PHP Startup: Unable to load dynamic library ‘php_mongodb.dll’ (tri
ed: E:xamppphpextphp_mongodb.dll (The specified module could not be found),
E:xamppphpextphp_php_mongodb.dll.dll (The specified module could not be foun
d)) in Unknown on line 0

Warning: PHP Startup: Unable to load dynamic library ‘php_mongodb.dll’ (tried: E
:xamppphpextphp_mongodb.dll (The specified module could not be found), E:xa
mppphpextphp_php_mongodb.dll.dll (The specified module could not be found)) i
n Unknown on line 0

I have add php_mongodb.dll in ext folder and php.ini file also

Unable to load dynamic library ‘imagick.so’

I’m already desperate, I know there are a lot of similar questions but no solution helped me, so I’ll try a new question.

I’m trying to activate Imagick but I get this error

Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/homebrew/lib/php/pecl/20210902/imagick.so (dlopen(/opt/homebrew/lib/php/pecl/20210902/imagick.so, 0x0009): symbol not found in flat namespace '_AcquireAlignedMemory'), /opt/homebrew/lib/php/pecl/20210902/imagick.so.so (dlopen(/opt/homebrew/lib/php/pecl/20210902/imagick.so.so, 0x0009): tried: '/opt/homebrew/lib/php/pecl/20210902/imagick.so.so' (no such file), '/System/Volumes/Preboot/Cryptexes/OS/opt/homebrew/lib/php/pecl/20210902/imagick.so.so' (no such file), '/opt/homebrew/lib/php/pecl/20210902/imagick.so.so' (no such file))) in Unknown on line 0

I’ve installed it with this order:

brew install imagemagick
brew install pkg-config
pecl install imagick

Also in php.ini I have it enabled:

extension="imagick.so"

Imagick is installed correctly:

convert --version                                                                                                                                  127 ✘  11:39:56
Version: ImageMagick 7.1.1-12 Q16-HDRI aarch64 21239 https://imagemagick.org
Copyright: (C) 1999 ImageMagick Studio LLC
License: https://imagemagick.org/script/license.php
Features: Cipher DPC HDRI Modules OpenMP(5.0)
Delegates (built-in): bzlib fontconfig freetype gslib heic jng jp2 jpeg jxl lcms lqr ltdl lzma openexr png ps raw tiff webp xml zlib
Compiler: gcc (4.2)

And imagick.so is placed correctly:

-rw-r--r--  1 jklimcik  admin  494967 Jul 14 10:08 /opt/homebrew/lib/php/pecl/20210902/imagick.so

What am I missing or what’s wrong? I am using MacOS 13.4, Apple M1 Pro. I’m also using Laravel Valet, but I don’t think it’s related to this issue.

Laravel as REST API – 401 Unauthorized

I create applications on the frontend side Angular but in the backend Laravel. I also created a login controller that returns me a token for Angular which then adds to the request headers and it should work but it returns 401… and I don’t know why :/

<?php

namespace AppHttpControllers;

use AppModelsUser;
use IlluminateHttpRequest;
use IlluminateSupportFacadesAuth;
use IlluminateSupportFacadesValidator;
use TymonJWTAuthFacadesJWTAuth;
use TymonJWTAuthExceptionsJWTException;

class AuthController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth:api', ['except' => ['login', 'register']]);
        $this->middleware('auth:jwt', ['except' => ['login', 'register']]);
    }

    public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string',
            'email' => 'required|email|unique:users',
            'password' => 'required|min:6',
        ]);

        if ($validator->fails()) {
            return response()->json(['error' => $validator->errors()], 400);
        }

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => bcrypt($request->password),
        ]);

        $token = JWTAuth::fromUser($user);

        return response()->json(['token' => $token], 201);
    }

    public function login(Request $request)
    {
        $credentials = $request->only('email', 'password');

        try {
            if (!$token = JWTAuth::attempt($credentials)) {
                return response()->json(['error' => 'Invalid credentials'], 401);
            }
        } catch (JWTException $e) {
            return response()->json(['error' => 'Could not create token'], 500);
        }

        return response()->json(['token' => $token]);
    }

    public function logout(Request $request)
    {
        try {
            JWTAuth::invalidate(JWTAuth::getToken());
        } catch (JWTException $e) {
            return response()->json(['error' => 'Failed to logout'], 500);
        }

        return response()->json(['message' => 'Successfully logged out']);
    }

}

I’m not sure if I’m using the right middleware or if I haven’t forgotten some configuration.. but the login() method in AuthController creates and returns a token the problem is with UserController and getUsers() because I get 401 method :/

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use AppModelsUser;
use TymonJWTAuthExceptionsJWTException;
use TymonJWTAuthFacadesJWTAuth;

class UserController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:api');
        $this->middleware('auth:jwt');
    }

    public function getUsers()
    {
        try {
            JWTAuth::invalidate(JWTAuth::getToken());
        } catch (JWTException $e) {
            return response()->json(['error' => 'Failed to getUsers()'], 500);
        }

        $users = User::all();
        return response()->json($users);
    }

    public function deleteUser($id)
    {
        try {
            JWTAuth::invalidate(JWTAuth::getToken());
        } catch (JWTException $e) {
            return response()->json(['error' => 'Failed to deleteUser()'], 500);
        }

        $user = User::findOrFail($id);
        $user->delete();
        return response()->json(['message' => 'Użytkownik został usunięty']);
    }
}

routes/api.php

Route::post('register', [AuthController::class, 'register']);
Route::post('login', [AuthController::class, 'login']);

Route::group(['middleware' => ['auth:api', 'auth:jwt']], function () {
    Route::post('logout', [AuthController::class, 'logout']);
    Route::get('users', [UserController::class, 'getUsers']);
    Route::delete('users/{id}', [UserController::class, 'deleteUser']);
});

config/auth.php

'defaults' => [
    'guard' => 'api',
    'passwords' => 'users',
],

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
    'api' => [
        'driver' => 'jwt',
        'provider' => 'users',
    ],
    'jwt' => [
        'driver' => 'jwt',
        'provider' => 'users',
    ],
],

How to get the OG image Dynamically

The project I’m working on is a project for a hotel. There are different images for different pages as a main image.
For Example-
If someone shares the about us page to facebook, the main image in the about us page should be displayed below the link. If someone shares the home page to facebook, the main image in the home page should be displayed below the link. There can only be one link in the og:image because the header.php file is the same file that I’m using to all pages

Is there any way that I can do this using php or js.

Thank you in advance.

<meta property="og:image" id="ogImage" content="">
  <script>
    function setOGImageURL() {
      const ogImageElement = document.querySelector('.entry-header-image');
      if (ogImageElement) {
        const ogImageURL = ogImageElement.getAttribute('src');
        console.log(ogImageElement)
        const ogImageTag = document.getElementById('ogImage');
        ogImageTag.setAttribute('content', ogImageURL);
      }
    }

    window.onload = function() {
      setOGImageURL();
    };
  </script>

I was trying to do from this code. But it didn’t work

How can i make auto fill an input form based on selectbox dropdown?

I’m trying to auto fill an input form based on the selection of a selectbox. the auto fill text comes from my database

This is my code:

<select style="width: 110px;" class="form-control" name="id_periodik" id="id_periodik" required oninvalid="this.setCustomValidity('Masukkan periodik sparepart!')"
oninput="this.setCustomValidity('')">
<?php foreach ($periodik_options as $option) {?>
<option value="<?php echo $option['id_periodik']; ?>">
<?php echo $option['nama_periodik']; ?>
</option>
<?php }?>
</select>
</td>

text auto fill based on selection:

<td>
<input type="text" class="form-control" id="jumlah_periodik" name="jumlah_periodik[]" readonly>
</td>

script:

<script>
$(document).ready(function() {
$('#id_periodik').on('change', function() {
var selectedValue = $(this).val();
$('#jumlah_periodik').val(selectedValue);
});
});
</script>

i’ve try that but nothing happens in my view. Any help you can give I appreciate it
enter image description here

Base64 images are not saving to images folder higher than 600kb

I’m using React Quill for the text editor, so when I upload images, they go to the backend as base64. I’m handling them in PHP to decode and upload them to the images folder as photos. Still, some images I’m uploading from the text editor higher than 600kb are immediately uploaded to the database as base64. They don’t get decoded and uploaded to the images folder as an image like png.

PHP Code

preg_match_all('/<img.*?src="data:image/(.*?);base64,(.*?)".*?>/si', $description, $matches);
if (isset($matches[1]) && isset($matches[2])) {
    $imageData = $matches[2];

    $imagePath = 'images/';

    foreach ($imageData as $key => $base64Data) {
        $extension = $matches[1][$key];
        // Generate a unique filename
        $imageName = uniqid() . '.' . $extension;

        // Decode the base64 image data
        $decodedImage = base64_decode($base64Data);

        // Save the image file
        $imageFilePath = $imagePath . $imageName;
        file_put_contents(__DIR__ . '/' . $imageFilePath, $decodedImage);

        // Replace the base64 image data with the image file path in the description field
        $description = str_replace($matches[0][$key], '<img src="' . $imageFilePath . '">', $description);
    }
}

wordpress with mysql deployment instance periodically unreachable

I have a wordpress + mysql instance deployed on the server machine with nginx. At some point I noticed wordpress container periodically returning 500 or 302. No errors shown in the corresponding mysql instance logs. Sometimes refreshing the wordpress page a few times helps.

Here is docker-compose file used for the deployment. WordPress version: 6.0.2, MySQL: 8.0.33

version: '3.9'
services:
  wordpress:
    image: wordpress
    depends_on:
      - db
    restart: always
    ports:
      - 8083:80
    environment:
      WORDPRESS_DB_HOST: db:3306
      WORDPRESS_DB_USER: wordpress
      WORDPRESS_DB_PASSWORD: "$DB_PASSWORD"
      WORDPRESS_DB_NAME: portal
    volumes:
      - /data/portal/wordpress:/var/www/html:Z

  db:
    image: mysql
    restart: always
    environment:
      MYSQL_DATABASE: portal
      MYSQL_USER: wordpress
      MYSQL_PASSWORD: "$DB_PASSWORD"
      MYSQL_ROOT_PASSWORD: "***"
    volumes:
      - /data/portal/db:/var/lib/mysql:Z
networks:
  default:
    name: default_network

I have tried to update both wordpress and mysql to recent versions, deactivate all plugins and themes, increase PHP memory limits and redeploy everything from scratch removing all the data from volumes, nothing so far helped to fix the issue. Any thoughts about where to look for the possible source of this problem?

unable to resubmit the form after failer using ajax method on codeignetor4

I’m using a form submission popup.if the form submitted success means no issue in case form submission fail we show a popup when we click on the close we form have the data what we entered so we correct the error field again we submit the button is not working. i think its an issue in generating the csrf .how can i fix this?

<script>
$(document).ready(function() {
    // Handle form submission
    $('#registrationForm').submit(function(e) {
        e.preventDefault();

        
        var csrfHash = '<?php echo csrf_hash(); ?>';

        $.ajaxSetup({
            headers: {
                'X-CSRF-Token': csrfHash
            }
        });
        // Get form data
        var formData = $(this).serialize();

        // Perform AJAX request
        $.ajax({
            url: '<?= base_url('register-post'); ?>',
            type: 'POST',
            data: formData,
            success: function(response) {

                if (response && response.success) {
                    // Handle successful form submission
                    console.log(response);
                    showPopup('Success!', 'Registration successful!');
                    setTimeout(function() {
                        location.reload();
                    }, 3000);
                } else {

                    // Handle failed form submission
                    var errorMessage = response && response.message ? response.message :
                        'Error occurred during form submqwwission.';
                    showPopup('Failed!', response.message);
                    console.error(errorMessage);
                }
            },

            error: function(xhr, status, error) {
                // Handle AJAX error
                if (csrfHash) {
                    console.log('ok3')
                    console.log(csrfHash);

                } else {

                    console.log('faaa')

                    // Handle CSRF verification failure
                    // ...
                }
                showPopup('Failed!', 'Error occurred during form submission: ' + xhr
                    .responseText);
                console.error(error);
            }

        });
    });
});

this my function.what i need is to generate new csrf on each submit

dynamically Locating items in css grid to have no empty space

I’m on wordpress and want to have a portfolio with css grid.

All items are get one column except some of the items are double width with style span 2 when admin wants to (with acf ture/false).

In some scenarios I have a free column.

As I know today that there is no solution in css. maybe javascript or php can handle it!

If you know how to fix this with any kind (even change grid to flex or use float) it would be much appreciated!

this is the picture of one of the scenarios that this problem occur and this is my code so far:

enter image description here

const project = document.querySelector(".project");
const projectBtn = document.querySelectorAll(".project--btn");
const projectList = document.querySelectorAll(".project__list");

project.onclick = e => {
    const tabId = e.target.dataset.id;
    if (tabId) {
        projectBtn.forEach(btn => {
            btn.classList.remove("active");
        });
        e.target.classList.add("active");

        projectList.forEach(content => {
            content.classList.remove("active");
        });
        const projectTab = document.getElementById(tabId);
        projectTab.classList.add("active");
    }
}
.project {
    width: 100%;
    margin: 50px auto;
}

.project__button-wrapper {
    margin: 20px 0;
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 10px;
}

.project--btn {
    background: transparent;
    border: 0;
    padding: 12px 20px;
    cursor: pointer;
    font-size: 14px;
    line-height: 26px;
}

.project--btn.active {
    border-bottom: 2px solid #000;
}

.project__list {
    padding: 0;
    display: none;
    grid-template-columns: repeat(5, 1fr);
    flex-wrap: wrap;
    gap: 20px;
}

.project__list.active {
    display: grid;
}

.project__item {
    height: 300px;
    border-radius: 15px;
    overflow: hidden;
}

.project__link {
    width: 100%;
    min-height: 100%;
    max-height: 100%;
    display: grid !important;
}

.project__link--img {
    width: 100%;
    min-height: 100%;
    max-height: 100%;
    grid-column: 1;
    grid-row: 1;
    object-fit: cover;
}

.project__link--overlay {
    padding: 20px;
    background: rgba(255, 255, 255, 0.32);
    box-shadow: 0 4px 30px rgba(0, 0, 0, 0.1);
    backdrop-filter: blur(4.7px);
    -webkit-backdrop-filter: blur(4.7px);
    color: #fff;
    opacity: 0;
    grid-column: 1;
    grid-row: 1;
    align-self: end;
}

.project__link--title {
    font-size: 18px;
    font-weight: 600;
    line-height: 30px;
}

.project__link--excerpt {
    font-size: 14px;
    font-weight: 500;
    line-height: 20px;
}

.project__link--overlay-footer {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    align-items: center;
}

.project__link--category {
    font-size: 12px;
    font-weight: 300;
    line-height: 16px;
    display: block;
    text-align: end;
}

.project__link:hover .project__link--overlay {
    opacity: 1;
}
@media only screen and (max-width: 1140px) {
    .project__list {
        grid-template-columns: repeat(4, 1fr);
    }
}
@media only screen and (max-width: 767px) {
    .project__list {
        grid-template-columns: repeat(2, 1fr);
    }
}
@media only screen and (max-width: 575px) {
    .project__list {
        grid-template-columns: repeat(1, 1fr);
    }
    .project__item{
        grid-column: 1 !important;
    }
}

/*@media only screen and (min-width: 992px) {
    .project__list {
        grid-template-columns: repeat(4, 1fr);
    }
}

@media only screen and (min-width: 1200px) {
    .project__list {
        grid-template-columns: repeat(5, 1fr);
    }
}*/
<?php 
// Shortcode: [project_shortcode]
add_shortcode('project_shortcode', 'company_porjects');

function company_porjects()
{
    ob_start(); ?>

    <div class="project">
        <?php
        $queryCats = get_terms(array(
            'taxonomy' => 'category',
            'hide_empty' => true
        ));
        ?>
        <div class="project__button-wrapper">
            <button class="project--btn active" data-id="tabAll">همه پروژه ها</button>
            <?php foreach ($queryCats as $cat) { ?>
                <button class="project--btn" data-id="tab<?php echo $cat->term_id; ?>"><?php echo $cat->name; ?></button>
            <?php } ?>
        </div>
        <div class="project__content-wrapper">
            <?php $allPortfolio = new WP_Query(array(
                'post_type' => 'post',
                'post_status' => 'publish',
                'posts_per_page' => -1,
                'orderby' => 'rand'
            )); ?>
            <ul class="project__list active" id="tabAll">
                <?php $itemOrderAll = 1;
                while ($allPortfolio->have_posts()) {
                    $allPortfolio->the_post();
                ?>
                    <li class="project__item" style="order:<?php echo $itemOrderAll ?>;<?php if (get_field('double_width')) { ?> grid-column: span 2; <?php } ?>;">
                        <a href="<?php the_permalink(); ?>" class="project__link">
                            <?php the_post_thumbnail('medium', array('class' => 'project__link--img')); ?>
                            <div class="project__link--overlay">
                                <h3 class="project__link--title"><?php the_title(); ?></h3>
                                <p class="project__link--excerpt"><?php the_excerpt(); ?></p>
                                <span class="project__link--category"><?php the_category(); ?></span>
                            </div>
                        </a>
                    </li>
                <?php
                    $itemOrderAll++;
                } ?>
                <?php wp_reset_postdata(); ?>
            </ul>
            <?php foreach ($queryCats as $cat) { ?>
                <?php $queryPortfolio = new WP_Query(array(
                    'post_type' => 'post',
                    'posts_per_page' => -1,
                    'orderby' => 'rand',
                    'tax_query' => array(
                        array(
                            'taxonomy'      => 'category',
                            'field'         => 'term_id',
                            'terms'         => $cat->term_id,
                            'operator'      => 'IN'
                        )
                    )
                )); ?>
                <ul class="project__list" id="tab<?php echo $cat->term_id; ?>">
                    <?php $itemOrder = 1;
                    while ($queryPortfolio->have_posts()) {
                        $queryPortfolio->the_post(); ?>
                        <li class="project__item" style="<?php if (get_field('double_width')) { ?> grid-column: span 2;<?php } ?>">
                            <a href="<?php the_permalink(); ?>" class="project__link">
                                <?php the_post_thumbnail('medium', array('class' => 'project__link--img')); ?>
                                <div class="project__link--overlay">
                                    <h3 class="project__link--title"><?php the_title(); ?></h3>
                                    <span class="project__link--category"><?php the_category(); ?></span>
                                </div>
                            </a>
                        </li>
                    <?php
                        $itemOrder++;
                    } ?>
                </ul>
            <?php } ?>
            <?php wp_reset_postdata(); ?>
        </div>
    </div>
<?php
    $project_content = ob_get_contents();
    ob_get_clean();
    return $project_content;
    wp_reset_postdata();
}

Getting a wordpress plugin to function after an event (eg Upon a draft post created)

I have created a wordpress plugin (with help from ChatGPT) that rewrites post titles that in drafts to meet the criteria i need of being between 36 and 38 characters in length. This is achieved currently by clicking a button , “Autofill” , this then gets ChatGPT to rewrite the current draft title, then the reply is checked to see how long it is, if it doesnt meet the 36-38 character limit, the process is repeated until it is complete. The title is then changed and the post is published.

This works fine, however, i am trying to make this more automatic, so instead of having to login to wordpress and click the button to start the rewrite process, i would like it whenever a new draft post is saved, the process then starts automatically. No matter what i have tried, i haven’t been able to do it, does anyone have any ideas of how i can achieve this? Below is my code that works when i manually press the button

<?php
/*
Plugin Name: ChatGPT Dashboard
*/

// Add a custom menu item to the WordPress dashboard
function chatgpt_dashboard_menu() {
  add_menu_page(
    'ChatGPT Dashboard',
    'ChatGPT',
    'manage_options',
    'chatgpt-dashboard',
    'chatgpt_dashboard_page',
    'dashicons-format-chat', // You can change the icon here
    20
  );
}
add_action('admin_menu', 'chatgpt_dashboard_menu');

// Enqueue jQuery UI library
function chatgpt_enqueue_scripts() {
  wp_enqueue_script('jquery-ui-core');
  wp_enqueue_script('jquery-ui-draggable');
}
add_action('admin_enqueue_scripts', 'chatgpt_enqueue_scripts');

// Register plugin settings
function chatgpt_register_settings() {
  register_setting('chatgpt_options', 'chatgpt_api_key');
}
add_action('admin_init', 'chatgpt_register_settings');

// Callback function to display the ChatGPT dashboard page
function chatgpt_dashboard_page() {
  ?>
  <div class="wrap">
    <h1>ChatGPT Dashboard</h1>

    <!-- API Key settings form -->
    <form method="post" action="options.php">
      <?php settings_fields('chatgpt_options'); ?>
      <?php do_settings_sections('chatgpt_options'); ?>
      <table class="form-table">
        <tr valign="top">
          <th scope="row">API Key</th>
          <td><input type="text" name="chatgpt_api_key" value="<?php echo esc_attr(get_option('chatgpt_api_key')); ?>" /></td>
        </tr>
      </table>
      <?php submit_button(); ?>
    </form>

    <!-- Chat interface -->
    <div id="chat-container">
      <div id="chat-log"></div>
      <input type="text" id="user-input" placeholder="Type your message..." />
      <button id="submit-button">Send</button>
      <button id="autofill-button">Autofill</button>
    </div>
  </div>

  <script>
    (function ($) {
      $(document).ready(function () {
        // Function to handle user input and generate ChatGPT responses
        function handleUserInput() {
          var userInput = $('#user-input').val();

          // Get the API key from the WordPress options database
          var apiKey = '<?php echo get_option("chatgpt_api_key"); ?>';

          // Make sure the API key is provided
          if (!apiKey) {
            alert('Please enter an API key in the ChatGPT dashboard settings.');
            return;
          }

          // Make an API call to ChatGPT to get a response
          function callChatGPT() {
            $.ajax({
              url: 'https://api.openai.com/v1/chat/completions',
              type: 'POST',
              beforeSend: function (xhr) {
                xhr.setRequestHeader('Authorization', 'Bearer ' + apiKey);
                xhr.setRequestHeader('Content-Type', 'application/json');
              },
              data: JSON.stringify({
                model: 'gpt-3.5-turbo',
                messages: [
                  { role: 'system', content: 'You are a user' },
                  { role: 'user', content: userInput },
                ],
              }),
              success: function (response) {
                var chatLog = $('#chat-log');

                if (!response.choices || !response.choices.length) {
                  chatLog.append('<p><strong>Error:</strong> No response received</p>');
                  return;
                }

                var botResponse = response.choices[0].message.content;

                // Check if botResponse is an array
                if (Array.isArray(botResponse)) {
                  botResponse = botResponse.map(msg => msg.content).join('');
                }

                // Count the number of characters in the bot response
                var characterCount = botResponse.length;

                // Display the user input, bot response, and character count in the chat log
                chatLog.append('<p><strong>You:</strong> ' + userInput + '</p>');
                chatLog.append('<p><strong>Bot:</strong> ' + botResponse + '</p>');
                chatLog.append('<p><strong>Character count:</strong> ' + characterCount + '</p>');

                // Clear the user input field
                $('#user-input').val('');

                // Scroll to the bottom of the chat log
                chatLog.scrollTop(chatLog.prop('scrollHeight'));

                // Check if the character count is within the desired range (36, 37, or 38)
                if (characterCount >= 36 && characterCount <= 38) {
                  // Print the new title 5 times in a row
                  for (let i = 0; i < 5; i++) {
                    chatLog.append('<p><strong>New Title:</strong> ' + botResponse + '</p>');
                  }
                  
                 // Create a new post with the new title and set it as a draft
$.ajax({
  url: '<?php echo admin_url("admin-ajax.php"); ?>',
  type: 'POST',
  data: {
    action: 'create_draft_post',
    title: botResponse,
  },
  success: function (response) {
    console.log('Draft post updated:', response);
    chatLog.append('<p><strong>New Title:</strong> ' + botResponse + '</p>');
  },
  error: function (xhr, status, error) {
    console.error(error); // Log any errors to the browser console
  },
});

                  return; // Exit the function if the condition is met
                }

                // Repeat the question until the character count is within the desired range
                callChatGPT();
              },
              error: function (xhr, status, error) {
                var chatLog = $('#chat-log');
                chatLog.append('<p><strong>Error:</strong> ' + error + '</p>');
                console.error(error); // Log any errors to the browser console
              },
            });
          }

          callChatGPT(); // Initial call to ChatGPT
        }

        // Handle user input when the submit button is clicked
        $('#submit-button').on('click', function (e) {
          e.preventDefault();
          handleUserInput();
        });

        // Handle user input when the enter key is pressed
        $('#user-input').on('keydown', function (e) {
          if (e.keyCode === 13) {
            e.preventDefault();
            handleUserInput();
          }
        });
// Handle autofill button click
$('#autofill-button').on('click', function (e) {
  e.preventDefault();

  // Get the draft posts
  $.ajax({
    url: '<?php echo admin_url("admin-ajax.php"); ?>',
    type: 'POST',
    data: {
      action: 'get_draft_posts',
    },
    success: function (response) {
      if (response && response.length) {
        var draftTitle = response[0].post_title;
        var autofillText = 'Summarize "' + draftTitle + '" to 38 characters';
        $('#user-input').val(autofillText);
        
        // Automatically start the process of generating the response
        handleUserInput();
      }
    },
    error: function (xhr, status, error) {
      console.error(error); // Log any errors to the browser console
    },
  });
});
      });
    })(jQuery);
  </script>
  <?php
}

// AJAX handler to retrieve draft posts
function chatgpt_get_draft_posts() {
  $draftPosts = get_posts(array(
    'post_status' => 'draft',
    'numberposts' => 1,
  ));
  wp_send_json($draftPosts);
}
add_action('wp_ajax_get_draft_posts', 'chatgpt_get_draft_posts');
add_action('wp_ajax_nopriv_get_draft_posts', 'chatgpt_get_draft_posts');

// AJAX handler to update the existing draft post with the new title and publish it
function chatgpt_create_draft_post() {
  $title = $_POST['title'];

  $draftPosts = get_posts(array(
    'post_status' => 'draft',
    'numberposts' => 1,
  ));

  if (empty($draftPosts)) {
    wp_send_json_error('No draft post found.');
    return;
  }

  $draftPost = $draftPosts[0];
  $draftPostID = $draftPost->ID;

  // Update the title of the draft post
  wp_update_post(array(
    'ID'         => $draftPostID,
    'post_title' => $title,
    'post_status' => 'publish',
  ));

  wp_send_json_success($draftPostID);
}
add_action('wp_ajax_create_draft_post', 'chatgpt_create_draft_post');
add_action('wp_ajax_nopriv_create_draft_post', 'chatgpt_create_draft_post');

Thanks in advance for any help/advice

I have tried to create a hook and a cron job, but my limited php knowledge has not been able to achieve this

how to copy a file from a linux directory into [closed]

type herefilenames <- list.files("C:/...", recursive=TRUE, full.names=TRUE, pattern=".xml")

name <- unlist(lapply(filenames, function(f) {  
  xml <- xmlParse(f)  
  xpathSApply(xml, "//...", xmlValue)
}))
data <- data.frame(name)filenames <- list.files("C:/...", recursive=TRUE, full.names=TRUE, pattern=".xml")

name <- unlist(lapply(filenames, function(f) {  
  xml <- xmlParse(f)  
  xpathSApply(xml, "//...", xmlValue)
}))
data <- data.frame(name)

edvfvkm fefilenames <- list.files(“C:/…”, recursive=TRUE, full.names=TRUE, pattern=”.xml”)

name <- unlist(lapply(filenames, function(f) {
xml <- xmlParse(f)
xpathSApply(xml, “//…”, xmlValue)
}))
data <- data.frame(name)

add url in the pie chart

enter image description here

Like this picture. I want to add 3 urls. (URL) => [A,B,C] When the user clicks on one of the pie charts. A new page will open.I want to know how to add url params in the javascript.

Is change datasetsdata ?

const data = {
  labels: [
    'Red',
    'Blue',
    'Yellow'
  ],
  datasets: [{
    label: 'My First Dataset',
    data: [300, 50, 100],
    backgroundColor: [
      'rgb(255, 99, 132)',
      'rgb(54, 162, 235)',
      'rgb(255, 205, 86)'
    ],
    hoverOffset: 4
  }]
};

EMM. I’m not to try everything. I don’t know how to do it.

Data inserting to database from table

I write acode that take input from input field (admissionNumber,course_name,midresult and finalresult) andwhen add button clicked to compute sum for midresult and finalresult and store it in total mark variable in javascript and compute total sum of all courses totalmark and average for alladmissionNumber and display in table form. I need to store the whole result details in database table called tblresult having admissionNumber,course_name,midresult, finalresult and total mark.

I tried to store as usual but when ad button is clicked the input fields are cleand exept the admissionNumber which is what i needed but i expected to insert into tblresult not from input fiel instead from the table which is created by java script dynamically

How to implement slug in laravel

I am having a problem how to display slug data in view file i am using cviebrock/eloquent-sluggable

my model file

use Sluggable;

public function sluggable() {
   return ['slug'=>[
       'source'=>'title',
       'onUpdate'=>true
   ]];
}

public static function boot()
{
    parent::boot();
    self::creating(function($model){
        $model->slug = Str::slug($model->title, '-');
    });
}

my route

Route::get(“tenderview”, “TenderViewController@show”)->name(‘tenderview’);

Route::get(‘/tenderview’, ‘TenderViewController@index’)->name(‘tenderview’);

Controller file

public function index()
{
    return view('tenderview');
}

public function show()
{
    $dataa = Kind::orderBy('created_at', 'DESC')->paginate(8);

    return view('tenderview',['dataa'=>$dataa]);
}

View file
@foreach($dataa as $dater)
{{$dater->name}}
@endforeach

How can i show slug in my view instead of displaying data as a whole, i want to display a link to the actual data. Thank you