Home > Software engineering >  Can't save data in WordPress via AJAX (plugin)
Can't save data in WordPress via AJAX (plugin)

Time:05-23

I'm working in a new plugin and I want the users use a form to send his/her email. This email would be saved in a custom table in the database.

This is the html form:

<form  action="#" method="post" data-url="<?php echo verde_product_info('extend_url') ?>">
<input type="hidden" name="language" value="<?php echo verde_top('language'); ?>">
<input type="hidden" name="database" value="<?php echo $wpdb->prefix; ?>">
<input type="email" name="email" placeholder="Email" required>
<button type="submit" >Send</button>
</form>

When it is sending, the js code is the next:

var urlplugin = jQuery('.subscribe-database').attr('data-url');
    
    jQuery('.subscribe form').submit(function() {
        var postdata = jQuery('.subscribe form').serialize();
        jQuery.ajax({
            type: 'POST',
            url: urlplugin   '/themes/php/sendmail.php',
            data: postdata, 
            dataType: 'json',
            success: function(json) {
                console.log(json);
            },
            error: function (xhr, ajaxOptions, thrownError) {
                console.log(xhr.status);
                console.log(thrownError);
            }
        });
        return false;
    });

And the file sendmail.php when the error happens is the next one:

global $wpdb;


if(!isset($wpdb))
{
    require_once('../../../../../wp-includes/wp-db.php');
}

switch ($_POST['language']) {
    case 'english':
        $success1 = 'Thanks for your subscription!';
        $error1 = 'Insert a valid email address';
        break;
    case 'spanish':
        $success1 = '&#161;Gracias por tu suscripci&oacute;n!';
        $error1 = 'Escribe un email v&aacute;lido';
        break;
    case 'french':
        $success1 = 'Merci pour votre abonnement!';
        $error1 = 'Ins&eacute;rez une adresse e-mail valide';
        break;
    case 'german':
        $success1 = 'Vielen Dank f&#252;r Ihr Abonnement!';
        $error1 = 'Legen Sie eine g&#252;ltige E-Mail-Adresse';
        break;
    case 'italian':
        $success1 = 'Grazie per il vostro abbonamento!';
        $error1 = 'Inserire un indirizzo email valido';
        break;
    case 'portuguese':
        $success1 = 'Obrigado pela sua inscri&#231;&#227;o!';
        $error1 = 'Insira um email v&aacute;lido';
        break;
}

function isEmail($email) {
    return(preg_match("/^[-_.[:alnum:]] @((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.) (ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i", $email));
}

if($_POST['email']) {
    $table = $_POST['database'] . 'verde_emails';
    $subscriber_email = ($_POST['email']);

    if(!isEmail($subscriber_email)) {
        $array = array();
        $array['valid'] = 0;
        $array['message'] = $error1;
        echo json_encode($array); 
    }
    else {
        $array = array();
        $array['valid'] = 1;
        $array['message'] = $success1;
        echo json_encode($array);
        $wpdb->insert( 
            $table, 
            array( 
                'option_email' => $subscriber_email, 
            )
        )
    }
}

When I use the form I get the next error in the browser console:

200
scripts-new.js:43 SyntaxError: Unexpected token < in JSON at position 0
    at JSON.parse (<anonymous>)
    at parseJSON (jquery-1.9.1.min.js:2:4322)
    at Fn (jquery-1.9.1.min.js:4:15175)
    at k (jquery-1.9.1.min.js:4:13895)
    at XMLHttpRequest.r (jquery-1.9.1.min.js:4:18226)

But it works fine if I comment the next code in the file sendmail.php:

$wpdb->insert( 
$table, 
    array( 
        'option_email' => $subscriber_email, 
    )
)

but obviously, the email can't be saved in the database.

I'm lost with this error and I will be very grateful if someone can help me.

Sorry for my English and thank you very much.

CodePudding user response:

Please remove this part of code and post what happens if you are inside Wordpress you don't need this, if you are outside Wordpress you need to include more than that, wp_load.php for ex.

if(!isset($wpdb))
{
    require_once('../../../../../wp-includes/wp-db.php');
}

CodePudding user response:

When I load the file wp-db.php there is not any error, but when I load the file wp_load.php the same error happens.

  • Related