I’m trying to achieve a simple custom AJAX request from my WordPress Page.
I don’t want to use form data but custom data from input fields.
When I try to use the data, that is send by the AJAX Call it does not work. Though it works when I do not send custom data within the AJAX Call and only trigger the insert.php file, where I manually set the Strings.
Can please anyone help me 🙂 ?
HTML
<input type="text" id="form-field-ajax_send_name">
<input type="text" id="form-field-ajax_send_detail">
<div id="ajax-send-button">SEND AJAX DATA</div>
JAVASCRIPT
document.querySelector('#ajax-send-button').addEventListener('click', function () {
// AJAX aufrufen
var ajax = new XMLHttpRequest();
var method = 'POST';
var url = 'insert.php';
var data = {name: document.querySelector('#form-field-ajax_send_name').value, details: document.querySelector('#form-field-ajax_send_detail').value}
var asynchronous = true;
ajax.open(method, url, asynchronous);
// AJAX Anfrage senden
ajax.send(data);
// Antwort der Anfrage erhalten
ajax.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
alert('Done!');
} else if (this.status === 201) {
alert('Fehler!')
}
}
ajax.onerror = function () {
alert("Request failed");
};
})
PHP
<?php
include_once "wp-config.php";
global $wpdb;
$p_name = $_POST["name"];
$p_details = $_POST["details"];
$insertedData = array(
'name' => $p_name,
'details' => $p_details,
);
$wpdb->insert('mytable', $insertedData);
?>
2
Answers
Thank you everyone :)
I found a solution. I needed to fix it within the js-code and set the request header first + then adapt the data so a string.
So Javascript AJAX would be: