• Status: Solved
  • Priority: High
  • Security: Public
  • Views: 56
  • Last Modified:

AJAX not returning in Wordpress

I am trying to make an AJAX Call in Wordpress and I am not having any luck.  The console shows all of the returns but they are not being printed out on the page.
<script>
jQuery(document).ready(function($) {

	// Listen for a click event on our text input submit button
	$( '.wcsf-submit-field' ).click( function( e ) {

		// Stop the button from submitting and refreshing the page.
		e.preventDefault();

		// Now that a click has happened, let's run Ajax!!!!!!!!!
		$.ajax({
			type: 'POST',
			dataType: 'json',
			url: wcsf_ajax.ajaxurl,
			data: {
				'action' : 'wcsf_ajax',
				//'data' : $( '.wcsf-text-field' ).val(),
				//'submission' : $( '.wcsf-submitted' ).val(),
				//'nonce' : $( '#wcsf-nonce' ).val(),
			},
			success: function( data ) {
				$( '#load_returns' ).html(data);
                                console.log(data);
			}
		});
	});
});

<?php

class WCSF_Example {

    /**
     * The construct method. This is where we hook all of our scripts outlined below.
     */
    public function __construct() {
        // Enqueue our ajax with WordPress
        add_action('wp_enqueue_scripts', array($this, 'add_javascript'));
        // Hook our Ajax script with the action we specified in the ajax request
        add_action('wp_ajax_wcsf_ajax', array($this, 'wcsf_ajax'));
        // Add our input/button at the end of the_content() function
        add_filter('the_content', array($this, 'add_button'));
    }

    /**
     * Enqueue our JavaScriptssssss
     */
    public function add_javascript() {
        // Enqueue our jQuery. You never know if an install is loading it!
        wp_enqueue_script('jquery');
        // Call our script that contains the Ajaxy goodness.
        wp_enqueue_script('wcsf_exmaple_ajax', plugins_url('js/ajax.js', __FILE__));
        // Although used for translation, this function allows us to load arbitrary JS built with PHP into the head of our WP theme
        // Without modifying the themes header.php :) #magix
        // We only need the admin ajax file in WordPress, so that's all we'll do.
        wp_localize_script('wcsf_exmaple_ajax', 'wcsf_ajax', array(
            'ajaxurl' => admin_url('admin-ajax.php'),
        ));
    }

    /**
     * The actual script to process the Ajax request.
     * This function is called when we pass the "action" key through $_POST and WordPress will map that to the proper add_action().
     * We'll process and then return the data in JSON form. Make sure you sanitize yo data! Safty first.
     */
    public function wcsf_ajax() {
        // Check that we requested this from the input field and the nonce is valid. Prevents malicious users.
        //if (!isset($_POST['submission']) && !$_POST['submission'] && !wp_verify_nonce($_POST['nonce'], 'wcsf-ajax'))
               
                     global $wpdb;
header('Content-Type: application/json');
ob_start();
        $get_id = $wpdb->get_results('SELECT term_id AS id, name AS name FROM wp_connections_terms WHERE term_id != 1');
        foreach ($get_id as $row) {
            $name = $row->name;
            $id = $row->id;

            $taxid = $wpdb->get_results("
          SELECT wp_connections_meta.meta_value AS value 
          FROM wp_connections_term_relationships, wp_connections_meta 
          WHERE wp_connections_term_relationships.term_taxonomy_id = '$id' AND (wp_connections_term_relationships.entry_id = wp_connections_meta.entry_id)"
            );

            $value = array();
            foreach ($taxid as $row) {
                $val = $row->value;
                $value[] = $val;
            }
            echo 'Sales Manager: ' . $name . '&nbsp;&nbsp;$' . array_sum($value) . '<br /><br />';
           
        }
         $data = ob_get_clean();  
      wp_send_json_success($data);
       
        wp_die();
     
    }

    /**
     * Add our input/button at the end of the_content() function
     */
    public function add_button() {
        echo '<form id="wcsf-example">';
        echo '<input type="text" class="wcsf-text-field" placeholder="Add your text" value="">';
        echo '<input type="submit" class="wcsf-submit-field" value="Add yo text!" />';
        echo '<input type="hidden" name="wcsf-submitted" class="wcsf-submitted" value="true" />';
        wp_nonce_field('wcsf-ajax', 'wcsf-nonce'); // Adds our nonce and creates a unique key automatically! #moremagix
        echo '</form>';
    }

}

// Initiate our class.
$wcsf_example = New WCSF_Example();

Open in new window

0
rgranlund
Asked:
rgranlund
  • 2
1 Solution
 
Leonidas DosasCommented:
How the php code is triggered?I mean I cant see any if isset $_POST['action']
0
 
rgranlundAuthor Commented:
I actually figured it out.  I forgot to us ob_start so it ws not looping the way WP wants it to.  Thanks!
0
 
rgranlundAuthor Commented:
Thanks for your help.  I got what I needed.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Introducing Cloud Class® training courses

Tech changes fast. You can learn faster. That’s why we’re bringing professional training courses to Experts Exchange. With a subscription, you can access all the Cloud Class® courses to expand your education, prep for certifications, and get top-notch instructions.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now