0

Please help. I have a simple plugin which uses ajax call. When I call another function within ajax php function (in the below example I am calling get_cat() function from update_passage_list() function) I am getting "Failed to load resource: the server responded with a status of 500 (Internal Server Error)" error.

quiz.js:

$jq =jQuery.noConflict();

$jq(document).ready(function($jq) {
    update_passage_list(32);
});

var update_passage_list = function(id){
    $jq.post(quiz.ajaxURL, {
        action:"update_passage_list",
        nonce:quiz.quizNonce,
        cpid : id
    }, function(return_data) {
        alert('Return Data = ' + return_data);
    }, "json");  
};

index.php:

<?php

/*
  Plugin Name: WP Quiz
  Plugin URI: -
  Description: Plugin description.
  Author: Author Name
  Version: 1.0
  Author URI: url
 */

class WP_Quiz {

    public $plugin_url;

    public function __construct() {
        $this->plugin_url = plugin_dir_url(__FILE__);

        add_action('admin_enqueue_scripts', array($this, 'wpq_admin_scripts'));

        add_action('wp_ajax_nopriv_update_passage_list', array($this, 'update_passage_list'));
        add_action('wp_ajax_update_passage_list', array($this, 'update_passage_list'));
    }

    function wpq_admin_scripts() {
        wp_enqueue_script('jQuery');
        wp_register_script('quiz-admin', plugins_url('js/quiz.js', __FILE__), array('jquery'));
        wp_enqueue_script('quiz-admin');

        $config_array = array(
            'ajaxURL' => admin_url('admin-ajax.php'),
            'quizNonce' => wp_create_nonce('quiz-nonce'),
            'plugin_url' => $this->plugin_url
        );

        wp_localize_script('quiz-admin', 'quiz', $config_array);
    }

    public function get_cat($id) {
        $new_id = $id + 100;
        return $new_id;
    }

    function update_passage_list() {
        $cpid = $_POST['cpid'];
        $cpid = get_cat($cpid);
        echo $cpid;
        die();
    }
}

$quiz = new WP_Quiz();
  • When you get 500 error, the server should have logged the real error in the server PHP error log, check that first. – Milan Petrovic Jun 30 '18 at 18:27
2

I am calling get_cat() function from update_passage_list() function

This is what you're doing:

$cpid = get_cat($cpid);

There's nothing there that says that get_cat() is a method of your class. It's trying to find a function get_cat() outside any class. To use the method of the class you need to use $this:

$cpid = $this->get_cat($cpid);
  • one more question if I want to return string from get_cat() function I am not getting the value. I am not sure what I am missing? thanks – user146122 Jun 30 '18 at 14:27
  • Never mid, echo json_encode('string'); did the trick. Thank you again. – user146122 Jun 30 '18 at 14:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.