Search code examples
phphtmlmysqlglobal-variables

how can I turn the content of the span into a php variable / How do I start a mysql query when clicking a word and send that word to _post in php


I am building a dictionary and I have my words and definitions stored in a MySQL database. I want to make some words clickable (maybe as spans or buttons) so when I click them a new query that has this word as key starts (so how can I send the content of this clicked word into to _post in my details.php file)? Or how can I turn the content of the span into a php variable?

<html>
    Click this <button>word</button>
</html>

<?php 
    
    echo "You clicked that " $word;
    
?>

Solution

  • MySQL communicates with your server-side code (PHP).

    Your PHP code reads/writes data into MySQL, generates (or loads) HTML templates that are sent to the browser when requested.

    Your browser requests a page via URL when someone visits your site, sending a request to your URL and getting some response, presumably HTML in return.

    From the moment when the page is received, CSS rules are being applied with design purpose and programmatic code (Javascript) is being executed.

    Now, your span is part of your HTML, which was either received from the server, or generated by your client-side code (Javascript).

    It is important to note that in production mode the browser and the PHP code are running on different, remote computers and sometimes the MySQL RDBMS is also running on a separate computer, a database server.

    So, the thing you want to do is to have a Javascript event that sends some content to your server, which processes it and then stores it into your MySQL database.

    Event creation via Javascript

    Read this article: https://developer.mozilla.org/en-US/docs/Web/Events/Creating_and_triggering_events

    Basically you will need to create an event, which will either be an

    onclick="yourJavascript()"
    

    or a call to addEventListener. Try to implement a trivial example for that, like below:

        document.getElementById("mybutton").addEventListener('click', function() {
            alert("Yay! The click was handled!");
        });
        <input type="button" value="click me" id="mybutton">

    Later on you will need to replace the function body with a request sending.

    Send an AJAX post request and receive a callback

    Read this article: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest

    Read this article as well: https://javascript.info/xmlhttprequest

    Example:

        let xhr = new XMLHttpRequest();
        xhr.open("POST", URL, somedata);
        xhr.send();
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 3) {
                // loading
            }
            if (xhr.readyState == 4) {
                // request finished
            }
        };
    

    It is worth converting something similar to a parameterizable function so in the future you would be able to reuse most of the benefits of your current work. And call this function I just suggested in your event listener.

    Explanation:

    • XMLHttpRequest is the type you instantiate in order to send an AJAX request
    • xhr is the resulting object of the instantiation
    • xhr.open is a function that you need to call, passing the request method (which is "POST" in this case, the URL, which is the target and some data)
    • somedata is a variable the code above assumes that was already defined, but you will need to properly initialize it yourself
    • send is sending the request, in our case asynchronously, that is, the request will not end yet when the next line is processed
    • xhr.onreadystatechange is a callback which is executed when the ready state changes; state 3 is loading, state 4 is request finished, so your meaningful code should be inside the if that checks for the state being 4

    Handle POST requests with PHP

    Read this article: https://www.codegrepper.com/code-examples/php/php+handle+post+request

    Basically you will have your data in $_POST, you can process whatever logic you want and you can generate an HTML/JSON/whatever response the way you like.

    PHP - MySQL

    You can generate MySQL queries with PHP and you can use PDO, for example, to generate parameterized queries and sanitize your dynamic parameters, especially those defined by the users, to avoid SQL injection.