send post to insert a row in database - Hack The Tech - Latest News related to Computer and Technology

Hack The Tech - Latest News related to Computer and Technology

Get Daily Latest News related to Computer and Technology and hack the world.

Saturday, August 20, 2022

send post to insert a row in database

hello i started to learn php and js i trying to insert a row in database tablet, getting the info want to insert from another table but i having a problem with sending post part

<?php

/*
plugin name: test
description: local
author uri: local
*/
function set_items_list($id){
    global $wpdb;

    $info = $wpdb->get_results("SELECT get_items.FirstName, get_items.SecondName
    FROM get_items 
    WHERE get_items.Id = $id");

$wpdb->insert('add_items',array('FirstName'=> $info[0]->FirstName,'SecondName'=> $info[0]->SecondName));
}

?>

<div class="item" data-id="1">
<a href="#" class="item-preview">TEST</a>
</div>
<div class="item" data-id="2">
<a href="#" class="item-preview">TEST</a>
</div>
<div class="item" data-id="3">
<a href="#" class="item-preview">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');// get the data-id from a
            console.log(id);// log the data-id

            var xhttp = new XMLHttpRequest();
            xhttp.open("POST", "", 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');

i also have tried to add the php into a file like

<?php 
$id;
global $wpdb;

    $info = $wpdb->get_results("SELECT get_items.FirstName, get_items.SecondName
    FROM get_items 
    WHERE get_items.Id = $id");

$wpdb->insert('add_items',array('FirstName'=> $info[0]->FirstName,'SecondName'=> $info[0]->SecondName));
?>

and change this line

 xhttp.open("POST", "", true);  to -> xhttp.open("POST", "file/test.php", true);

but also nothing happened

what i need is when press on a class="item-preview" 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 how i can fix it please



source https://stackoverflow.com/questions/73420717/send-post-to-insert-a-row-in-database

No comments:

Post a Comment