Home > Software engineering >  send post to insert a row in database
send post to insert a row in database

Time:08-20

hello i started to learn php and js i trying to insert a row in wordpress database tablet, getting the info need to insert from another table but i having a problem with php file it not insert in the database here is the code i trying

<?php

/*
plugin name: test
description: local
author uri: local
*/
function set_items_list(){
}
?>

<div  data-id="1">
<a href="#" >TEST</a>
</div>
<div  data-id="2">
<a href="#" >TEST</a>
</div>
<div  data-id="3">
<a href="#" >TEST</a>
</div>

<script>
     var itemnodes = document.getElementsByClassName('item-preview');
     var item = document.getElementsByClassName("item");
     
        for (var i = 0, size = itemnodes.length; i < size; i  ) {
            itemnodes[i].addEventListener('click', function(i) {
            var id = item[i].getAttribute('data-id');
            console.log(id);
            var xhttp = new XMLHttpRequest();
            xhttp.open("POST", "files/test.php", true); 
            xhttp.setRequestHeader("Content-Type", "application/json");
            xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {

            var response = this.responseText;
            console.log(response);
             }
        };
        
        var data = {id:id};
        xhttp.send(JSON.stringify(data));

         }.bind(null, i));
    }
    </script>
<?php

add_shortcode('list','set_items_list');

and the php file

<?php
$contents = file_get_contents('php://input');
$jsondata = json_decode($contents, true);
    global $wpdb;


$wpdb->insert('add_items',array('FirstName'=> 'test1','SecondName'=> 'test2'));

echo $jsondata['id'];

exit;
?>

what i need is when press on a it read the data-id from item and send it to php to insert the row in the database everything is working right except php part at insert it showing in the console

Post 500 (anonymous) @ (index):34

CodePudding user response:

I'm not 100% sure, but it might be the line var data = {id:dataid};

I think you want var data = {"id": id} instead.

  • Related