jQuery AJAX POST not working in PHP 8
-
I have very limited PHP knowledge – trying to help a client solve a coding issue with their WordPress site. This AJAX POST worked in PHP 7.4 but throws an error in PHP 8.
Their site allows users to purchase license keys which grant access to an online training and certification program. Certain users can buy bulk licenses and then assign those licenses to others (usually their employees) through a form. It’s this form that is no longer successfully posting AJAX data in PHP 8 to activate the license key using the $.ajax() method. It returns a 500 Internal Server Error with the response of “SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data.” The intended result is that the license key included on the form should be activated, a new user profile created for the student/employee entered on the form, and the activated license key assigned to them. Here’s an abbreviated version of the code, which is included in a custom plugin installed on the site:
(function ($) { var addStudentForm = $('.student-submission-form'); var addStudentButton = $('.student-submission-form .gform_button'); var urlBase = window.location; var urlSiteBase = urlBase.origin; var licenseString = '/wp-admin/admin-ajax.php?action=license_key_activate'; //evaluate/activate license addStudentButton.click(function (event) { //if any fields are empty don't fire functions if (!(productSku == '' || firstName == '' || lastName == '' || email == '' || lKey == '')) { // get all form inputs into array var studentArray = $('.student-submission-form input').map(function () { return $(this).val(); }).get(); // evaluate/activate license activateLicense(); } else { } //activate license function called above function activateLicense() { $.ajax({ url: urlSiteBase + licenseString, type: 'POST', data: { 'store_code': 'XXXXXX', 'sku': productSku, 'license_key': theKeyField }, success: function (resp) { }, error: function (xhr, ajaxOptions, thrownError) { alert(xhr.status); alert(thrownError); } }); } }); })(jQuery);
Oddly, I’ve discovered that if I modify the “activation endpoint” in line 6 to point to the logged-in user’s account page at “/my-account?action=license_key_activate”, I can kind of get the process to function… It will attempt to post the ajax data to that URL and then redirect itself to “/wp-admin/admin-ajax.php” where it hangs. But if I reload the page and resubmit the form, it works and continues to work for all subsequent submissions during that user’s logged-in session.
One other note… The license key creation and assignment functions are being handled through the License Keys For WooCommerce plugin which seems like it might be abandoned. We’re hoping to temporarily find a solution to this issue without having to switch to a different license key management plugin and rebuild this whole workflow.
Appreciate any insight anyone can provide.
- The topic ‘jQuery AJAX POST not working in PHP 8’ is closed to new replies.