Procédure AJAX et retour 0 (Créer un compte)

  • Statut : non résolu
15 sujets de 1 à 15 (sur un total de 17)
  • Auteur
    Messages
  • #530369
    netchaiev
    Membre
    Initié WordPress
    25 contributions

    Bonjour,

    Ma configuration WP actuelle :
    – Version de WordPress : 3.6
    – Version de PHP/MySQL :
    – Thème utilisé : personnel
    – Extensions en place :
    – Nom de l’hebergeur : oxyd
    – Adresse du site :

    Problème(s) rencontré(s) : Retour « 0 » sur une procédure AJAX

    Je rencontre un problème lors de ma procédure AJAX. Firebug me signal que ma requête contient bien les éléments de mon formulaire. Mais, en retour je n’ai qu’une réponse 0. Je n’arrive d’ailleurs pas à faire un var_dump coté fichier de gestion histoire de savoir ce qui est arrivé.

    Je précise que j’ai suivi le tuto disponible ici : http://www.geekpress.fr/wordpress/tutoriel/formulaire-contact-ajax-1802/

    Je précise ausique je récupère ce site et que l’absence de commentaires sur le code ne m’aide pas…….

    Si vous avez une idée, je suis preneur, parce que je m’arrache les cheveux depuis deux jours et je ne trouve pas la solution.

    je vous remercie de votre aide

    -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*

    Le fichier functions contient ceci :

    include (TEMPLATEPATH.’/configurations/config_theme.php’);
    include (TEMPLATEPATH.’/functions/init.php’);
    include (TEMPLATEPATH.’/functions/initJavaScript.php’);
    include (TEMPLATEPATH.’/functions/sandbox.php’);
    include (TEMPLATEPATH.’/functions/forms.php’);
    include (TEMPLATEPATH.’/functions/ajax.php’);

    J’ai une page ‘recherche’ basée sur un template page-recherche.php.
    Je construit un shortcode comme ceci via le fichier forms.php

    add_shortcode(‘contact-comm-perso’, ‘commPerso_shortcode’);

    function commPerso_shortcode(){
    $t .=’<form action="" method="post">‘;
    $t .= ‘<p>‘;
    $t .=’<label for="contact-name">Name</label>‘;
    $t .=’<input type="text" name="name" id="contact-name" placeholder="Votre nom" required/>‘;
    $t .= ‘</p>‘;
    $t .= ‘<p>‘;
    $t .=’<label for="contact-prenom">prenom</label>‘;
    $t .=’<input type="text" name="prenom" value=" " id="contact-prenom" required/>‘;
    $t .= ‘</p>‘;
    $t .= ‘<p>‘;
    $t .=’<label for="contact-email">email</label>‘;
    $t .=’<input type="email" name="email" value=" " id="contact-email" required/>‘;
    $t .= ‘</p>‘;
    $t .=’<input type="button" value="Ajouter un document" id="ajouter"/>‘;
    $t .=’</div>‘;

    $t .= ‘<input type="hidden" name="action" value="contact" />‘;
    $t .= wp_nonce_field(‘ajax_contact_nonce’, ‘security’ );
    $t .=’<input type="submit" id="send-message" value="envoyer"/>‘;
    $t .=’ </form>‘;

    return $t;
    }

    Le fichier Javascript :

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

    if($(‘#send-message’).length > 0) {

    var busy = null; // permet de gérer une soumission multiple du formulaire.

    // A la soumission du formulaire
    $(‘#send-message’).click( function(){


    var error = false,
    form = $(this).parent(‘form’);

    form.find(‘[required]’).each( function(){
    // on vérifie si le champ est vide
    if( $.trim( $(this).val() ) ==  ») {
    $(this).css(‘border-color’,’#FF0000′);
    error = true;
    }
    else {
    $(this).css(‘border-color’,’#CDCDCD’);
    }
    });

    if( !error){

    $.ajax({
    url: ajaxurl,
    type: ‘POST’,
    data: form.serialize(),
    success: function( response ){
    alert(response);
    }
    });
    }
    return false;
    });
    }

    });

    et du coup le fichier ajax.php qui traite la demande :

    add_action( ‘ wp_ajax_contact’ , ‘_ajax_contact’ );

    add_action( ‘ wp_ajax_nopriv_contact’ , ‘ _ajax_contact’);

    function _ajax_contact() {
    print_r($_POST[‘nonce’]);
    check_ajax_referer( ‘ajax_contact_nonce’ , ‘security’ );


    die(‘je suis le fichier ajax.php’);
    }

    #922070
    MikyJoseph
    Membre
    Initié WordPress
    45 contributions

    Bonjour,

    Ma première idée est de vous demander si vous renseigner bien « ajaxurl » :

    $.ajax({
    url: ajaxurl,

    Merci de nous tenir au courant!

    #922072
    netchaiev
    Membre
    Initié WordPress
    25 contributions

    Bonjour MikyJoseph,

    Concernant le « url : ajaxurl », en fait je place dans le header de la page la commande suivante pour appeler le fichier admin-ajax.php :

    <?php  echo is_page('recherches' ) ? ' var ajaxurl = « https://www.lesite.fr/wp-admin/admin-ajax.php »‘ :  »;

    Suit bien évidemment l’appel à Jquery (ici ils utilisent la version 1.4.2) et mon fichier js via


    <script type="text/javascript" src="/js/custom.js »>

    Lorsque je soumets le formulaire les données partent correctement. J’otiens cela avec firebug :

    Paramètresapplication/x-www-form-urlencoded
    _wp_http_referer /recherches?page=&pagename=recherches&debug-this=wp_query
    action contact
    email toto@free.fr
    name b
    prenom b
    security 3c86a99fce
    Source
    name=b&prenom=+b&email=toto%40free.fr&action=contact&security=3c86a99fce&_wp_http_referer=%2Frecherches%3Fpage%3D%26pagename%3Drecherches%26debug-this%3Dwp_query

    Mais, je ne sais pas si elle arrivent….

    #922073
    MikyJoseph
    Membre
    Initié WordPress
    45 contributions

    Bonjour,

    D’après ce que j’ai pu lire rapidement sur l’ajax et wordpress, le paramètre « action » est mal renséigné.

    Cela doit correspondre à votre action ajax php « _ajax_contact » et non « contact ». Je n’ai jamais mis en place cette méthodologie sur WordPress. J’apprends WordPress comme vous.

    Quel niveau avez vous avec la méthodologie Ajax?

    #922074
    MikyJoseph
    Membre
    Initié WordPress
    45 contributions

    Aussi, dans ton fichier « ajax.php »,

    Il faut remplacer

    die(‘je suis le fichier ajax.php’);

    par

    wp_send_json(‘je suis le fichier ajax.php’);

    #922071
    netchaiev
    Membre
    Initié WordPress
    25 contributions

    bonjour,

    Quel niveau avez vous avec la méthodologie Ajax ?

    Pour ce qui est d’ajax, je me défends. Par contre ce qui me manque c’est la connaissance de WP. Je ne connais absolument pas. Enfin pas beaucoup.

    Je vais essayer la méthode que vous m’avez donnée. Mais ce qui m’étonne, c’est qu’un var_dump($_POST) ou le même en version print_r ne donne rien. J’ai l’impression que les données n’arrive pas à mon fichier de traitement ……

    je vous tiens au courant.

    bonne journée

    #922075
    netchaiev
    Membre
    Initié WordPress
    25 contributions

    je remarque un truc. Ma réponse « 0 » reprend la dernière ligne du fichier admin-ajax.php.

    En effet, à ce niveau là j’ai un die(‘0’). Si je remplace de die par die(‘toto’), j’obtiens toto à ma réponse d’AJAX.

    Je suppose qu’il s’agit là de la réponse par défaut en cas de bonne procédure non?

    #922076
    MikyJoseph
    Membre
    Initié WordPress
    45 contributions

    A première vue, vous me parlez d’un fichier « admin-ajax.php » que vous êtes le seul à pouvoir visualiser.

    Pouvez vous mettre les fichiers complets à disposition afin de pouvoir concrètement vous aider !

    #922077
    netchaiev
    Membre
    Initié WordPress
    25 contributions

    Bonjour,

    D’après la documentation le fichier admin-ajax.php est le fichier qui gère les procédures ajax sous wp. Il est en natif et se trouve sous racineDuSite/wp-admin.php

    A titre d’information, je le rajoute :

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

    /**
    * Executing AJAX process.
    *
    * @since 2.1.0
    */
    define( 'DOING_AJAX', true );
    define( 'WP_ADMIN', true );

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

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

    // Require an action parameter
    if ( empty( $_REQUEST['action'] ) )
    die( '0' );

    /** 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', 'autosave', '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', 'set-post-thumbnail', 'date_format', 'time_format', 'wp-fullscreen-save-post',
    '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',
    );

    // 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 );

    if ( is_user_logged_in() ) {
    /**
    * Fires authenticated AJAX actions for logged-in users.
    *
    * The dynamic portion of the hook name, $_REQUEST['action'],
    * refers to the name of the AJAX action callback being fired.
    *
    * @since 2.1.0
    */
    do_action( 'wp_ajax_' . $_REQUEST['action'] );
    } else {
    /**
    * Fires non-authenticated AJAX actions for logged-out users.
    *
    * The dynamic portion of the hook name, $_REQUEST['action'],
    * refers to the name of the AJAX action callback being fired.
    *
    * @since 2.8.0
    */
    do_action( 'wp_ajax_nopriv_' . $_REQUEST['action'] );
    }
    // Default status
    die( '0' );

    Bonne journée

    #922078
    MikyJoseph
    Membre
    Initié WordPress
    45 contributions

    D’accord.

    Peux tu résumer tous tes fichiers créés et modifiés ?
    Peux tu les mettre à disposition STP?

    Merci.

    #922079
    netchaiev
    Membre
    Initié WordPress
    25 contributions

    Salut,

    Puisque je n’arrivais pas à réaliser ma procédure AJAX sur le site en production, j’ai téléchargé la dernière version de WP et installé en local sur ma machine.

    JE n’ai donc touché à aucun fichier de base (pas même au wp-admin/admin-ajax.php).

    J’utilise le theme twentythirteen. Les seules choses que j’ai fait c’est :

    – Création d’une page contact dans le backoffice
    – création d’un template page-contact (que tu as plus haut)
    – création d’un fichier custom.js (que tu as plus haut)
    – création d’un fichier ajax.php (que tu as plus haut)
    -modification du fichier functions pour appeler le fichier ajax.php avec la commande :

    include (TEMPLATEPATH.’/inc/ajax.php’);

    – modification du fichier header en intégrant l’appel au custom.js et la variable ajaxurl. Tu les as plus haut.

    Voilà tout ce que j’ai fait.

    Ce n’est pas grand chose et c’est pour cela que je ne comprends pas.

    Bonne journée à toi

    #922080
    netchaiev
    Membre
    Initié WordPress
    25 contributions

    J’ai continué un peu le truc. Ce que je veux c’est de récupérer les données du formulaire et m’en servir pour envoyer un mail.

    Comme je suis en local, je demande juste de créer un fichier txt.
    je modifie le fichier ajax. php comme ceci :

    <?php

    add_action( ' wp_ajax_contact' , 'ajax_contact' );
    add_action( ' wp_ajax_nopriv_contact' , ' ajax_contact');

    function ajax_contact() {

    check_ajax_referer( 'ajax_contact_nonce','security');

    /********************************
    * protection des variables
    *********************************/

    $name = wp_strip_all_tags($_POST['name']);
    $pname = wp_strip_all_tags($_POST['pname']);
    $sender = sanitize_email($_POST['email']);
    $message = nl2br(stripcslashes(wp_kses($_POST['message'] , $$GLOBALS['allowedtags'] ) ) ) ;

    /***********************************
    * GEstion des headers
    ************************************/
    $headers = array();
    $headers[] = 'FROM : ' . $name . '’ . « rn »;


    /*****************************************************
    * GEstion du message
    *******************************************************/

    ob_start();
    include (TEMPLATEPATH.’inc/mail/contact.php’);
    $mail = ob_get_contents();

    ob_end_clean();
    file_put_contents(TEMPLATEPATH . ‘inc/mail/mail.txt’ , $mail);

    }

    et ben rien ne se passe. Pas de création d’un fichier txt.

    Conclusion, je pense que le problème vient de la fonction check_ajax_referer qui doit considérer le nonce comme non valide et donc ne pas exécuter la suite du script.

    Dans Firebug j’ai cela comme info
    _wp_http_referer /wp2/contact/
    action contact
    email coucou@toto.fr
    message coucou
    name tata
    pname toto
    security ead902e394

    #922081
    MikyJoseph
    Membre
    Initié WordPress
    45 contributions

    Bonjour,

    J’ai installé moi aussi un wordpress en local et utilisé le theme twentythirteen.
    J’ai suivi le tutoriel à la lettre et je n’ai pas eu de soucis particulier.

    Pourrais tu me remettre tous les fichiers complets que tu as créé et modifier afin que je analyse tes dernières versions.

    Je pense que tu dois avoir :
    – le fichier « page-contact.php » (creation)
    – le fichier « custom.js » (creation) (le CSS avec mais ce n’est que du style)
    – le ficher « ajax.php » (creation)

    – le fichier « footer.php » (modification)
    – le fichier « functions.php » (modification)
    – le fichier « header.php » (modification)

    Je pense que cela vient d’un détail que tu n’arrives pas à voir.

    #922082
    netchaiev
    Membre
    Initié WordPress
    25 contributions

    Salut le leve tôt ou le couche tard,:D

    et merci de ton aide. 👏
    JE suis d’accord avec toi, je dois avoir un petit truc qui foire quelque part et je ne le vois pas.

    Je te remets tout les fichiers issus de la procédure faite en local avec la dernière version de WP et sur le theme twentythirteen.

    le fichier header.php

    <?php
    /**
    * The Header template for our theme
    *
    * Displays all of the section and everything up till <div id="main">
    *
    * @package WordPress
    * @subpackage Twenty_Thirteen
    * @since Twenty Thirteen 1.0
    */
    ?>
    <!--[if IE 7]>-->
    <html class="ie ie7" >

    <!--[if IE 8]>-->
    <html class="ie ie8" >

    <!--[if !(IE 7) | !(IE 8) ]>>-->
    <html >
    <!–




    <meta charset=" »>

    <title></title>

    <link rel="pingback" href=" »>



    <!--[if lt IE 9]>-->
    <script src="/js/html5.js »>








    <body >
    <div id="page" class="hfeed site">
    <header id="masthead" class="site-header" role="banner">
    <a class="home-link" href=" » title= » » rel= »home »>
    <h1 class="site-title"></h1>
    <h2 class="site-description"></h2>
    </a>

    <div id="navbar" class="navbar">
    <nav id="site-navigation" class="navigation main-navigation" role="navigation">
    <h3 class="menu-toggle"></h3>
    <a class="screen-reader-text skip-link" href="#content" title=" »></a>
    ‘primary’, ‘menu_class’ => ‘nav-menu’ ) ); ?>

    </nav><!-- #site-navigation -->
    </div><!-- #navbar -->
    </header><!-- #masthead -->

    <div id="main" class="site-main">

    Le fichier footer.php



    </div><!-- #main -->
    <footer id="colophon" class="site-footer" role="contentinfo">


    <div class="site-info">

    <a href=" » title= » »></a>
    </div><!-- .site-info -->
    </footer><!-- #colophon -->
    </div><!-- #page -->


    <!-- INSERTION DES SCRIPTS POUR LA PROCEDURE AJAX
    -->

    <?php echo is_page('contact') ? 'var ajaxurl = »‘.admin_url(‘admin-ajax.php’).' »‘ : ‘ ‘;?>

    <script type="text/javascript" src="/js/custom.js »>



    Le fichier functions.php MA modif est tout à la fin

    <?php
    /**
    * Twenty Thirteen functions and definitions
    *
    * Sets up the theme and provides some helper functions, which are used in the
    * theme as custom template tags. Others are attached to action and filter
    * hooks in WordPress to change core functionality.
    *
    * When using a child theme (see http://codex.wordpress.org/Theme_Development
    * and http://codex.wordpress.org/Child_Themes), you can override certain
    * functions (those wrapped in a function_exists() call) by defining them first
    * in your child theme's functions.php file. The child theme's functions.php
    * file is included before the parent theme's file, so the child theme
    * functions would be used.
    *
    * Functions that are not pluggable (not wrapped in function_exists()) are
    * instead attached to a filter or action hook.
    *
    * For more information on hooks, actions, and filters, @link http://codex.wordpress.org/Plugin_API
    *
    * @package WordPress
    * @subpackage Twenty_Thirteen
    * @since Twenty Thirteen 1.0
    */

    /*
    * Set up the content width value based on the theme's design.
    *
    * @see twentythirteen_content_width() for template-specific adjustments.
    */
    if ( ! isset( $content_width ) )
    $content_width = 604;

    /**
    * Add support for a custom header image.
    */
    require get_template_directory() . '/inc/custom-header.php';

    /**
    * Twenty Thirteen only works in WordPress 3.6 or later.
    */
    if ( version_compare( $GLOBALS['wp_version'], '3.6-alpha', '<' ) )
    require get_template_directory() . '/inc/back-compat.php';

    /**
    * Twenty Thirteen setup.
    *
    * Sets up theme defaults and registers the various WordPress features that
    * Twenty Thirteen supports.
    *
    * @uses load_theme_textdomain() For translation/localization support.
    * @uses add_editor_style() To add Visual Editor stylesheets.
    * @uses add_theme_support() To add support for automatic feed links, post
    * formats, and post thumbnails.
    * @uses register_nav_menu() To add support for a navigation menu.
    * @uses set_post_thumbnail_size() To set a custom post thumbnail size.
    *
    * @since Twenty Thirteen 1.0
    *
    * @return void
    */
    function twentythirteen_setup() {
    /*
    * Makes Twenty Thirteen available for translation.
    *
    * Translations can be added to the /languages/ directory.
    * If you're building a theme based on Twenty Thirteen, use a find and
    * replace to change 'twentythirteen' to the name of your theme in all
    * template files.
    */
    load_theme_textdomain( 'twentythirteen', get_template_directory() . '/languages' );

    /*
    * This theme styles the visual editor to resemble the theme style,
    * specifically font, colors, icons, and column width.
    */
    add_editor_style( array( 'css/editor-style.css', 'fonts/genericons.css', twentythirteen_fonts_url() ) );

    // Adds RSS feed links to for posts and comments.
    add_theme_support( ‘automatic-feed-links’ );

    /*
    * Switches default core markup for search form, comment form,
    * and comments to output valid HTML5.
    */
    add_theme_support( ‘html5’, array( ‘search-form’, ‘comment-form’, ‘comment-list’ ) );

    /*
    * This theme supports all available post formats by default.
    * See http://codex.wordpress.org/Post_Formats
    */
    add_theme_support( ‘post-formats’, array(
    ‘aside’, ‘audio’, ‘chat’, ‘gallery’, ‘image’, ‘link’, ‘quote’, ‘status’, ‘video’
    ) );

    // This theme uses wp_nav_menu() in one location.
    register_nav_menu( ‘primary’, __( ‘Navigation Menu’, ‘twentythirteen’ ) );

    /*
    * This theme uses a custom image size for featured images, displayed on
    * « standard » posts and pages.
    */
    add_theme_support( ‘post-thumbnails’ );
    set_post_thumbnail_size( 604, 270, true );

    // This theme uses its own gallery styles.
    add_filter( ‘use_default_gallery_style’, ‘__return_false’ );
    }
    add_action( ‘after_setup_theme’, ‘twentythirteen_setup’ );

    /**
    * Return the Google font stylesheet URL, if available.
    *
    * The use of Source Sans Pro and Bitter by default is localized. For languages
    * that use characters not supported by the font, the font can be disabled.
    *
    * @since Twenty Thirteen 1.0
    *
    * @return string Font stylesheet or empty string if disabled.
    */
    function twentythirteen_fonts_url() {
    $fonts_url =  »;

    /* Translators: If there are characters in your language that are not
    * supported by Source Sans Pro, translate this to ‘off’. Do not translate
    * into your own language.
    */
    $source_sans_pro = _x( ‘on’, ‘Source Sans Pro font: on or off’, ‘twentythirteen’ );

    /* Translators: If there are characters in your language that are not
    * supported by Bitter, translate this to ‘off’. Do not translate into your
    * own language.
    */
    $bitter = _x( ‘on’, ‘Bitter font: on or off’, ‘twentythirteen’ );

    if ( ‘off’ !== $source_sans_pro || ‘off’ !== $bitter ) {
    $font_families = array();

    if ( ‘off’ !== $source_sans_pro )
    $font_families[] = ‘Source Sans Pro:300,400,700,300italic,400italic,700italic’;

    if ( ‘off’ !== $bitter )
    $font_families[] = ‘Bitter:400,700’;

    $query_args = array(
    ‘family’ => urlencode( implode( ‘|’, $font_families ) ),
    ‘subset’ => urlencode( ‘latin,latin-ext’ ),
    );
    $fonts_url = add_query_arg( $query_args, « //fonts.googleapis.com/css » );
    }

    return $fonts_url;
    }

    /**
    * Enqueue scripts and styles for the front end.
    *
    * @since Twenty Thirteen 1.0
    *
    * @return void
    */
    function twentythirteen_scripts_styles() {
    /*
    * Adds JavaScript to pages with the comment form to support
    * sites with threaded comments (when in use).
    */
    if ( is_singular() && comments_open() && get_option( ‘thread_comments’ ) )
    wp_enqueue_script( ‘comment-reply’ );

    // Adds Masonry to handle vertical alignment of footer widgets.
    if ( is_active_sidebar( ‘sidebar-1’ ) )
    wp_enqueue_script( ‘jquery-masonry’ );

    // Loads JavaScript file with functionality specific to Twenty Thirteen.
    wp_enqueue_script( ‘twentythirteen-script’, get_template_directory_uri() . ‘/js/functions.js’, array( ‘jquery’ ), ‘2013-07-18’, true );

    // Add Source Sans Pro and Bitter fonts, used in the main stylesheet.
    wp_enqueue_style( ‘twentythirteen-fonts’, twentythirteen_fonts_url(), array(), null );

    // Add Genericons font, used in the main stylesheet.
    wp_enqueue_style( ‘genericons’, get_template_directory_uri() . ‘/fonts/genericons.css’, array(), ‘2.09’ );

    // Loads our main stylesheet.
    wp_enqueue_style( ‘twentythirteen-style’, get_stylesheet_uri(), array(), ‘2013-07-18’ );

    // Loads the Internet Explorer specific stylesheet.
    wp_enqueue_style( ‘twentythirteen-ie’, get_template_directory_uri() . ‘/css/ie.css’, array( ‘twentythirteen-style’ ), ‘2013-07-18’ );
    wp_style_add_data( ‘twentythirteen-ie’, ‘conditional’, ‘lt IE 9’ );
    }
    add_action( ‘wp_enqueue_scripts’, ‘twentythirteen_scripts_styles’ );

    /**
    * Filter the page title.
    *
    * Creates a nicely formatted and more specific title element text for output
    * in head of document, based on current view.
    *
    * @since Twenty Thirteen 1.0
    *
    * @param string $title Default title text for current view.
    * @param string $sep Optional separator.
    * @return string The filtered title.
    */
    function twentythirteen_wp_title( $title, $sep ) {
    global $paged, $page;

    if ( is_feed() )
    return $title;

    // Add the site name.
    $title .= get_bloginfo( ‘name’ );

    // Add the site description for the home/front page.
    $site_description = get_bloginfo( ‘description’, ‘display’ );
    if ( $site_description && ( is_home() || is_front_page() ) )
    $title = « $title $sep $site_description »;

    // Add a page number if necessary.
    if ( $paged >= 2 || $page >= 2 )
    $title = « $title $sep  » . sprintf( __( ‘Page %s’, ‘twentythirteen’ ), max( $paged, $page ) );

    return $title;
    }
    add_filter( ‘wp_title’, ‘twentythirteen_wp_title’, 10, 2 );

    /**
    * Register two widget areas.
    *
    * @since Twenty Thirteen 1.0
    *
    * @return void
    */
    function twentythirteen_widgets_init() {
    register_sidebar( array(
    ‘name’ => __( ‘Main Widget Area’, ‘twentythirteen’ ),
    ‘id’ => ‘sidebar-1’,
    ‘description’ => __( ‘Appears in the footer section of the site.’, ‘twentythirteen’ ),
    ‘before_widget’ => ‘<aside id="%1$s" class="widget %2$s">‘,
    ‘after_widget’ => ‘</aside>‘,
    ‘before_title’ => ‘<h3 class="widget-title">‘,
    ‘after_title’ => ‘</h3>‘,
    ) );

    register_sidebar( array(
    ‘name’ => __( ‘Secondary Widget Area’, ‘twentythirteen’ ),
    ‘id’ => ‘sidebar-2’,
    ‘description’ => __( ‘Appears on posts and pages in the sidebar.’, ‘twentythirteen’ ),
    ‘before_widget’ => ‘<aside id="%1$s" class="widget %2$s">‘,
    ‘after_widget’ => ‘</aside>‘,
    ‘before_title’ => ‘<h3 class="widget-title">‘,
    ‘after_title’ => ‘</h3>‘,
    ) );
    }
    add_action( ‘widgets_init’, ‘twentythirteen_widgets_init’ );

    if ( ! function_exists( ‘twentythirteen_paging_nav’ ) ) :
    /**
    * Display navigation to next/previous set of posts when applicable.
    *
    * @since Twenty Thirteen 1.0
    *
    * @return void
    */
    function twentythirteen_paging_nav() {
    global $wp_query;

    // Don’t print empty markup if there’s only one page.
    if ( $wp_query->max_num_pages
    <nav class="navigation paging-navigation" role="navigation">
    <h1 class="screen-reader-text"></h1>
    <div class="nav-links">


    <div class="nav-previous"><?php next_posts_link( __( '<span class="meta-nav">←</span> Older posts’, ‘twentythirteen’ ) ); ?></div>



    <div class="nav-next"><?php previous_posts_link( __( 'Newer posts <span class="meta-nav">→</span>‘, ‘twentythirteen’ ) ); ?></div>


    </div><!-- .nav-links -->
    </nav><!-- .navigation -->
    post_parent ) : get_adjacent_post( false,  », true );
    $next = get_adjacent_post( false,  », false );

    if ( ! $next && ! $previous )
    return;
    ?>
    <nav class="navigation post-navigation" role="navigation">
    <h1 class="screen-reader-text"></h1>
    <div class="nav-links">

    <?php previous_post_link( '%link', _x( '<span class="meta-nav">←</span> %title’, ‘Previous post link’, ‘twentythirteen’ ) ); ?>
    <?php next_post_link( '%link', _x( '%title <span class="meta-nav">→</span>‘, ‘Next post link’, ‘twentythirteen’ ) ); ?>

    </div><!-- .nav-links -->
    </nav><!-- .navigation -->
    <?php
    }
    endif;

    if ( ! function_exists( 'twentythirteen_entry_meta' ) ) :
    /**
    * Print HTML with meta information for current post: categories, tags, permalink, author, and date.
    *
    * Create your own twentythirteen_entry_meta() to override in a child theme.
    *
    * @since Twenty Thirteen 1.0
    *
    * @return void
    */
    function twentythirteen_entry_meta() {
    if ( is_sticky() && is_home() && ! is_paged() )
    echo '<span class="featured-post">‘ . __( ‘Sticky’, ‘twentythirteen’ ) . ‘</span>‘;

    if ( ! has_post_format( ‘link’ ) && ‘post’ == get_post_type() )
    twentythirteen_entry_date();

    // Translators: used between list items, there is a space after the comma.
    $categories_list = get_the_category_list( __( ‘, ‘, ‘twentythirteen’ ) );
    if ( $categories_list ) {
    echo ‘<span class="categories-links">‘ . $categories_list . ‘</span>‘;
    }

    // Translators: used between list items, there is a space after the comma.
    $tag_list = get_the_tag_list(  », __( ‘, ‘, ‘twentythirteen’ ) );
    if ( $tag_list ) {
    echo ‘<span class="tags-links">‘ . $tag_list . ‘</span>‘;
    }

    // Post author
    if ( ‘post’ == get_post_type() ) {
    printf( ‘<span class="author vcard"><a class="url fn n" href="%1$s" title="%2$s" rel="author">%3$s</a></span>‘,
    esc_url( get_author_posts_url( get_the_author_meta( ‘ID’ ) ) ),
    esc_attr( sprintf( __( ‘View all posts by %s’, ‘twentythirteen’ ), get_the_author() ) ),
    get_the_author()
    );
    }
    }
    endif;

    if ( ! function_exists( ‘twentythirteen_entry_date’ ) ) :
    /**
    * Print HTML with date information for current post.
    *
    * Create your own twentythirteen_entry_date() to override in a child theme.
    *
    * @since Twenty Thirteen 1.0
    *
    * @param boolean $echo (optional) Whether to echo the date. Default true.
    * @return string The HTML-formatted post date.
    */
    function twentythirteen_entry_date( $echo = true ) {
    if ( has_post_format( array( ‘chat’, ‘status’ ) ) )
    $format_prefix = _x( ‘%1$s on %2$s’, ‘1: post format name. 2: date’, ‘twentythirteen’ );
    else
    $format_prefix = ‘%2$s’;

    $date = sprintf( ‘<span class="date"><a href="%1$s" title="%2$s" rel="bookmark">%4$s</a></span>‘,
    esc_url( get_permalink() ),
    esc_attr( sprintf( __( ‘Permalink to %s’, ‘twentythirteen’ ), the_title_attribute( ‘echo=0’ ) ) ),
    esc_attr( get_the_date( ‘c’ ) ),
    esc_html( sprintf( $format_prefix, get_post_format_string( get_post_format() ), get_the_date() ) )
    );

    if ( $echo )
    echo $date;

    return $date;
    }
    endif;

    if ( ! function_exists( ‘twentythirteen_the_attached_image’ ) ) :
    /**
    * Print the attached image with a link to the next attached image.
    *
    * @since Twenty Thirteen 1.0
    *
    * @return void
    */
    function twentythirteen_the_attached_image() {
    /**
    * Filter the image attachment size to use.
    *
    * @since Twenty thirteen 1.0
    *
    * @param array $size {
    * @type int The attachment height in pixels.
    * @type int The attachment width in pixels.
    * }
    */
    $attachment_size = apply_filters( ‘twentythirteen_attachment_size’, array( 724, 724 ) );
    $next_attachment_url = wp_get_attachment_url();
    $post = get_post();

    /*
    * Grab the IDs of all the image attachments in a gallery so we can get the URL
    * of the next adjacent image in a gallery, or the first image (if we’re
    * looking at the last image in a gallery), or, in a gallery of one, just the
    * link to that image file.
    */
    $attachment_ids = get_posts( array(
    ‘post_parent’ => $post->post_parent,
    ‘fields’ => ‘ids’,
    ‘numberposts’ => -1,
    ‘post_status’ => ‘inherit’,
    ‘post_type’ => ‘attachment’,
    ‘post_mime_type’ => ‘image’,
    ‘order’ => ‘ASC’,
    ‘orderby’ => ‘menu_order ID’
    ) );

    // If there is more than 1 attachment in a gallery…
    if ( count( $attachment_ids ) > 1 ) {
    foreach ( $attachment_ids as $attachment_id ) {
    if ( $attachment_id == $post->ID ) {
    $next_id = current( $attachment_ids );
    break;
    }
    }

    // get the URL of the next image attachment…
    if ( $next_id )
    $next_attachment_url = get_attachment_link( $next_id );

    // or get the URL of the first image attachment.
    else
    $next_attachment_url = get_attachment_link( array_shift( $attachment_ids ) );
    }

    printf( ‘<a href="%1$s" title="%2$s" rel="attachment">%3$s</a>‘,
    esc_url( $next_attachment_url ),
    the_title_attribute( array( ‘echo’ => false ) ),
    wp_get_attachment_image( $post->ID, $attachment_size )
    );
    }
    endif;

    /**
    * Return the post URL.
    *
    * @uses get_url_in_content() to get the URL in the post meta (if it exists) or
    * the first link found in the post content.
    *
    * Falls back to the post permalink if no URL is found in the post.
    *
    * @since Twenty Thirteen 1.0
    *
    * @return string The Link format URL.
    */
    function twentythirteen_get_link_url() {
    $content = get_the_content();
    $has_url = get_url_in_content( $content );

    return ( $has_url ) ? $has_url : apply_filters( ‘the_permalink’, get_permalink() );
    }

    /**
    * Extend the default WordPress body classes.
    *
    * Adds body classes to denote:
    * 1. Single or multiple authors.
    * 2. Active widgets in the sidebar to change the layout and spacing.
    * 3. When avatars are disabled in discussion settings.
    *
    * @since Twenty Thirteen 1.0
    *
    * @param array $classes A list of existing body class values.
    * @return array The filtered body class list.
    */
    function twentythirteen_body_class( $classes ) {
    if ( ! is_multi_author() )
    $classes[] = ‘single-author’;

    if ( is_active_sidebar( ‘sidebar-2’ ) && ! is_attachment() && ! is_404() )
    $classes[] = ‘sidebar’;

    if ( ! get_option( ‘show_avatars’ ) )
    $classes[] = ‘no-avatars’;

    return $classes;
    }
    add_filter( ‘body_class’, ‘twentythirteen_body_class’ );

    /**
    * Adjust content_width value for video post formats and attachment templates.
    *
    * @since Twenty Thirteen 1.0
    *
    * @return void
    */
    function twentythirteen_content_width() {
    global $content_width;

    if ( is_attachment() )
    $content_width = 724;
    elseif ( has_post_format( ‘audio’ ) )
    $content_width = 484;
    }
    add_action( ‘template_redirect’, ‘twentythirteen_content_width’ );

    /**
    * Add postMessage support for site title and description for the Customizer.
    *
    * @since Twenty Thirteen 1.0
    *
    * @param WP_Customize_Manager $wp_customize Customizer object.
    * @return void
    */
    function twentythirteen_customize_register( $wp_customize ) {
    $wp_customize->get_setting( ‘blogname’ )->transport = ‘postMessage’;
    $wp_customize->get_setting( ‘blogdescription’ )->transport = ‘postMessage’;
    $wp_customize->get_setting( ‘header_textcolor’ )->transport = ‘postMessage’;
    }
    add_action( ‘customize_register’, ‘twentythirteen_customize_register’ );

    /**
    * Enqueue Javascript postMessage handlers for the Customizer.
    *
    * Binds JavaScript handlers to make the Customizer preview
    * reload changes asynchronously.
    *
    * @since Twenty Thirteen 1.0
    *
    * @return void
    */
    function twentythirteen_customize_preview_js() {
    wp_enqueue_script( ‘twentythirteen-customizer’, get_template_directory_uri() . ‘/js/theme-customizer.js’, array( ‘customize-preview’ ), ‘20130226’, true );
    }
    add_action( ‘customize_preview_init’, ‘twentythirteen_customize_preview_js’ );



    /********************************************************************************************************************
    * MES FONCTIONS
    *********************************************************************************************************************/


    include (TEMPLATEPATH.’/inc/ajax.php’);

    Le fichier page-contact.php



    <form action="#" method="post" class="contact-form">
    <p>
    <label for="contact-name">Nom :</label>

    </p>
    <p>
    <label for="contact-pname">Prénom :</label>

    </p>
    <p>
    <label for="contact-email">Email :</label>

    </p>
    <p>
    <label for="contact-message">Message :</label>
    <textarea name="message" id="contact-message" cols="88" rows="5"></textarea>
    </p>





    </form>

    Le fichier custom.php dans /js

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

    if($(‘#send-message’).length > 0) {

    $(‘body’).append(‘<div id="noty"></div>‘);

    var busy = null; // permet de gérer une soumission multiple du formulaire.

    // A la soumission du formulaire
    $(‘#send-message’).click( function(){


    var error = false,
    form = $(this).parent(‘form’);

    form.find(‘[required]’).each( function(){
    // on vérifie si le champ est vide
    if( $.trim( $(this).val() ) == ‘ ‘) {
    $(this).css(‘border-color’,’#FF0000′);
    error = true;
    }
    else {
    $(this).css(‘border-color’,’#CDCDCD’);
    }
    });

    if( !error){
    if ( busy ){busy.abort();}

    busy = jQuery.ajax({
    url: ajaxurl,
    type: ‘POST’,
    data: form.serialize(),
    action: ‘contact’,
    success: function( response ){
    alert(response);

    });
    }
    return false;
    });
    }
    });

    Le fichier ajax.php dans /inc/

    <?php

    add_action( ' wp_ajax_contact' , '_ajax_contact' );
    add_action( ' wp_ajax_nopriv_contact' , ' _ajax_contact');

    function _ajax_contact() {
    check_ajax_referer( 'ajax_contact_nonce' , 'security' );



    die('toto');

    }

    #922083
    MikyJoseph
    Membre
    Initié WordPress
    45 contributions

    Salut,

    Dans ton fichier « ajax.php » :

    Remplace :

    add_action( ‘ wp_ajax_contact’ , ‘_ajax_contact’ );
    add_action( ‘ wp_ajax_nopriv_contact’ , ‘ _ajax_contact’);

    par :

    add_action( ‘wp_ajax_contact’ , ‘_ajax_contact’ );
    add_action( ‘wp_ajax_nopriv_contact’ , ‘_ajax_contact’);

    Cela semble anodin mais les espaces au début de tes noms d’action doivent faire bugger.

    Dis moi si cela résous ton problème.

    Aussi, j’ai lu que « TEMPLATEPATH » (dans ton fichier functions.php) doit être remplacé par « get_template_directory() ».

    Fait attention à bien inclure l’appel à la librairie Jquery dans ta page « page-contact.php ».

15 sujets de 1 à 15 (sur un total de 17)
  • Vous devez être connecté pour répondre à ce sujet.