Support » Developing with WordPress » How to connect to wordpress database and show data from the logged user?

  • Resolved mysteryintime

    (@mysteryintime)


    I’m not a programer. This is my first time coding and first time working with wordpress. It’s just a personal project.
    Please have patience with my noob question.

    I’m trying to connect to wordpress database and show data from the logged user.
    First I got a plugin (https://wordpress.org/plugins/easy-registration-forms/) that allow me to add custom fields into user registration form and then add the answers to wp_usermeta.

    Then I found and modify (with a friend’s help) a code that should conect to database and show the data. And it does show the data. But just in localhost (XAMPP). It stops working when I pass the files to wordpress online server by FTP.

    How am I suppose to put this code online? Is there a specific folder? Should I make it a Template? I’m totally lost.
    The code has two files because that was the only tutorial I could find and understand on how to do.

    The error is:

    VM184:1 Uncaught SyntaxError: Unexpected end of JSON input
        at JSON.parse (<anonymous>)
        at XMLHttpRequest.ajax.onreadystatechange (index3.php:33)

    Main page:

    
    <table style="text-align: center;">
      <tr>
        <th>Nickname</th>
        <th>First Name</th>
        <th>Pontos de Classe</th>
        <th>Pontos de Ra├ža</th>
        <th>Perfil Vk</th>
      </tr>
      <tbody id="data"> <!-- data will be displayed here -->
    
      </tbody>
    </table>
    <div id="div1">
    
    </div>
    <script>
        // call ajax
        var ajax = new XMLHttpRequest ();
        var method = "GET";
        var url = "http://my_site.com/data.php";
        var asynchronous = true;
    
        ajax.open (method, url, asynchronous);
        // sending ajax request
        ajax.send ();
    
        // receiving response from data2.php
        ajax.onreadystatechange = function ()
        {
          if(this.readyState == 4 && this.status == 200)
          {
            //converting JSON back to array
            var data = JSON.parse(this.responseText);
            console.log(data); //for debugging
    
            // HTML value for <tbody>
            var html = "";
            // Looping through the data
              var nickname = data.nickname;
              var first_name = data.first_name;
              var user_pc = data.user_pc;
              var user_pr = data.user_pr;
              var user_vk = data.user_vk;
    
              //storing in html
              html += "<tr>";
                html += "<td>" + nickname + "</td>";
                html += "<td>" + first_name + "</td>";
                html += "<td>" + user_pc + "</td>";
                html += "<td>" + user_pr + "</td>";
                html += "<td>" + user_vk + "</td>";
              html += "</tr>";
    
              // replacing the <tbody> of <table>
              document.getElementById("data").innerHTML = html;
          }
        }
    </script>

    Data File:

    <?php
    
    //Connect to take data from database
    $conn = mysqli_connect("my_db_server", "my_db_user", "my_db_password", "my_db_name");
    
    $user_id =  "1"; // Identify logged user
    $query = 'SELECT * FROM wp_usermeta WHERE user_id = ' . $user_id; // Results from this specific User
    $result = mysqli_query($conn, $query);
    
    // Create keys and values to ask latter with "data.field_name"
    $keys = array();
    $values = array();
    while ($row = mysqli_fetch_assoc($result))
    {
      array_push($keys, $row['meta_key']);
      array_push($values, $row['meta_value']);
    }
    
    $return = array_combine($keys, $values);
    
    // Returning responde in JSON format
    
    echo json_encode($return);

    Thanks for your help!

Viewing 4 replies - 1 through 4 (of 4 total)
  • kjodle

    (@kjodle)

    Where do you want this data to appear? My first thought is to create a child theme and add in the appropriate code there.

    mysteryintime

    (@mysteryintime)

    Everything I need to appear in the website will be in that “Main page”.
    Currently there are just random data to test. As soon as I’m able to recieve the data from database I’ll take some numbers and apply in an RPG’s Level Up system that I created here with javascript: http://mysteryintime.ihostfull.com/perfil/habilidades/

    I just need to:
    – Be able to set Points to each user (what I’ve done with the plugin)
    – Be able to call the Point’s field in the user profile to that Level Up page and use it inside the javascript.

    The problem is the second part. There are weeks since I’m trying to connect to the database and still couldn’t get it.

    The data.php just exists because as I do not know how to code I was traped to the tutorial and the guy in the video used two files. I’m uploading the data.php in the wordpress public directory and trying to call it inside the “Main Page” by the url. Like:

     var ajax = new XMLHttpRequest ();
        var method = "GET";
        var url = "http://mysteryintime.ihostfull.com/data.php";
        var asynchronous = true;

    The “Main Page” is in:

    http://mysteryintime.ihostfull.com/wp-content/themes/oceanwp/main-page.php

    So I go to wordpres, I create a New Page, and then I use “Main Page” as a Template.
    It shows all the layout, but do not recive the data from database.

    Moderator bcworkz

    (@bcworkz)

    It appears you are using Ajax to get data that is related to the current user and not related to any user input. While this may be a valid learning exercise, it’s illogical from a practical standpoint. The current user and related data can all be determined and output with the initial request without resorting to Ajax. Ajax is mainly used to get data from the server based on user input that cannot be known when the page was requested. For example, maybe there is data for multiple RPGs. The user selects a particular game and the related data appears in the relevant fields on the page. The user can repeatedly select different games and see related data, all without needing to reload the page.

    Even that is a poor example if there are only 5 fields per game, you could easily output related fields from all games on one page from the onset. Ajax is best when there is too much data to cover all possible variables that could be reasonably contained on a single page. In any case, Ajax coding is a good skill to develop if you intend to continue to learn coding. If you just want this to work and don’t care to learn more than you have to, send all the data with the page output and don’t bother with Ajax.

    Using pure JS and PHP to manage Ajax as you are doing is perfectly fine, but on WP sites, you will sooner or later find it more useful to use WP functions to do things. Using Ajax as you have does not allow the use of WP functions. To make Ajax requests which utilize WP functions, you need to do so in a specific way which is different from what you are currently doing. This way is detailed in the Plugin Handbook. While this is oriented towards plugins, the same approach can be utilized with a child theme like kjodle suggested. You do not want to place custom files with your primary theme. When the theme is updated, your custom files will be deleted.

    The examples use jQuery to make Ajax requests. You can still use XMLHttpRequest if you want, client side code is not where WP specific methods are required. jQuery is a little easier (in some cases a lot easier) to code with, and the jQuery library is local to your server anyway, so there is little reason not to use jQuery. If nothing else, it’ll make following the examples easier. Don’t be afraid of needing to learn yet another language, jQuery is essentially extended JS functions. You are still basically coding with JS.

    You did get one thing right, the concept of first getting simple, basic data to make a round trip, then building upon that basic foundation. There are many things that need to correctly come together for Ajax to work. Adding further complications when trying to learn just makes for more frustration.

    kjodle, thank you for your sugestion about the Child Theme. I’ll definitely look on it.

    Bcworkz, thank you very much for your kindly explanation. It’s pretty sad to lost the code, but as this is the the way to go I’ll have to start over.

    As you told me about plugins documentation I took a look and found out this code used to create a registration plugin. It just adds one more field (date of birth) but I gues I can just duplicate as much as I want the field and get all the ones I need.

    https://www.cssigniter.com/how-to-add-custom-fields-to-the-wordpress-registration-form/

    As the code is ready, it’ll be a quickly test anyway. And I can save it to use in the future in other sites that I may engage. I’m not sure if I’ll keep coding but see a page working after the creation is really pleasent. So for now I’ll go a little futher.

    Have a good day you both.
    Thanks again for everything! <3

Viewing 4 replies - 1 through 4 (of 4 total)
  • You must be logged in to reply to this topic.