skip to Main Content

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


  1. Chosen as BEST ANSWER

    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:

    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.getElementById('form-field-ajax_send_name').value + '&bestellung=' + document.getElementById('form-field-ajax_send_details').value;
        var asynchronous = true;
        
        ajax.open(method, url, asynchronous);
        ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
        
        // 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");
        };
    })


  2. at first you confirm that your WordPress have connected with ajax CDN. If not connected then enque ajax CDN to your functions.php file.
    Then, Write HTML form like,

    <form>
       <label for="Name">Name</label>
       <input type="text" name="name" id="name">
       <label for="Date of Birth">Date of Birth</label>
       <input type="date" name="dob" id="dob">
       <label for="Address">Address</label>
       <input type="text" name="address" id="address">
       <input type="submit" value="Submit" id="dataForm-submit">
    </form>

    After Completed HTML Form, you write this Jscript Code,

    <script>
    jQuery(document).on('submit','#dataForm-submit', function(){
     jQuery.ajax({
      type:'POST',
      url:'<?php echo admin_url('admin-ajax.php');?>',
      data:'action=dataform_submition&'+jQuery('form').serialize(),
      success:function(data){
       console.log(data);
      }
     });
    });
    </script>
    

    Now, wirte your PHP functions page,

    add_action('wp_ajax_dataform_submition', 'dataform_submition');
    add_action('wp_ajax_nopriv_dataform_submition', 'dataform_submition');
    
    function dataform_submition(){
     global $wpdb;
     $table = $wpdb->prefix . 'Your-Table Name';
     extract($_POST);
     $wpdb->query($wpdb->insert($table, array(name=>$name, dob=$dob, 
     address=$address), array('%s','%s','%s'));
     echo 'success';
     exit();
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search