1

I have problem with wordpress plugin - in jQuery.ajax part, the ajax_object (url: ajax_object.ajax_url) is undefined and I don't know why. I cant recieve correct code from my php plugin, but if I hardlik url to sm.php file, everything is working correctly, other way if I delete "url" and use only "action: acton_exitpopup" In success(data) I'm recieving full html document (html of site where form is placed). I need help to solve my ajax and wordpress integration problem.

JS/Ajax:

jQuery(document).ready(function () {

jQuery('#submit').click(function()
{   

email = jQuery("#email").val();
firstName = jQuery("#firstName").val();
agree = jQuery('#agree').prop('checked');

var mail_match =/^[^@]+@[^@]+.[a-z]{2,}$/;


if(firstName == "" || firstName == "Your email" ) {
    jQuery("#firstName").css({'border-color': 'red'});
    return false;
}
else if((email.search(mail_match) == -1)) {
     jQuery("#email").css({'border-color': 'red'});
    return false;
}
else if(agree == false) {
     jQuery(".agree").css({color: 'red'});
    return false;
}
else {
      jQuery("#email").css({'border-color': '#d1d1d1'});
      jQuery("#firstName").css({'border-color': '#d1d1d1'});


      jQuery.ajax({
        url: ajax_object.ajax_url,
        action: action_exitpopup,
        type: "POST",
        data:
        {
            firstName: firstName,
            email: email
        },
        success: function(data)
        {

            if(data && (data != 'bad') )
            {
                console.log(data);
                setCookie("popup", "1", 365);
                setCookie("smuuid", data, 30);
                console.log('correct data recieved');
            }
            else if (data = "bad")
            {      
                console.log('not working');

            } else {
                console.log('totaly not working');
            }
            return false;
        }
      });  
      return false;
}

});  

});

PHP plugin:

<?php
   /*
   Plugin Name: Exitpopup for Salesmanago
   Plugin URI: somedata
   Description: Exitpopup window for salesmanago 
   Version: 1.0
   Author: somedata
   Author URI: http://somedata.pl
   License: GPL2
   */


function add_exitpopup(){ 
    wp_enqueue_style('styleexitpop', get_bloginfo('template_directory') . "/exitpop/styleexitpop.css" );



    wp_enqueue_script( 'popup.js', get_bloginfo('template_directory') . "/exitpop/popup.js", array( 'jquery' ) );


    wp_localize_script( 'add_exitpopup', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) ); 
} 

add_action( 'wp_enqueue_style', 'add_exitpopup' );
add_action( 'wp_enqueue_scripts', 'add_exitpopup' );


function action_exitpopup() {

    // SALESmanago config  

    $clientId = 'somedata'; 
    $apiKey = 'somedata'; 
    $apiSecret = 'somedata'; 
    $endpoint = 'http://app2.salesmanago.pl'; 
    // If we send message for the user, add email ID from SALESmanago
    $emailId = 'somedata'; 

    $dt = new DateTime('NOW'); 

    function do_post_request($url, $data)
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER,
                    array(
                         'Content-Type: application/json',
                         'Content-Length: ' . strlen($data)
                    )
        );

        return curl_exec($ch);
    }

    if(isset($_POST['email'])) {
        // Filled form

        $name = $_POST['firstName'];
        $email = $_POST['email'];

        // $name = $firstName . ' ' . $lastName;

        // Data for request 
        $data = array( 
            'clientId' => $clientId,
            'apiKey' => $apiKey, 
            'requestTime' => time(), 
            'sha' => sha1($apiKey . $clientId . $apiSecret), 
            'contact' => array( 
               'email' => $email, 
               'name' => $name 
                ), 
            'owner' => 'some@mail.com', 
            'tags' => array('test_cookie'), // Tags
            'lang' => 'EN',
            'useApiDoubleOptIn' => true,
            'forceOptIn' => false,
            'forceOptOut' => false  
        );



        $jsonAddContact = json_encode($data);


        // Send request, add new/update contact to SALESmanago
        $result = do_post_request($endpoint. '/api/contact/upsert', $jsonAddContact);

        $r = json_decode($result);

        // Get contact ID 
        $contactId = $r->{'contactId'};

        if (isset($contactId)) {
            // If contact added/updated successfully

         echo json_encode($contactId);
        }


    } else {
        echo 'bld';
    }
wp_die();

}

add_action( 'wp_ajax_action_exitpopup', 'action_exitpopup' );
add_action( 'wp_ajax_nopriv_action_exitpopup', 'action_exitpopup' );



function displayExitPopup() {

    echo '<div id="popup-overlay" style="display: none;"></div>
    <div id="popup" style="display: none;">
    <div class="btn">x</div>
    <div class="left">
    <h2>Lorem ipsum</h2>

    <p>Lorem Ipsum Lorem IpsumLorem IpsumLorem IpsumLorem Ipsum</p>

    <form class="subscribe-form" role="form">

        <input type="text" name="firstName" placeholder="Your name" id="firstName" class="form-control">

        <input type="email" name="email" placeholder="Your email" id="email" class="form-control">

        <input type="checkbox" id="agree" class="agree" name="agree" />
        <p class="agree">Agree <a href="">pp</a></p>

        <button class="btn-newsletter" id="submit">Lorem Ipsum!</button>

    </form>
    </div>
    <div class="right">
        <img src="' . get_bloginfo('template_directory') .'/exitpop/someimg.jpg" alt="">
    </div>
</div>';

}

add_action( 'wp_footer', 'displayExitPopup' );

?>
1

Here's how localization works. The first thing you need to do is register your script with WordPress. This pretty much tells WordPress where the script is located, what version it is, any dependants ( like jquery ), and whether it will be located in the header or footer. More importantly you need to give it a unique identifier which you'll be able to reference in the wp_localize_script() so WordPress knows your local variable scope. So throughout all 3 function calls, the unique identifier needs to be the same:

function add_exitpopup(){ 
    wp_enqueue_style('styleexitpop', get_bloginfo('template_directory') . "/exitpop/styleexitpop.css" );

    // Register Our Script:
    wp_register_script(
        'popup-js',
        get_bloginfo('template_directory') . "/exitpop/popup.js",
        array( 'jquery' )
    );

    // Localize Our Script with our AJAX URL ( Note the same unique identified at the front )
    wp_localize_script(
        'popup-js',
        'ajax_object',
        array( 'ajax_url' => admin_url( 'admin-ajax.php' ) )
    ); 

    // Enqueue Our Script
    wp_enqueue_script( 'popup-js' );
}
add_action( 'wp_enqueue_scripts', 'add_exitpopup' );
  • 1
    I think that wp_enqueue_style action doesn't exist. You can remove it. – cybmeta Feb 1 '16 at 15:35
  • Ok, I add changes as You told me how it should works and it is still reloading page with error in console "Uncaught ReferenceError: action_exitpopup is not defined". – Adamo Feb 1 '16 at 15:49
  • 1
    @Adamo JS Errors are kind of out of the context of both this question and this stackexhcnage ( as it's not WordPress specific ) but action: action_exitpopup needs to be passed to your data object as a string. See my example on another question so it would look like: data: { 'action': 'action_exitpopup' } along with your other data stuff. – Howdy_McGee Feb 1 '16 at 15:52
  • 1
    OMG, sorry ;) My bad :) Thanks, it is working now. :) – Adamo Feb 1 '16 at 15:57

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.