Request AJAX Wordpress with problems

Asked

Viewed 751 times

1

I am developing a form template within a wordpress theme. I need the form data to be sent via e-mail to a certain address via AJAX. Here is the processing of the form 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 only for study purposes anyway. Omitting the methods I believe to make no difference, I proceed.

$('#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 for the 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. In fact, I receive the success message as a response. However, the PHP function is not really executed and I do not receive any email.

Where I went wrong?

  • Where do you call the function sendMail() in PHP?

  • I don’t actually call the function in PHP. sendmail is a PHP function that just decodes the json object and uses it as an argument for the mail function. In this case, this json object is passed at the time of the request.

  • @Sergio, in theory, the sendMail should be defined within of the object formData, but this is not in the code displayed... . . . . Pedro, which "function is not actually executed"? The mail() PHP? It is not clear which error you are talking about, because it showed a lot of code to end up talking about something else (?).

  • Yes @brasofilo. The mail() function that does not execute. The Success function in javascript is executed. The data is being sent to php’s function as json object, but for some reason, the function in php is not running or something is wrong.

  • Try with wp_mail and activating the SMTP

  • @brasofilo, I’ve tried this too :-/ SMTP enabled. My code is correct?

  • As I said, you speak of Ajax, form, JS, Wordpress, but in the end your problem is PHP Mail :/ If you want to solve this problem, please edit the question to reflect this (citing that you have already tried wp_mail and smtp). . . . . I would make some security adjustments and use of native WP functions, but if the code works and the Ajax request returns correctly, then yes, the code is ok. Your problem is elsewhere...

  • @Brasofilo, they’re all related matters. I just described the problem with its details, because I don’t know where my mistake is and I thought that would be easier to understand. But that’s okay.

  • It’s just that I don’t think it’s about one thing and another, and you’re concentrating on technical details where there’s nothing wrong... Check the results in the OS for [php] debug mail.

Show 4 more comments

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 (complete information in Wordpress Codex http://codex.wordpress.org/Function_Reference/wp_enqueue_script).

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

Brief explanation:

$Handle = Name for the script, for example bootstrap-script;

$src = Path to your file;

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

$ver = Script version;

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

After you make this call you add the line below (complete information in Wordpress Codex http://codex.wordpress.org/Function_Reference/wp_localize_script).

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 the ajax requests is admin-ajax.php, you can put this way admin_url( 'admin-ajax.php' );

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

To make it work, you need to create your function and pass as parameter of the add_action hook 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 non-logged user in the manager, so it can be used in 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 the Ajax Name is the same as the one 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.