1

I need the data from var search_value in msearch.js to pass to the php variable called $woot in the child theme functions.php file so it can be the returned value for wtfwoot() and therefore used for other functions. I know I am close, but I am missing something important.

I've already tried other suggestions that use "echo" and wp_die(), but solutions that include these do not work. I have also tried dataType: 'json' in the AJAX array, but I'm not sure if I decoded it properly in the wtfwoot() function.

//Wordpress Hooks (in child theme functions.php file near the top):

add_action( 'wp_enqueue_scripts', 'mSearch' );

function mSearch() {
        wp_enqueue_script( 'msearchjs', get_stylesheet_directory_uri() . '/msearch.js', array( 'jquery' ),'',true );
        wp_localize_script('msearchjs', 'sAjax', array(
            'ajaxurl' => admin_url('admin-ajax.php')
        ));
}

add_action( 'wp_ajax_wtfwoot', 'wtfwoot' );
add_action( 'wp_ajax_nopriv_wtfwoot', 'wtfwoot' );

//HTML (front end Wordpress page):

<form id="srch" method="post" enctype="multipart/form-data" action="msearch.js">

<input class="membersearch" placeholder="Search" id="membersearch" type="text" name="smemb">

<input class="searchsubmit" type="submit"  value="SUBMIT"></form>

//JS/AJAX file called msearch.js (in same directory as child theme functions.php):

function msearchjs(e) {

    var nack = 'NO';
    var search_value = $('#membersearch').val();
    var url = sAjax.ajaxurl;

    if(search_value == '') {

        console.log(nack);

    } else {

        $.ajax ({
            type: 'POST',
            url: sAjax.ajaxurl,
            data: {
                'action': 'wtfwoot',
                'svalue': search_value
            },
            success: function(data) {
                console.log(data);
            },
            error: function() {
                console.log('ERROR');
            }

        });
}
e.preventDefault();

};

$(document).submit( '#srch', msearchjs);

//PHP function (in same child theme functions.php file as the hooks but near the bottom):

function wtfwoot() {

    if (isset($_POST)) {

        $woot = $_POST;

        var_dump($woot);

    } else {

        return 'Not working!';

    }
}

Input data is not passing to the PHP function. The var_dump in wtfwoot() returns array(0) { }.

Console.log(data) shows:

array(2) { ["action"]=> string(7) "wtfwoot" ["svalue"]=> string(6) "Dallas" } 0

ADMIN-AJAX.PHP:

<?php
/**
 * WordPress Ajax Process Execution
 *
 * @package WordPress
 * @subpackage Administration
 *
 * @link https://codex.wordpress.org/AJAX_in_Plugins
 */

/**
 * Executing Ajax process.
 *
 * @since 2.1.0
 */
    define( 'DOING_AJAX', true );
    if ( ! defined( 'WP_ADMIN' ) ) {
    define( 'WP_ADMIN', true );
}

/** Load WordPress Bootstrap */
require_once( dirname( dirname( __FILE__ ) ) . '/wp-load.php' );

/** Allow for cross-domain requests (from the front end). */
send_origin_headers();

// Require an action parameter
if ( empty( $_REQUEST['action'] ) ) {
    wp_die( '0', 400 );
}

/** Load WordPress Administration APIs */
require_once( ABSPATH . 'wp-admin/includes/admin.php' );

/** Load Ajax Handlers for WordPress Core */
require_once( ABSPATH . 'wp-admin/includes/ajax-actions.php' );

@header( 'Content-Type: text/html; charset=' . get_option( 'blog_charset' ) );
@header( 'X-Robots-Tag: noindex' );

send_nosniff_header();
nocache_headers();

/** This action is documented in wp-admin/admin.php */
do_action( 'admin_init' );

$core_actions_get = array(
'fetch-list',
'ajax-tag-search',
'wp-compression-test',
'imgedit-preview',
'oembed-cache',
'autocomplete-user',
'dashboard-widgets',
'logged-in',
);

$core_actions_post = array(
'oembed-cache',
'image-editor',
'delete-comment',
'delete-tag',
'delete-link',
'delete-meta',
'delete-post',
'trash-post',
'untrash-post',
'delete-page',
'dim-comment',
'add-link-category',
'add-tag',
'get-tagcloud',
'get-comments',
'replyto-comment',
'edit-comment',
'add-menu-item',
'add-meta',
'add-user',
'closed-postboxes',
'hidden-columns',
'update-welcome-panel',
'menu-get-metabox',
'wp-link-ajax',
'menu-locations-save',
'menu-quick-search',
'meta-box-order',
'get-permalink',
'sample-permalink',
'inline-save',
'inline-save-tax',
'find_posts',
'widgets-order',
'save-widget',
'delete-inactive-widgets',
'set-post-thumbnail',
'date_format',
'time_format',
'wp-remove-post-lock',
'dismiss-wp-pointer',
'upload-attachment',
'get-attachment',
'query-attachments',
'save-attachment',
'save-attachment-compat',
'send-link-to-editor',
'send-attachment-to-editor',
'save-attachment-order',
'heartbeat',
'get-revision-diffs',
'save-user-color-scheme',
'update-widget',
'query-themes',
'parse-embed',
'set-attachment-thumbnail',
'parse-media-shortcode',
'destroy-sessions',
'install-plugin',
'update-plugin',
'crop-image',
'generate-password',
'save-wporg-username',
'delete-plugin',
'search-plugins',
'search-install-plugins',
'activate-plugin',
'update-theme',
'delete-theme',
'install-theme',
'get-post-thumbnail-html',
'get-community-events',
'edit-theme-plugin-file',
'wp-privacy-export-personal-data',
'wp-privacy-erase-personal-data',
'health-check-site-status-result',
'health-check-dotorg-communication',
'health-check-is-in-debug-mode',
'health-check-background-updates',
'health-check-loopback-requests',
'health-check-get-sizes',
);

// Deprecated
$core_actions_post_deprecated = array( 'wp-fullscreen-save-post', 'press-this-save-post', 'press-this-add-category' );
$core_actions_post            = array_merge( $core_actions_post, 
$core_actions_post_deprecated );

// Register core Ajax calls.
if ( ! empty( $_GET['action'] ) && in_array( $_GET['action'], $core_actions_get ) ) {
    add_action( 'wp_ajax_' . $_GET['action'], 'wp_ajax_' . str_replace( '-', '_', $_GET['action'] ), 1 );
}

if ( ! empty( $_POST['action'] ) && in_array( $_POST['action'], 
$core_actions_post ) ) {
add_action( 'wp_ajax_' . $_POST['action'], 'wp_ajax_' . str_replace( '-', '_', $_POST['action'] ), 1 );
}

add_action( 'wp_ajax_nopriv_heartbeat', 'wp_ajax_nopriv_heartbeat', 1 );

$action = ( isset( $_REQUEST['action'] ) ) ? $_REQUEST['action'] : '';

if ( is_user_logged_in() ) {
    // If no action is registered, return a Bad Request response.
    if ( ! has_action( "wp_ajax_{$action}" ) ) {
        wp_die( '0', 400 );
    }

/**
 * Fires authenticated Ajax actions for logged-in users.
 *
 * The dynamic portion of the hook name, `$action`, refers
 * to the name of the Ajax action callback being fired.
 *
 * @since 2.1.0
 */
    do_action( "wp_ajax_{$action}" );
} else {
// If no action is registered, return a Bad Request response.
    if ( ! has_action( "wp_ajax_nopriv_{$action}" ) ) {
        wp_die( '0', 400 );
    }

    /**
     * Fires non-authenticated Ajax actions for logged-out users.
     *
     * The dynamic portion of the hook name, `$action`, refers
     * to the name of the Ajax action callback being fired.
     *
     * @since 2.8.0
     */
    do_action( "wp_ajax_nopriv_{$action}" );
}
// Default status
wp_die( '0' );
12
  • Where does sAjax.ajaxurl come from? Have you verified if the AJAX requests are sending and receiving? Commented Sep 16, 2019 at 21:34
  • sAjax.ajaxurl is defined in the hook...the path that is generates goes to wp-admin/admin-ajax.php and it does so properly. I just need the ajax request to pass the form data to the php function. I don't need it to send a request back. The data is not passing to the function. Commented Sep 16, 2019 at 21:42
  • I don't understand. You're saying sAjax.ajaxurl is defined properly but how do you know? The URL is really the only issue you could have there. Commented Sep 16, 2019 at 22:09
  • h ttp://thedomain.net/wp-admin/admin-ajax.php (without the space)...is it possible it isn't firing because I don't have an SSL installed yet? Commented Sep 16, 2019 at 22:23
  • 1
    Oh wait..you may be right...it is hitting the primary domain admin-ajax.php and not the addon domain admin-ajax.php. Two sets of eyes are better than one. Let me test and reply with my findings. Commented Sep 16, 2019 at 22:27

2 Answers 2

1

Looks like you've worked out how to receive the POST request. In order to send a response back, that all depends on what format is needed. I'd recommend JSON. Give this a try.

$.ajax({
  type: 'POST',
  dataType: 'json',
  url: sAjax.ajaxurl,
  data: {
    'action': 'wtfwoot',
    'svalue': search_value
  },
  success: function(data) {
    console.log(data);
  },
  error: function() {
    console.log('ERROR');
  }
});

// you may need to pass $_POST as an argument here
function wtfwoot() {
  if (isset($_POST['svalue'])) {
    // you need to validate & sanitize the $_POST values here
    $woot = $_POST;
    // process $_POST and return what you need
    return json_encode($woot);
  } else {
    return json_encode(['error' => "POST was empty!"]);
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

I see what you are doing there, but I actually don't need a response sent back to the browser. I need to be able to save the value of $_POST['svalue']; on the server side (outside of the AJAX function as you said earlier) so that I can pass it to other php shortcode functions by adding a variable such as $inputvalue = wtfwoot(); to each of those functions. But wtfwoot(); as the ajax function doesn't allow me to return the value on the server side. I'm starting to think that ajax isn't the right route, even tho it is recommended. I've been working on this for days.<pulls hair>
@Shay - If you do var_dump("response"); at the top of admin-ajax.php do you see it in the ajax response?
No...and the ajax throws an error: 'error: function() {console.log('ERROR');}' I have added admin-ajax.php to my original post.
0

@EternalHour I'm going to close this thread. When I originally created the form and functions, I was able to call $_POST['value'] and return it in one of my php functions. But that suddenly stopped working a few weeks ago. Suddenly, it has started working again. Your help was just fantastic and it helped me understand better ajax and json. I believe this thread offers a lot more then others like it. Moving forward, I am going to consider rewriting the application using a REST API solution, a whole 'nother learning experience for me.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.