0

How can I echo the response of a php script on my current page when I click on a button? I know how I can run a php script without leaving the page. The problem is that the response (echo) is not shown on the page where the user is. My current solution is to call the current site from a form and handle the response like that but is it possible to do that without refreshing the page?

<?php
if (isset($_POST['message'])) {
  echo $_POST['message'];
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
  <title>Sandbox</title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="styles/style.css">
</head>

<body>
  <form class="form" action="index.php" method="post">
    <input type="text" class="textfield" name="message" id="message">
    <input type="submit" class="button" value="send">
  </form>
</body>

</html>

Normally I would use Javascript for tasks like that but in this case I have to use php. I also tried to make a JS post request against a php file but this solution felt not "clean".

Keanu Hie
  • 297
  • 2
  • 8
  • 12

4 Answers4

1

The only way to get a response from PHP (or anything else that executes on the server) is to make an HTTP request to it.

If you don't want to leave the current page then your options are:

  • Set target="_blank" in the form to open the response in a new tab or window
  • Add an iframe to the document and set target="name_of_iframe" to open the response in the iframe
  • Make the HTTP request with JavaScript and display the response using DOM manipulation. This technique is known as Ajax and the Internet is awash with tutorials on it.
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • First thanks for your suggestions. Your first point isn't something I want. The content should update without reloading or opening the page in a new tab/window. The iframe method doesn't work in my case, because I don't get the response on my page. The last point is the method which I will use. I thought there is a better solution for my problem (that's why I asked this question here) but unfortunately there is none – Keanu Hie Apr 18 '19 at 08:31
1

Using Jquery and its ajax function and without form :

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<input type="text" class="textfield" name="message" id="message">
<button id="btn_callajax">Envoyer</button>
<p id="getajaxresponse"></p>
 <script>
   $document).ready(function(){

$("#btn_callajax").click(function(){
 var my_msg = $("#message").val();
$.ajax({
   url : 'getajaxcall_respback.php',
   type : 'POST', 
   data : 'my_msg='+my_msg, 
   dataType : 'html',
   success : function(htmlresponse, statut){
       $("#getajaxresponse").html(htmlresponse); 
   },

   error : function(responses, statut, error){

   }
 });
});
});</script>

In the getajaxcall_respback.php file :

if( isset($_POST['my_msg'])
{
 $mesg = $_POST['my_msg'];

 //get your database request ?

 echo "send your html code back to your index.php"; 
}
sylvain
  • 853
  • 1
  • 7
  • 20
  • Thanks for your comment. I decided to stick with the javascript post request because I'm not a fan of jQuery but still thanks for your suggestion. – Keanu Hie Apr 18 '19 at 08:31
1

You can use the Ajax for this.

Add jquery library in your code and than write below ajax code:

$('body').on('click', '.button',function(){
    $.ajax({
      type: 'POST',
      url: 'post.php',
    })
    .done(function (response) {
      $('.message').html(response);
    });
    return false;
  });

In post.php file write below code:

<?php 
if (isset($_POST['message'])) {
  echo $_POST['message'];
}
Jaimin Rlogical
  • 256
  • 1
  • 11
1

You can use Ajax form submit script using PHP like.

<?php
if (isset($_POST['message'])) {
  echo $_POST['message'];
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
  <title>Sandbox</title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="styles/style.css">
</head>

<body>
  <div class="alert-msg"></div>
  <form class="form" id="myForm" action="index.php" method="post">
    <input type="text" class="textfield" name="message" id="message">
    <input type="submit" class="button submit-btn" value="send">
  </form>
// you can use add this script in body tag
<script type="text/javascript">
    // -------   Mail Send ajax

     $(document).ready(function() {
        var form = $('#myForm'); // contact form
        var submit = $('.submit-btn'); // submit button
        var alert = $('.alert-msg'); // alert div for show alert message

        // form submit event
        form.on('submit', function(e) {
            e.preventDefault(); // prevent default form submit

            $.ajax({
                url: 'index.php', // form action url
                type: 'POST', // form submit method get/post
                dataType: 'html', // request type html/json/xml
                data: form.serialize(), // serialize form data
                beforeSend: function() {
                    alert.fadeOut();
                    submit.html('Sending....'); // change submit button text
                },
                success: function(data) {
                    alert.html(data).fadeIn(); // fade in response data
                    form.trigger('reset'); // reset form
                    submit.attr("style", "display: none !important");; // reset submit button text
                },
                error: function(e) {
                    console.log(e)
                }
            });
        });
    });
</script>
</body>
</html>
  • Thanks for your comment. I decided to stick with the javascript post request because I'm not a fan of jQuery but still thanks for your suggestion. – Keanu Hie Apr 18 '19 at 08:31