0

I'm trying to use a function in wordpress for both direct and ajax implementation but it doesn't seem to work because it has arguments. When I remove the arguments from the function, the ajax call works fine but with them I get a "500 (internal server error).

PHP:

add_action('wp_ajax_nopriv_example_function', 'example_function');
add_action('wp_ajax_example_function', 'example_function');    
function example_function($foo) {
    if (is_null($foo)) {
        $foo = $_POST["foo"];
    }
    echo $foo;
}

JS:

$(document).on("change", "select", function(){
   $foo = 'test';
   $.ajax({
      ajax_object.ajax_url,
      type: 'post',
      data: { action: 'example_function', foo: $foo },
      success: function(html) {
        $(div).append(html);
      }
   });
});
user300979
  • 389
  • 1
  • 4
  • 18
  • 3
    It seems like you've mixed up PHP and JavaScript code? – Dan May 24 '18 at 09:56
  • How exactly have I done that? – user300979 May 24 '18 at 09:58
  • I don't know anything about Wordpress programming, but everything past line 10 is JavaScript code and needs to be in the template. – Dan May 24 '18 at 10:01
  • A 500 error means that a server error occurred. This is most likely an error in your PHP-code. To see the _actual_ error message, check your servers error log. You can also change how PHP displays errors and tell it to show all errors directly on the screen (this is not something you want in production though, since it can show sensitive data, but during development, you should). Here's how to show all errors and warnings: https://stackoverflow.com/questions/5438060/showing-all-errors-and-warnings – M. Eriksson May 24 '18 at 10:03
  • 1
    My bet is that you've defined a required argument in your `example_function()` while those callbacks doesn't actually pass any argument. Try to define the callback as: `function example_function($foo = null) { //your code }`. – M. Eriksson May 24 '18 at 10:05

0 Answers0