0

I have both JavaScript and a PHP function on the same document.

this is my PHP function which makes an API request and returns me the data.

How to make the request onClick of the button and update the results dynamically, should I use Ajax or is there another solution

Updated question: So my issue now is I just need to figure out how to pass the getAnswer function in the play of URL when I am using AJAX in the end of the script.

<?php
require './Url.php';
function getAnswer($question)
{
    return $answer_result;
}
?>
  <!doctype html>
  <html lang="en">

  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="./bot.css" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <title>Bot</title>
  </head>

  <body class="container h-100">
    <div class="outer">
      <div class="middle">
        <div class="inner p-2" id="inner">
          <h4 class="text-center">Hello there! how can I help?</h4>
          <hr />
          <p class="text-left text-light"><span class="bg-primary rounded p-1 m-1">I am designed by the WebShop team. How can I help?</span></p>
          <p class="text-right text-light"><span class="bg-dark rounded p-1 m-1">Hey what is your name?</span></p>
          <p class="text-left text-light"><span class="bg-primary rounded p-1 m-1">I do not have a name yet.</span></p>

        </div>
        <div class="d-flex justify-content-center mt-1">
          <div class="d-flex justify-content-around" style="width: 35rem;">
            <input type="text" class="form-control" id="input" placeholder="Type here..." />
            <button type="button" class="btn btn-outline-primary" id="send" onclick="send()">Send</button>
          </div>
        </div>
      </div>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.js" integrity="sha512-n/4gHW3atM3QqRcbCn6ewmpxcLAHGaDjpEBu4xZd47N0W2oQ+6q7oc3PXstrJYXcbNU1OHdQ1T7pAP+gi5Yu8g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script type="text/javascript">
      function send() {
        var input = document.getElementById('input').value;
        if (input) {
          var box = document.getElementById("inner");
          var para = document.createElement("p");
          para.className = "text-right text-light";
          var span = document.createElement("span");
          span.className = "bg-dark rounded p-1 m-1";
          span.innerHTML = input;
          para.appendChild(span);
          box.appendChild(para);
          document.getElementById('input').value = "";
          // call the getAnswer function directly from here usnig ajax and send the input as a parameter
          $.ajax({
            url: './chatbot.php',
            type: 'POST',
            data: {
              input: input
            },
            success: function(response) {
              console.log(response);
              var para = document.createElement("p");
              para.className = "text-left text-light";
              var span = document.createElement("span");
              span.className = "bg-primary rounded p-1 m-1";
              span.innerHTML = response;
              para.appendChild(span);
              box.appendChild(para);
            }
          });


        }
      }
    </script>
  </body>


  </html>




  <!-- <script type="text/javascript">
    function send() {
        var input = document.getElementById('input').value;
        if (input) {
            var box = document.getElementById("inner");
            var para = document.createElement("p");
            para.className = "text-right text-light";
            var span = document.createElement("span");
            span.className = "bg-dark rounded p-1 m-1";
            span.innerHTML = input;
            para.appendChild(span);
            box.appendChild(para);
            document.getElementById('input').value = "";
            // AJAX call
            $.ajax({
                url: './chatbot.php',
                type: 'POST',
                data: {
                    'question': input
                },
                success: function(response) {
                    console.log(response);
                    var para = document.createElement("p");
                    para.className = "text-left text-light";
                    var span = document.createElement("span");
                    span.className = "bg-primary rounded p-1 m-1";
                    span.innerHTML = response;
                    para.appendChild(span);
                    box.appendChild(para);
                }
            });
        } else {
            alert("Please enter a message");
        }
    }
</script> -->
WildThing
  • 969
  • 1
  • 12
  • 30
  • 1
    If you want to make PHP code run you have to send a HTTP request from the browser to the server. There are a number of ways to achieve that - 1) the user clicks a link, 2) the user submits a form, or 3) the user clicks on a button/other element and you (the programmer) then handle that with Javascript can cause either a) the browser to navigate to a new URL, b) the browser to submit a (hidden) form, or c) the browser to make an AJAX request to the server asynchronously. Those options are available in any web page, the world is your oyster, choose an approach and go for it. – ADyson Apr 20 '22 at 11:05
  • 1
    You can use JQuery Ajax for fetching the data and update dynamically – sree Apr 20 '22 at 11:07
  • 1
    @sree Just to avoid confusion: AJAX is not exclusive to jQuery – RiggsFolly Apr 20 '22 at 11:17
  • Thank you all for the quick explanation, I was able to understand the link a little and I have updated the code snippet. Please refer to the updated code, In this case, how do I call the function now, the response I am supposed to get is just a string and I want to append it to the end of the previous element. But I see that I need to send the url , how do I send my function there instead? – WildThing Apr 20 '22 at 12:01

0 Answers0