1

i'm trying to make custom ajax handler because the admin-ajax.php is taking to long to handle ajax requests from 7s to 10s so i google it and mange to do some custom ajax-handler.php like this

<?php
if (is_ajax_request()) {
    if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists
        $action = $_POST["action"];
        switch($action) { //Switch case for value of action
            case "test": test_function(); break;
        }
    }
}

//Function to check if the request is an AJAX request
function is_ajax_request() {
    return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}

function test_function()
{
    $response = wc_get_product(1463);
    header('Content-Type: application/json');
    echo json_encode($response);
    die();
}

and i send first the response as text $response = "test" and the ajax call was taking 300ms but when trying to call function from another file like $response = wc_get_product(1463); it throws an error in the response Fatal error: Call to undefined function wc_get_product() in C:\wamp\www\.... and i tried to make custom wordpress ajax handel using this ajaxflow plugin but it the same thing so please please how can i call the functions from another files and many thanks in advance for any help.

  • 1
    just don't do it. if your ajax is slow then fix the slowness instead of trying to recreate the wheel – Mark Kaplun Jan 4 '16 at 18:14
  • the default admin-ajax.php handler is taking too much time when even when the response is very small like $response = "test" – Fadi Jan 4 '16 at 18:26
  • Use the REST API as an alternative – jgraup Jan 4 '16 at 23:15
  • Then as @MarkKaplun says, get better hosting or pin down whatever the cause of slowness is. – Andy Macaulay-Brook Sep 24 '16 at 8:37
-1

You have to include WP core function files, something like this...

<?php
//mimic the actuall admin-ajax
define('DOING_AJAX', true);

if (!isset( $_POST['action']))
    die('-1');

//make sure you update this line 
//to the relative location of the wp-load.php
require_once('../../../../../wp-load.php'); 

//Typical headers
header('Content-Type: text/html');
send_nosniff_header();

//Disable caching
header('Cache-Control: no-cache');
header('Pragma: no-cache');

You can read more about this here https://coderwall.com/p/of7y2q/faster-ajax-for-wordpress or here https://wp-dreams.com/articles/2014/03/better-ajax-handler-for-wordpress-super-fast-ajax/.

  • 1
    it is always wrong to guess where wordpress is installed and include files based on that – Mark Kaplun Apr 29 '18 at 5:45

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.