changed permalink structure and now ajax functions are broken

Question

I changed the permalinks from /%category%/%postname%/ to just /%postname%/ and now my custom ajax function returns a 500 error. The exact message I get in the console is:

Failed to load resource: the server responded with a status of 500 () /wp-admin/admin-ajax.php:1

Even if I change it back to /%category%/%postname%/ it still doesnt work.

I have made no other changes to the ajax javascript or the underlying PHP script that sends results to the ajax function.

I read in another post that the URL to the admin-ajax.php has changed and that I need to update it in my functions for the ajax. But Im not sure what/if its changed or changed to.

Here is the PHP that enques the ajax scripts:

function my_script_enqueuer() {
   wp_register_script( "snek_results", get_template_directory_uri() . '-child/js/results.js', array('jquery') );
   wp_localize_script( 'snek_results', 'snek_results', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));        

   wp_enqueue_script('jquery', false, array(), false, false);
   wp_enqueue_script( 'snek_results');

}

Here is the AJAX functions:

jQuery(document).ready(function($) {
  $('#game').on('submit', function(event) {
    event.preventDefault(); // Prevent the form from submitting the traditional way

    // Capture the values from the selected radio buttons for choice and bet
    var choice = $("input[name="choice"]:checked").val();
    var bet = $("input[name="bet"]:checked").val();
    
    if (choice && bet) {
      // Now call your AJAX function with the user's input
      getDiceRollResults(choice, bet);
    } else {
      $('#results').html('Please select both a choice and a bet');
    }
  });

  function getDiceRollResults(choice, bet) {
    $.ajax({
      url: snek_results.ajaxurl, // Use localized script object
      type: 'POST',
      data: {
        action: 'roll_dice',
        choice: choice,
        bet: bet,
      },
      success: function(response) {
        var jsonResponse = JSON.parse(response);
        if (jsonResponse.status === 'winner') {
          $('#results').html('You won! Your prize is ' + jsonResponse.prize);
        } else if (jsonResponse.status === 'loser') {
          $('#results').html('You lost! Try again.');
        } else if (jsonResponse.status === 'error') {
          $('#results').html('Error: ' + jsonResponse.message);
        }
      },
      error: function() {
        $('#results').html('AJAX error');
      },
    });
  }
});

Everything worked fine until I messed with the permalinks.

Thanks!

0
jon 2 months 2023-09-23T17:06:57-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse