Execute js code inside a ajax handler function in wordpress

I focused on a wordpress plugin development. In this plugin, I’m trying to design a progress bar that moves according a backend process. After an extensive search, I understood that it is possible by using jquery methods.

From this reference, I wrote following code in plugin’s main php file:

<?php
add_action( 'admin_footer', 'my_action_javascript' );

function my_action_javascript() { ?>
<script type="text/javascript" >
jQuery(document).ready(function($) {

    var element = document.getElementById("myBar"); // It is my bootstrap progress bar
    var width=0; // Initial width (%)
    var add=1; // 1% incrementation variable for progress bar

    var data = {
        'action': 'my_action',
        'whatever': 1234
    };
    
    jQuery.post(ajaxurl, data, function(response) {
        alert('Got this from the server: ' + response);
    });
});
</script> <?php
}

add_action( 'wp_ajax_my_action', 'my_action' );

function my_action() {

$whatever = $_POST['whatever'];

echo $whatever;

wp_die();
}

It works fine, the response shows on alert field. However, when I add following js code into that my_action function:

add_action( 'wp_ajax_my_action', 'my_action' );

function my_action() {

$repeater = 0;
$controller = 0;

for ($i=1; $i <= 4000 ; $i++) { 
    if ($repeater <= 10) {
        $controller++;
        if ($controller == 40) { ?>
            //code starts here
            <script type="text/javascript">
            element.style.width = width + add + "%"; 
            element.innerHTML = width + add + "%";
            width = width+add;  
            </script>
            <?php 
            sleep(1);
            $controller=0;
            $repeater++;
        }
    } else {
        return;
    }
}

wp_die();
}

It doesn’t work. I guess the nature of ajax process in wordpress, the core is waiting for finishes all php codes in function and it doesn’t allow run another js code. So, if I miss some point or there is a better way to achieve this; I would be grateful if you help.

Use Pivot Table id in Another Pivot Table

Each store ships products through shipping_methods. For example store1 ships with FedEx and UPS. But each store can restrict its shipping methods per product.
For example product1 ships only via FedEx by store1 while product2 can get shipped via both FedEx and UPS.
My table structure is as follows:

stores
- id
  
delivery_methods
- id

products
- id

I have a pivot table which connects stores with delivery_methods implementing a ManyToMany relationship:

store_delivery_method
- id
- store_id
- delivery_method_id

I need a way to connect this pivot to multiple products so that every product in every store may have multiple delivery/shipping methods. My idea is to create another table like so:

delivery_method_product_store
- store_delivery_method_id
- product_id

The catch is, product1 of store1 cannot have a delivery_method of, for example DHL since the store manager doesn’t work with that company.
Is this the correct way? If so, how should I write the model relationships?
Thanks in advance.
PS: My models so far:

class Store extends Model
{
  public function deliveryMethods()
    {
       return $this->belongsToMany(DeliveryMethod::class,'store_delivery_method');
    }
}

class DeliveryMethod extends Model
{
  public function stores()
    {
       return $this->belongsToMany(Store::class, 'store_delivery_method');
    }
}

How to send data from Livewire component to a controller?

I have a very basic Livewire component. I know, there is a wire:click, but I simplified it very much, to give you something by hand. In my real app, there is a calendar component and when you click on an event, it fires the emit() and sends data from the ui to the Livewire component, where it get’s modified.

My question is: How can post this data from the Livewire component to the foo.store route?

app/Http/Livewire/Foo.php:

class Foo extends Component
{
    public $foo;

    protected $listeners = [
         'store' => 'store'
    ];

    public function render()
    {
         return view('livewire.foo');
    }

    public function store($data)
    {
         $payload = $this->do_complex_math_on_data($data);
         // ❓ post payload to FooController's store() function - HOW?
    }

    private function do_complex_math_on_data($data)
    {
         return 1+1;
    }
}

resources/views/livewire/foo.blade.php:

<div>
   <button>Click me!</button>
</div>

<script>
    document.addEventListener('livewire:load', function() {
        document.querySelector('button').addEventListener('click' () => {
            Livewire.emit('store', data.coming.from.ui);
        });    
    });
</script>

Delete value from database with input checkbox[] using XMLrequest or fetch API

I am trying to delete data using checkboxes and the result is either nothing happens or Attempt to read property "id" on null Is it because the table is in a function, should I be placing checkbox input in the html file? and I am not quite sure how to connect the checkbox[] part with the requests. I am out of ideas…

button tag <button class="mass-btn" id="deleteBtn" > MASS DELETE</button>

The delete function..

$query = 'DELETE FROM ' . $this->table . 'WHERE id = :id'; 
$stmt = $this->conn->prepare($query);
$this->id = htmlspecialchars(strip_tags($this->id));
$stmt->bindParam(':id', $this->id);
$stmt->execute();

the delete.php

header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: DELETE');


include_once '../../config/database.php';
include_once '../../models/post.php';

//Instantiate db

$database = new Database();
$db = $database->connect();


//Instantiate post
$product = new Post($db);

//Get raw data

$data = json_decode(file_get_contents("php://input"));

$product->id = $data->id;



if($product->delete()) {
    echo json_encode(
        array('message' => 'Product Deleted')
    );
} else {
    echo json_encode(
        array('message' => 'Product Not Deleted')
    );
}

the table with input…

async function renderUser() {
        let users = await getUsers(); 
        let html = ``;

        users.forEach(user => {
            let htmlSegment = `
                <table class="box">
                    <tr> 
                    <th> <input type='checkbox' id='checkbox' name='checkbox[]'> </th>
                                       
                    <td>  ${user.sku}</td>
                    <td>  ${user.name}</td>
                    <td>  ${user.price}</td>
                    ${user.size ? `<td> Size: ${user.size} $ </td>` : ""} 
                    ${user.weight ? `<td> Weight: ${user.weight}  Kg</td>` : "" }
                    ${user.height ? `<td>  Height: ${user.height} CM</td>` : ""}
                    ${user.length ? `<td>  Length: ${user.length} CM</td>` : ""}
                    ${user.width ? `<td>  Width: ${user.width} CM</td>` : ""}
                    </tr>
                </table>`;

                html += htmlSegment;
        });

        let container = document.querySelector('.message');
        container.innerHTML = html;
    }
    renderUser();
  };

the XMLRequest and Fetch API attempt

    document.addEventListener('DOMContentLoaded',function(){
      document.getElementById('deleteBtn').onclick=function(){
           
           var req;
           req=new XMLHttpRequest();
           req.open('DELETE', '/api/post/delete.php');
           req.send();
          
           req.onload=function(){
           
            if (req.readyState === 4 && req.status == "204") {
              console.table(json);
            } else {
              console.error(json);
            }
            req.send(null);
             
          };
        };
      });

let btnDel = document.getElementById('#deleteBtn');

let deleteData = async () => {
    let response = await fetch ('../api/post/delete.php', {
      method: 'DELETE', 
      headers: {'Content-Type': 'application/json' },
      body: JSON.stringify(id)
    }) 
    try {
        let res = await fetch(url);
        return await res.json(); 
    } catch(error) {
            console.log(error);
        }
}

btnDel.addEventListener('click', deleteData);

React, PHP: blocked by CORS policy – Redirect is not allowed for a preflight request

I am trying to send request with Axios to my backend server (PHP 8.1) with this part of code

axios.post('https://mydomainfake.org/send_message.php', {
      email: getValues("email"),
    }).then(function (response) {
      console.log(response);
    })

and I receive every time this error message

Access to XMLHttpRequest at 'https://mydomainfake.org/send_message.php' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.

Any how how to send data successful?
And I am using cloudflare and have SSL from ZeroSSL
My cors on backend php server

<?php
header("Accept: *");
header("Content-Type: multipart/form-data");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT");
header('Content-Type: text/html; charset=utf-8');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

if (isset($_SERVER['HTTP_ORIGIN'])) {
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 86400');
}
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
        header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
        header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
}

and my package.json

{
  "name": "website",
  "version": "1.0.0",
  "private": true,
  "homepage": "/",
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": "",
  "dependencies": {
    "axios": "^0.27.2",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-scripts": "5.0.1",
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
  },
  }
}

RSS Feeds are not getti ng update automatically

I have set up a blog on a subdomain. like blog.mywebsite.com

And I have set up a recent posts widget using RSS Feed on my main website’s homepage.

I have managed to display the most recent 3 posts in that widget.

But now when I add a new post on the subdomain blog site that widget is not getting updated. It is showing only old posts.

I used this tutorial to set up the widget. https://www.worldoweb.co.uk/2012/display-wordpress-posts-on-another-wp-blog

The actual PHP Code I am using on my website is below.

<?php
//replace with your URL
$rss = fetch_feed('https://blog.mywebsite.com/feed/');

if (!is_wp_error($rss)) :

    $maxitems = $rss -> get_item_quantity(3); //gets latest 3 items This can be changed to suit your requirements
    $rss_items = $rss -> get_items(0, $maxitems);
endif;
?>
<?php
//shortens description
function shorten($string, $length) {
    $suffix = '&hellip;';
    $short_desc = trim(str_replace(array("r", "n", "t"), ' ', strip_tags($string)));
    $desc = trim(substr($short_desc, 0, $length));
    $lastchar = substr($desc, -1, 1);
    if ($lastchar == '.' || $lastchar == '!' || $lastchar == '?')
        $suffix = '';
        $desc .= $suffix;
    return $desc;
}
?>
<!--start of displaying our feeds-->
<ul class="rss-items" id="wow-feed">
<?php
        if ($maxitems == 0) echo '<li>No items.</li>';
        else foreach ( $rss_items as $item ) :
?>
<li class="item">
    <span class="data">
            <h3><a href='<?php echo esc_url($item -> get_permalink()); ?>' title='<?php echo esc_html($item -> get_title()); ?>'> <?php echo esc_html($item -> get_title()); ?></a></h3>
        <span class="date-image">&nbsp;</span>
            <div class="rtin-date"><?php echo $item -> get_date('F j, Y'); ?></div>
        <p class="rtin-content"><?php echo shorten($item -> get_description(), '120'); ?></p>
    </span>
</li>
<?php endforeach; ?>
</ul>

What I want to do is.

when i add new post to my blog it should show in that RSS widget too.

PHP: Cannot reference a class implementing an interface before its definition (but can without an interface)

When it comes to “access class before definition”: Why is php treating a standalone class differently from a class implementing an interface?
I thought the following code should work, but it doesn’t. (Tried with php 7.3.9 and 8.1.11, with or without namespaces…)
I know that the order of interface and class definitions is important in case of “extends” and “implements”, but this is a different issue here.

Is this a php ‘bug’ / inconsistency, or a specific language rule I oversighted?

<?php

// This works fine:
$a1 = new A();
// The following line causes error:
$b1 = new B();
// Fatal error: Uncaught Error: Class "B" not found in D:CodingPHPstrange.php:6

class A {}

interface I {}

class B implements I {}

// After the class definitions everything is fine (after commenting out line #6 of course)
$a2 = new A();
$b2 = new B();

Note: this old thread is somewhat similar, but not quite the same.

Go Daddy SMTP Error – SMTP connect() failed

I am using php mailer to generate and send automatic e-mails when a form is submitted on my web site which is run on GoDaddy. Since GoDaddy has changed their e-mail platform from Workspace to Office365 last week, my website stopped sending automatic e-mails, because host was changed, and since new host (Office365) required new settings (like different port number and SMTPSecure info). So I made some changes on my php code as following:

$mail->SMTPDebug = 2;

$mail->isSMTP();
$mail->Host = 'smtp.office365.com';
$mail->Username = '[email protected]';
$mail->Password = 'password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;

$mail->From = ('[email protected]');
$mail->addAddress('[email protected]');
$mail->FromName = 'myname';

After changing host to office365, SMTPSecure info to ‘tls’ and Port number to 587, I started to get the following error:

SMTP ERROR: Failed to connect to server: An attempt was made to access
a socket in a way forbidden by its access permissions. (10013)
2022-10-08 08:35:07 SMTP connect() failed

I have tried following ports: 25, 80, 465 and 587.
I have tried following SMTPSecure types: ‘tls’, ‘ssl’, ‘StartTLS’. But none of them worked.

I have also enabled SMTP authentication as advised in other answers. And tried all the alternative code snippets given in other questions but none of them worked.

Also, I have tried accessing my e-mail account and send automatic e-mail from Powershell. And it worked, so I think there is no issue with the e-mail account that I am using. So I’m thinking issue might be GoDaddy specific.

I have checked almost all of the questions and answers on websites but none of them worked. So I desperately need help to resolve this issue and start using my websites back. Any answer will be appreciated.

Thanks in advance.

how to show customer email address on the EZ-Pages in Zen Cart?

I Have codes as blow, but when I write them in EZ-page as code. php will not run, please help. thanks.

<?PHP
// Query the database for customers email address by (logged in) customer's ID
$email_results = $db->Execute('SELECT customers_email_address FROM customers WHERE 
customers_id = ' . $_SESSION['customer_id']);

// The customer's Email Address is now in the PHP variable $email_addr
$email_addr = $email_results->fields['customers_email_address'];
echo $email_addr;
?>

Omnipay how to handle notification webhooks from the payment gateways

I am working on a payment gateway driver for thephpleague/Omnipay. I am really struggling to implement a payment gateway driver that is off-site (i.e redirects the user to a payment provider page to complete payment). Now my payment provider returns the user back to my site but the payment is not complete and the payment for success or failure will be subsequent pushed to my site using registered web-hooks callbacks. I can not find good documentation on how to do these things when using Omnipay php package. I am asking the community for any help how to implement the omnipay payment gateway driver. Any any explanation of how omnipay is suppose to work will also be welcomed. Thank you.

Trying to load datatable from SQL Server query with where clause on PHP site using AJAX

I was following along Dani Krossing’s video to help with using AJAX for a SQL Server query (his video is for MySQL) as I have not used AJAX queries before. Hopefully, with some guidance on what I have done so far, it will end up a good lesson for me.

I am trying to build a webpage for our stock takes. The user selects the stock take they are querying from a dropdown menu (as below) and I want to use the StocktakeID as a parameter for the query to return the table of stock with the stocktakeID.

<form method="POST" action="loadstock.inc.php"> 
    <select name="filter_stocktake" id="filter_stocktake" class="form-control" required>
        <option value="">Select a stocktake:</option>               
        <?php         
        while ($row = sqlsrv_fetch_array($result)) {
        echo '<option value="' . $row["StocktakeID"] . '">' . $row["StocktakeName"] . '</option>';
        }
        ?>
    </select>
</form>

The loadstock.inc.php code below

if (isset($_POST['filter_stocktake']))
{
    $id = $_POST["filter_stocktake"];
    $query = "SELECT [Code], [Name], [BoxQty], [RecordedQuantityInStock],
                        [ActualQuantityInStock], [ActualQuantityEntered], [DiscrepancyNarrative],[Barcode], [QtySoldSinceSnapshot], [StocktakeCountShtItemID]
                    FROM [StockTakeStockSheet]
                    WHERE StocktakeID = '$id'";
    $stmt = $conn->sqlsrv_query($conn, $query);
    while ($row = sqlsrv_fetch_array($stmt)) {
        echo '
             <tr>
                 <td>' . $row["Code"] . '</td>
                 <td>' . $row["Name"] . '</td>
                 <td>' . $row["BoxQty"] . '</td>
                 <td>' . $row["RecordedQuantityInStock"] . '</td>
                 <td>' . $row["ActualQuantityInStock"] . '</td>
                 <td>' . $row["ActualQuantityEntered"] . '</td>
                 <td>' . $row["DiscrepancyNarrative"] . '</td>
                 <td>' . $row["Barcode"] . '</td>
                 <td>' . $row["QtySoldSinceSnapshot"] . '</td>
                 <td>' . $row["StocktakeCountShtItemID"] . '</td>
             </tr>
         ';
    }
        
}
else
{
    $id = null;
    echo "No stocktake ID supplied";
}

All I am getting when I submit the stocktake option is the “No stocktake ID supplied” message.

Below is the AJAX lines based on Dani Krossing’s video –

<script type="text/javascript" language="javascript" >
$(document).ready(function(){
    var stockID = '';
    $("button").click(function(e) {
        var button = $(e.relatedTarget)     
        var stocktakeID = button.data('stockID')
        $("#stock_data").load('includes/loadstock.inc.php', {
            filter_stocktake: stocktakeID
        });
    });
});
</script>

Am I very far away from getting this right? If you had any guidance or resources that you believe would help me get over the line, I would be really appreciative.

If I have left anything out or you require more details, let me know.

Thank you!

acess variable in sub function

I made this function and observed there was an issue during it execution.
I’m not able to get the result of $names_from_source inside the sub function.
There is no error, it detects the variable but it value is always NULL.

/*
source: array of MyObject
copy: array of MyObject
return: return duplicated objects based on name
*/
function get_all_duplicated($source, $copy) {
    $names_from_source = array_map(fn($obj): string => $obj->name, $source);
    var_dump($names_from_source); // return list of names
    return array_filter($copy, function($obj) {
        global $names_from_source;
        var_dump($names_from_source); // return NULL
        return in_array($obj->name, $names_from_source);
    });
}

Why?
Thanks