AJAX Wordpress request with problems

1

I'm developing a form template within a wordpress theme. I need the form data to be sent via email to a certain address via AJAX. Here is the form handling in JS:

var FormData = function(){
var user_name;
var user_email;
var user_message;

this.setName = function(name){
    this.user_name = name;
}

this.getName = function(){
    return this.user_name;
}

this.setEmail = function(email){
    this.user_email = email;
}

this.getEmail = function(){
    return this.user_email;
}

this.setMessage = function(message){
    this.user_message = message;
}

this.getMessage = function(){
    return this.user_message;
}

this.nameIsValid = function(){
    if(this.user_name != ''){
        return true;
    } else {
        return false;
    }
}

this.emailIsValid = function(){
    if(this.user_email != ''){
        return true;
    } else {
        return false;
    }
}

this.messageIsValid = function(){
    if(this.user_message != ''){
        return true;
    } else {
        return false;
    }
}

this.formIsValid = function(){
    if((this.nameIsValid() && this.emailIsValid() && this.messageIsValid())){
        return true;
    } else {
        return false;
    }
}
};

$(document).ready(function(){
    user_object = new FormData();
});

Some may find it unnecessary to validate a form. But I did it just for study purposes anyway. Omitting the methods that I believe do not make any difference, I press on.

$('#form-contact').submit(function(e){
e.preventDefault();

user_object.setName($('input[name=user_name]').val());
user_object.setEmail($('input[name=user_email]').val());
user_object.setMessage($('#user_message_textarea').val());

if(user_object.formIsValid()){
    var formData = JSON.stringify(user_object);
    $.ajax({
        type: 'POST',
        dataType: 'json',
        cache: false,
        url: '/wp-admin/admin-ajax.php',
        data: formData,
        success: function(data){
            alert(data);
            $('#form-contact').trigger('reset');
        },
        error: function(){
            alert("Deu erro aqui!");
        }
    });
} else {
    alert("Este formulário não é válido!");
}

I want to send the object in Ajax notation pro PHP method. Now the server-side code:

function sendMail(){
    $obj = json_decode($_POST['formData']);

    $user_name    = $obj->{'user_name'};
    $user_email   = $obj->{'user_email'};
    $user_message = $obj->{'user_message'};

    $send = mail('[email protected]', 'Contato pelo Site',      $user_message);
    if ($send) {
        return json_encode("Certinho!");
    } else {
        return json_encode("Deu erro!");
    }
}

add_action('wp_ajax_sendMail', 'sendMail');
add_action('wp_ajax_nopriv_sendMail', 'sendMail');

Now the problem! When I submit the form, I debug the AJAX request, and it is giving status 200. Including, I get the success message in response. However, the PHP function is not actually executed and I do not get any email.

Where did I go wrong?

    
asked by anonymous 01.07.2014 / 13:13

1 answer

1

You can make this call in another way that I will explain below:

Use the wp_enqueue_script function to register your script (full information in Wordpress Codex link ).

wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer );

Brief explanation:

$ handle = Name for the script, eg bootstrap-script;

$ src = Path to your file;

$ deps = If there are other files that need to be loaded before;

$ ver = Version for the script;

$ in_footer = Whether it should be displayed in the footer or not;

After you make this call you add the following line (full information in Wordpress Codex link ).

wp_localize_script( $handle, $name, $data );

Explanation:

$ handle = The name of the script you previously registered;

$ name = Name that will be available in your theme for Ajax requests;

$ data = Address of the file responsible for the requests. As in Wordpress the file responsible for ajax requests is admin-ajax.php, you can put that way admin_url ('admin-ajax.php');

With this setting now in your theme there will be a variable that can be used in the Ajax call url.

In order for it to work, you need to create your function and pass as add-action hook parameter as follows:

add_action( 'wp_ajax_nome_acao', 'nome_funcao_php' );
add_action( 'wp_ajax_nopriv_nome_acao', 'nome_funcao_php' );

Explaining:

The call to wp_ajax is to register its function for logged in user and wp_ajax_nopriv is for user not logged into the manager, so it can be used on the entire site.

Now in your javascript function do:

$.ajax({
    type: 'POST',
    dataType: 'json',
    cache: false,
    url: NOME_VARiAVEL_AJAX,
    data: 'action=nome_acao_ajax&' + formData,
    success: function(data){
        alert(data);
        $('#form-contact').trigger('reset');
    },
    error: function(){
        alert("Deu erro aqui!");
    }
});

Where VARiAVEL_AJAX_NAME is the same as you created in wp_localize_script ();

You need to pass an action parameter with the name of the function you want to call in your php, in which case it is the name of the action you gave in add_action.

Passing the action name Wordpress does the rest when there is an Ajax request.

    
04.07.2014 / 16:14