Priority call methods – PHPMailer->addAddress(NULL)

You’re trying to use $instance in your deliver_mail method, but that variable doesn’t exist in that method. To get that variable, you need to be inside the widget function, but that’s not possible. That function is only called when an instance of that widget is being displayed, which will never happen in an Admin AJAX call.

The problem is that my deliver_mail() method has been executed first
and it gives me “Uncaught phpmailerException: Invalid
address:…PHPMailer->addAddress(NULL)”

This would explain the mistake however, the request that handles the AJAX request, and calls PHPMailer, is a completely different request to the one that renders/saves the widget. They might as well be running on completely different machines, remember, PHP requests aren’t like Node/Java/Python web apps, each request starts from a blank slate. It has nothing to do with the order the functions are called, because no request calls both functions to begin with

Additionally, adding Admin AJAX handlers in a WP_Widget based object like this is extremely unusual.

So:

  • First, separate your ajax handlers out of the widget object. They don’t belong there
  • Second, you need to send everything that’s needed along with the request
  • Thirdly, you can’t store the email that the form mails in the widget, because you have no way of knowing which widget sent the request

Sending the email in the request, would allow attackers to use your contact form to email anybody anything using your server as a relay, which would get you quickly blacklisted ( amongst other things ), so that’s not an option.

Instead you could store the recipient:

  • In an option
  • Attached to a post, select the post in the widget and pass the post ID along so that the callback can handle it

Additionally, I see you use the old Admin AJAX request, is there a specific reason you didn’t use the simpler/easier/newer REST API?