Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'm having problems with some "contact form" plugins whose use Ajax. The problem is that I use Ajax to call the plugin. Then the plugin is loaded, but when I try to submit the form, I'm redirected to this URL: SITE/wp-admin/admin-ajax.php, when it should send the Ajax request, and only a 0 is printed on the window.

I think I'm using Ajax correctly:

functions.php:

function theme_name_scripts() {

    wp_enqueue_script( 'mi-script-ajax',get_bloginfo('stylesheet_directory') . '/js/ajax-search.js', array( 'jquery' ) );
    wp_localize_script( 'mi-script-ajax', 'MyAjax', array( 'url' => admin_url( 'admin-ajax.php' ) ) );
}


function llamadaAjax_callback() {
    $pageId = 0;
    $newSlug = '';
    $reviewSlug = '';
    $sPostType = 'any';
    $sTemplatePart = '';
    $sTaxonomy= false;

    //Busqueda
    if( isset(  $_POST['search'] ) ) {
        $sTemplatePart = 'search-ajax';
        $sPostType = 'any';
    }
    //Links
    elseif( isset(  $_POST['href'] ) ) {
        $pageId = preg_match( '/^http:\/\/.+\/\?page_id=\d+$/', $_POST['href'] ) ? substr( strrchr( $_POST['href'], '=' ), 1 ) : 'no-page' ;
        if( $pageId === 'no-page' && preg_match( '/^http:\/\/.+\/\?(news|reviews|entrevistas|radio_shows|podcasts|cat|tag)=[a-zA-Z0-9\-]+$/', $_POST['href'] ) ) {
            $newSlug = substr( strrchr( $_POST['href'], '=' ), 1 );
        } elseif( $pageId === 'no-page' && preg_match( '/^http:\/\/.+\/\?(artistas|sellos|generos)=[a-zA-Z0-9\-]+$/', $_POST['href'] ) ) {
            $sTaxonomy = true;
        }
        //$pageName = get_page_template_slug( intval( $pageId ) );
        if( $pageId !== 'no-page' ) {
            if( $pageId === '8' ) {
                $sPostType = 'any';
                $sTemplatePart = 'home-ajax';
            } elseif( $pageId === '22' ) { 
                $sPostType = 'reviews';
                $sTemplatePart = 'reviews-rvw-ajax';
            } elseif( $pageId === '6' ) {
                $sPostType = 'news';
                $sTemplatePart = 'noticias-news-ajax';
            } elseif( $pageId === '109' ) {
                $sPostType = 'entrevistas';
                $sTemplatePart = 'entrevistas-ajax';
            } elseif( $pageId === '112' ) {
                $sPostType = 'radio-shows';
                $sTemplatePart = 'radio-shows-ajax';
            } elseif( $pageId === '412' ) {
                $sTemplatePart = 'podcasts-ajax';
            } elseif( $pageId === '415' ) {
                $sTemplatePart = 'contacto-ajax';
            }

        } elseif( $sTaxonomy === true ) {
            $sTemplatePart = 'reviews-rvw-ajax';
            $sPostType = 'reviews'; 
        } elseif( $newSlug !== '' ) {
            $sTemplatePart = 'single-ajax';
            $sPostType = 'any';
            if( preg_match( '/^http:\/\/.+\/\?cat=\d+$/', $_POST['href'] ) ) {
                 $sTemplatePart = 'category-ajax';  
                 $sPostType = 'category';       
            } elseif( preg_match( '/^http:\/\/.+\/\?tag=[A-Za-z0-9\-]+$/', $_POST['href'] ) ) {
                 $sTemplatePart = 'tags-ajax';  
                 $sPostType = 'tag';        
            }

            //get_template_part( 'single-ajax' );
        }

    //Siguiente y Anterior
    } elseif( isset( $_POST['cadenaAll'] ) && ( isset( $_POST['cadenaPrev'] ) || isset( $_POST['cadenaNext'] ) ) ) {
        if( isset(  $_POST['pageName'] ) ) {
            if( $_POST['pageName'] === 'reviews' ) {
                $sPostType = 'reviews';
                $sTemplatePart = 'next_reviews-rvw-ajax';
            }
            elseif( $_POST['pageName'] === 'news' ) {
                $sPostType = 'news';
                $sTemplatePart = 'next_noticias-news-ajax';
            }
            elseif( $_POST['pageName'] === 'entrevistas' ) {
                $sPostType = 'entrevistas';
                $sTemplatePart = 'next_entrevistas-ajax';
            }
            elseif( $_POST['pageName'] === 'radio-shows' ) {
                $sPostType = 'radio-shows';
                $sTemplatePart = 'next_radio-shows-ajax';
            }
            elseif( $_POST['pageName'] === 'podcasts' ) {
                $sPostType = 'podcasts';
                $sTemplatePart = 'next_podcasts-ajax';
            }
            elseif( $_POST['pageName'] === 'categories' ) {
                $sPostType = 'category';
                $sTemplatePart = 'next_categories-ajax';
            }
            elseif( $_POST['pageName'] === 'tags' ) {
                $sPostType = 'tag';
                $sTemplatePart = 'next_tags-ajax';
            }
            elseif( $_POST['pageName'] === 'search' ) {
                $sPostType = 'any';
                $sTemplatePart = 'next_search-ajax';
            }
        }
    }


    //Submenu
    echo '<div id="submenu"><ul>';
    if( $sPostType !== '' ) {
        if( $sPostType == 'any' || $sPostType == 'category' || $sPostType == 'tag' ) {
            $allCategories = get_categories();
            foreach( $allCategories as $cat ) {
                echo '<li class="type-category"><a href="' . get_category_link( $cat->cat_ID ) . '">' . $cat->name . '</a></li>'; 
            }
        } else {

            global $wpdb;
            // set the target relationship here
            $post_type = $sPostType;
            $taxonomy = 'category';

            $terms_ids = $wpdb->get_col( $wpdb->prepare( "
                SELECT
                    tt.term_id
                FROM
                    {$wpdb->term_relationships} tr,
                    {$wpdb->term_taxonomy} tt,
                    {$wpdb->posts} p
                WHERE 1=1
                    AND tr.object_id = p.id
                    AND p.post_type = '%s'
                    AND p.post_status = 'publish'
                    AND tr.term_taxonomy_id = tt.term_taxonomy_id
                    AND tt.taxonomy ='%s'
                ", $post_type, $taxonomy ) );

            $terms = get_terms( $taxonomy, array(
                'include' => $terms_ids,
                'orderby' => 'name',
                'order' => 'ASC'
            ) );


             //$aTypeCategories = get_categories( array( 'post_type' => $type, 'number' => '10'  ) );
             foreach( $terms as $cat ) {
                echo '<li class="type-category"><a href="' . get_category_link( $cat->term_id ) . '">' . $cat->name . '</a></li>'; 
             }
        }
    } else {
        echo '<li class="type-category" style="color: transparent">Sin categorías</li>'; 
    }
    echo '</ul></div>';
    if( $sTemplatePart ) get_template_part($sTemplatePart);
}

add_action( 'wp_enqueue_scripts', 'theme_name_scripts' );
add_action('wp_ajax_llamadaAjax', 'llamadaAjax_callback');
add_action('wp_ajax_nopriv_llamadaAjax', 'llamadaAjax_callback');

and in the /js/ajax-search.js file:

jQuery(document).ready(function($) {

    var linksPages = $('.menu-menu-container a');

    linksPages.on('click',function(e){
                e.preventDefault();
                $('#content').addClass('cortinaOut');
                if( !$(this).attr('href').match(/=8$/) ) {
                    $('#slider').fadeOut(800);
                }
                jQuery.post(MyAjax.url, {action : 'llamadaAjax' ,href : $(this).attr('href') }, function(response) {
                setTimeout(function() {
                    $('#content').html(response).fadeIn();
                    $('#content').removeClass('cortinaOut');
                }, 500);
            });
    });
});

I'm trying to found out the problem since two days ago. Any idea of how to solve it?

share|improve this question
5  
This is how the robot wars begin... –  GhostToast Jan 24 at 14:59
    
@ManoloSalsas I can see a number of potential problems right off of the bat. First a question: Are you ever registering your ajax_callback() function as an ajax handler with a call to add_action()? Your question doesn't show this step. Additionally, in what file is the first code block present? Is this in a plugin, or your theme's functions.php, or somewhere else entirely? –  boscho Jan 27 at 21:47
    
Also you mention you use Ajax to "load the plugin" but then it doesn't respond when you submit your form. I believe you're misinterpreting how WordPress loads... The entire platform and the necessary plugins must be loaded on every request - as soon as the request is finished, everything leaves memory - this goes for AJAX requests as well; as soon as your AJAX request that calls the plugin finishes, the plugin is no longer available for any subsequent requests without loading it once more. –  boscho Jan 27 at 21:56
    
You show the JS, and the hooks, but where is the form itself? –  Tom J Nowell Jan 28 at 9:58
    
Also can you check if your console has any messages? Set the console not to clear on page navigation encase you're missing something –  Tom J Nowell Jan 28 at 9:59
show 3 more comments

2 Answers 2

up vote 1 down vote accepted
+50

Your javascript is heavily reliant on inline attributes for event handling, rather than jQuery based event handling, and you're making AJAX calls to a different domain than the one you're currently on

enter image description here

share|improve this answer
    
Thanks Tom, but my code has not syntax errors. The rest of the Ajax requests are working right. It is just the Contact Plugins that I've tried, the ones that don't work. The thing is that my Ajax code shouldn't affect to the plugin. –  Manolo Jan 28 at 11:07
    
You haven't posted all of your code, please post all of your code if you want an answer that isn't based on second guessing –  Tom J Nowell Jan 28 at 12:37
    
It's done. You can also check at the URL added to the question. –  Manolo Jan 28 at 14:10
2  
hmmm, I strongly recommend you remove all traces of stuff like 'onchange=""' etc, put all your javascript in javascript files and not inline in your HTML. Also your page has numerous js errors calling incorrect domains –  Tom J Nowell Jan 28 at 15:18
1  
See the image I attached to my answer. Whatever plugin you're using, it's not good code. I recommend you go back to basics, implement a basic contact form with no captcha, and features such as AJAX step by step. There are thousands of tutorials on how to implement a contact form out there. –  Tom J Nowell Jan 28 at 15:33
show 4 more comments

A number of problems are present here.

First and foremost, it appears that the first code block you posted is present in your functions.php file, or another theme file. If this is true, I urge you to consider WordPress's loading routine - themes are completely irrelevant to AJAX requests, and therefore WordPress will never touch any theme file of its own accord when processing an AJAX requests. What I'm getting at is that if that code is indeed in a theme file, then the ajax_callback() function is not available to WordPress when it's processing AJAX requests.

The next problem is that ajax_callback() never seems to get registered as an AJAX handler. In order to do so, you need to register the function with a custom action prefixed with wp_ajax_ and/or wp_ajax_nopriv as described in the Codex, with the complete action format wp_ajax_{custom action name} and/or wp_ajax_nopriv_{custom action name}. Doing so would look similar to the following (if not present in a plugin class):

function ajax_callback() {
  ...
}

add_action( 'wp_ajax_my_custom_action', 'ajax_callback' );        // For registered users
add_action( 'wp_ajax_nopriv_my_custom_action', 'ajax_callback' ); // For unregistered users

If this code is not in a plugin class or PHP namespace, I highly recommend that you use a more descriptive name than ajax_callback in order to remove the possibility of naming collisions.

If this code is in a plugin class or PHP namespace, the second argument of add_action needs to be modified to fit the appropriate PHP callback format.

Finally, in your posted JavaScript the action key is set to ajax. This key is what tells WordPress which registered AJAX handler to execute. As it stands, your JavaScript function would invoke WordPress to attempt to execute any handlers registered to the wp_ajax_ajax action. If your AJAX callback is indeed registered to this action, I recommend you change it as wp_ajax_ajax is excessively generic and has a high probability of resulting in naming collisions (if not general confusion).

The action key should be set to the {custom action name} portion of the action(s) referenced above. In order to call the ajax_callback() function as registered to the wp_ajax_my_custom_action/wp_ajax_nopriv_my_custom_action actions as done above, the action key in your AJAX request should be my_custom_action.

I recommend that you read the Codex entry on AJAX in Plugins for a better understanding of how AJAX works in WordPress.

share|improve this answer
    
Thank you for your detailed answer. However, I was already registering the Ajax callback. I've tried replacing the so generic callback function name, but no success. Remember that Ajax is working fine with all other links. I've updated my question. –  Manolo Jan 28 at 9:09
    
I've updated my question. Maybe now you're able to see the problem. –  Manolo Jan 28 at 14:11
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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