I have made a quick $wpdb->insert
function that adds content with an AJAX function.
The goal is to insert the form data into a table.
Here is my Javascript function calling the ajax:
$(".modal__form").submit(function(e){
e.preventDefault();
$.post(
ajaxurl,
{
'action': 'add_to_newsletter',
'param': $(this).serialize()
},
function(response){
if(response == 'success') {
$('.modal__form').hide();
$('.modal__box .text__success').show();
}
}
);
});
The form data in headers can be printed as :
action: add_to_newsletter
param: firstname=FIRSTNAME&lastname=LASTNAME&email=EMAIL%40DOMAIN.COM&type=TYPE
On my function, I have this :
function add_to_newsletter() {
global $wpdb;
$table = $wpdb->prefix.'newsletter';
$param = $_POST['param'];
if($wpdb->insert($table, array(
'firstname' => $param['firstname'],
'lastname' => $param['lastname'],
'email' => $param['email'],
'ip' => $_SERVER['REMOTE_ADDR']
),
array( '%s', '%s', '%s', '%s')
)) {
var_dump($wpdb);
echo 'success';
}
else {
$wpdb->print_error();
}
die();
}
add_action( 'wp_ajax_add_to_newsletter', 'add_to_newsletter' );
add_action( 'wp_ajax_nopriv_add_to_newsletter', 'add_to_newsletter' );
The problem is that I only got strange things on the database when posted.
Here is the var_dump()
return.
"INSERT INTO 'actz_newsletter' ('firstname', 'lastname', 'email', 'ip') VALUES ('f', 'f', 'f', '::1')"
Anyone ever expected something similar? I am clueless about my research.
wp_json_encode
the parameters instead of serializing. Then you need to decode once you receive them. – MikeNGarrett Jun 5 '19 at 17:51