0

I want to display the echoed text from my PHP file into a 'p' text in my main html page (main.php)

I connect to a database to retrieve the data I want and in that PHP page, I currently have it to echo a text depending on what data is available in the database.

Right now, in my main.php page I have a button called "Search" which redirects me to another availability.php page that displays a echo message telling me my result. I want that message to display in my main page without refreshing the page.

Following is my PHP file.

<?php
session_start();
include "php/db.php";

/////////////////////////////////////////////////////

$checkin = $_POST['checkin'];
$checkout = $_POST['checkout'];

$date1=date_create("$checkin");
$date2=date_create("$checkout");
$diff=date_diff($date1,$date2) ->format ("%a");
$nightsStaying = (int) ("$diff");

////////////////////////////////////////////////////

$peopleString = $_POST['people'];
$people = (int) "$peopleString"; //converts people string to int

//////////////////////////////////////////////////// 


if ($people > 1){
    $results = $db->query("SELECT * FROM availability WHERE date >= '$checkin' AND date < '$checkout' AND (droom > 0 OR suite > 0) ")->fetchALL(PDO::FETCH_ASSOC); 
    // Checks if a double room or suite are available on the days requested
    $resultsCount = count($results); //checks how many rows are retrieved
    
    if ($resultsCount == $nightsStaying){
        echo "There are available rooms";
    }else{
        echo "There is no availability for the selected dates";
    }
}
else {
    $results = $db->query("SELECT * FROM availability WHERE date >= '$checkin' AND date < '$checkout' AND (sroom > 0 OR droom > 0 OR suite > 0) ")->fetchALL(PDO::FETCH_ASSOC); 
    // CHECK FOR ANY ROOM IS GREATER THAN 0.
    $resultsCount = count($results);
    
    if ($resultsCount == $nightsStaying){
        echo "There are available rooms";
    }else{
        echo "There is no availability for the selected dates";
    }
}
?>

HTML part:

<form  id="availabilitySearch" action="availability.php" method="post">
    
<div class="d-flex justify-content-center container">

    <div class="col m2">

        <label><i class="fa fa-calendar-o"></i> Check In</label>

        <input id="checkin" class="input border" name="checkin" type="date">
    </div>

    <div class="col m2">

        <label><i class="fa fa-calendar-o"></i> Check Out</label>

        <input id="checkout" class="input border" name="checkout" type="date">
    </div>

    <div class="col m2">

        <label><i class="fa fa-male"></i> People</label>

        <input id="people" class="input border" name="people" type="number" placeholder="1">
    </div>

    <div class="col m2">

        <label><i class="fa fa-search"></i> Search</label>

        <button type="submit" class="button block black">Search</button>
    </div>
</div>
</form>

<div>
    <!-- THIS IS WHERE I WANT THE AJAX SCRIPT TO SHOW THE RESULT-->
    <p></p>
</div>
Alexander
  • 69
  • 7
  • **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman Dec 13 '20 at 21:24

1 Answers1

0
  1. Add jquery on top in the main.php (if you haven't plugged in before)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  1. Add the id here
<div>
    <!-- THIS IS WHERE I WANT THE AJAX SCRIPT TO SHOW THE RESULT-->
    <p id="message"></p>
</div>
  1. Add at the bottom of the main.php
<script>
$("#availabilitySearch").on("submit", function(){
    event.preventDefault();
    $.ajax({
        url: 'availability.php',
        method: 'post',
        dataType: 'html',
        data: $(this).serialize(),
        success: function(data){
            $('#message').html(data);
        }
    });
}); 
</script>

The final main.php

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<form  id="availabilitySearch" action="availability.php method="post">  <!-- remove action="availability.php " -->
    
<div class="d-flex justify-content-center container">

    <div class="col m2">

        <label><i class="fa fa-calendar-o"></i> Check In</label>

        <input id="checkin" class="input border" name="checkin" type="date">
    </div>

    <div class="col m2">

        <label><i class="fa fa-calendar-o"></i> Check Out</label>

        <input id="checkout" class="input border" name="checkout" type="date">
    </div>

    <div class="col m2">

        <label><i class="fa fa-male"></i> People</label>

        <input id="people" class="input border" name="people" type="number" placeholder="1">
    </div>

    <div class="col m2">

        <label><i class="fa fa-search"></i> Search</label>

        <button type="submit" class="button block black">Search</button>
    </div>
</div>
</form>

<div>
    <!-- THIS IS WHERE I WANT THE AJAX SCRIPT TO SHOW THE RESULT-->
    <p id="message"></p>
</div>


<script>
$("#availabilitySearch").on("submit", function(){
    event.preventDefault();
    $.ajax({
        url: 'availability.php',
        method: 'post',
        dataType: 'html',
        data: $(this).serialize(),
        success: function(data){
            $('#message').html(data);
        }
    });
}); 
</script>
  • This worked perfectly, thank you! Question, I tried putting the script in a separate .js file and referencing it at the bottom instead of having the whole code at the bottom and it didn't work. Any thoughts? – Alexander Dec 14 '20 at 10:35
  • Yes, move the connection of this js script down to the bottom of the main.php page – Vladimir Zotov Dec 14 '20 at 11:11
  • Thanks! :) Another thing is, if I change the value of "people" and the output now should be "There is no availability for the selected dates" instead of "There are available rooms", when pressing on the Search button again it doesn't change the text - the text remains the same - as if it doesnt re-run the script. – Alexander Dec 14 '20 at 11:23
  • You're welcome) In this example the ajax works every time the button is clicked. Of course, you can also catch all the necessary events in JS, so that e.g. the data is cleared when the form fields change, etc. The .change() event can help, see the examples here: https://api.jquery.com/change/#change-handler – Vladimir Zotov Dec 14 '20 at 11:45