1

Okay, this question was closed for not being clear enough, so I'm going to completely re-write it in as clear a form as I can...

Project: Room Booking System

Required Function: Check the database for existing bookings matching a criteria, return the result of 'COUNT' SQL query to a textbox which another function then looks to. The values which need to be inserted into the COUNT criteria are as follows:

<h4>Date:</h4>
    <input required type="text" name = "datebox" id = "datebox" ><br/>
    <h4>Timeslot:</h4>
    <input required type="text" name = "timebox" id = "timebox" ><br/>
    <h4>Location:</h4> 
    <input required type="text" name = "roombox" id = "roombox" ><br/>
    <h4>Person:</h4>
    <input required type="text" name = "bookerbox" id = "bookerbox" ><br/>
    </br>

Problem: I have a functioning php script which counts the number of rows in the database matching a criteria, which will then return the result to a textbox (main function sorted) when set up in a test directory with nothing else on the page. However, when I embed this php into an existing page (the new booking page) it doesn't work when the 'Check Availability' button is clicked. Instead, it reloads the page (as php does) which is not useful when users have already input their data for checking (and would need to re-enter it). I've Googled and have found that I need to use AJAX to run the php function in the background and then return the result to the textbox on the current page. I have never ever used AJAX and are only new to php, js etc. as it is, so I have no idea what I'm doing

How can you help: I need help in converting my existing code into a working solution to the above problem, probably using a combination of AJAX, PHP and JS functions.

Code:

PHP COUNT CODE (works)

<?php
    if(isset($_POST['info'])) {
        $con = mysqli_connect("x", "x", "x", "x");
        // Check connection
        if (mysqli_connect_errno()) {
            echo "Failed to connect to MySQL: " . mysqli_connect_error();
        }

        $sql="SELECT COUNT(*) FROM `Existing_Bookings` WHERE Date = '2019-12-30' AND Time = 'Period 6' AND Room = 'C3'";

        if ($result=mysqli_query($con,$sql)) {
            // Return the number of rows in result set
            $rowcount = mysqli_num_rows($result);
            // Free result set
            mysqli_free_result($result);
        }
        mysqli_close($con);
        echo $rowcount; // echo the data you want to send over ajax
    }
?>

Area of php/html in which the result should be returned (id="availresult")

<h2>Check availability</h2>
<h4>Click the button below to check whether your options are available:</h4>
<h4>This will only check against other bookings. It is your responsibility to use the timetable above to check whether the room is actually free.</h4>
<button onclick="soflow()" id="checkAvail" >Check Availability</button>
<input onclick="unhideReview()" type="button" id="continue" value="Continue" disabled />
<input type="text" style="width: 30px;" id="availresult" value="1" />

Test AJAX function, as suggested by an existing reply to my post

<script>
	function soflow() {
		$.post('checkAvailability.php', {info: 'start'}, function(data) { //if you don't need to send any data to the php file then you can set the value to whatever you want
			document.getElementById('availResult').innerHTML = data;
		});
	}
</script>

I have tried various ways to do this myself, including modifying the suggested AJAX code above, but I'm not sure how to get my values from my various textbox over to the PHP function. Also, I don't know how to tell whether the AJAX function is running, or whether there is an error somewhere. At present, the value shown in my 'availresult' textbox does not change.

I appreciate any help with this, and thank anyone who has tried to help so far. I'm not sure how much clearer I can make this - please don't close the question again.

8
  • it's a bit unclear from your question what you've achieved here and where you're stuck but to return a value to an ajax call just echo it. Commented Jan 1, 2020 at 17:06
  • @billynoah What would I need to edit in my PHP script to echo the value? The area I'm stuck on is returning the result from this PHP script (file1) to a textbox in file2. Commented Jan 1, 2020 at 17:28
  • You could post a value with ajax, and then in the php check if that post value isset(). Afterwords you can echo out the result and you would get it in the ajax callback. If you have any more questions, ask here. Commented Jan 1, 2020 at 17:31
  • @LeonKunštek - This sounds like it probably would work, and sounds similar to things I've read elsewhere, though I have no idea how to do this unfortunately (extremely new to all of this, so wouldn't know where to start). Any chance you could explain in a bit more depth please, possibly with some example code to help me try and learn? Thank you Commented Jan 1, 2020 at 17:36
  • if your goal is to return the row count just echo $rowcount and catch the return value in your ajax success callback Commented Jan 1, 2020 at 17:38

1 Answer 1

1

UPDATE:

(index.php):

<html>
    <head>
        <title>Test</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    </head>
    <body>
        <h4>Date:</h4>
            <input required type="text" name = "datebox" id = "datebox" ><br/>
        <h4>Timeslot:</h4>
            <input required type="text" name = "timebox" id = "timebox" ><br/>
        <h4>Location:</h4> 
            <input required type="text" name = "roombox" id = "roombox" ><br/>
        <h4>Person:</h4>
            <input required type="text" name = "bookerbox" id = "bookerbox" ><br/>
        <br/>

        <h2>Check availability</h2>
        <h4>Click the button below to check whether your options are available:</h4>
        <h4>This will only check against other bookings. It is your responsibility to use the timetable above to check whether the room is actually free.</h4>
        <button onclick="soflow()" id="checkAvail" >Check Availability</button>
            <input onclick="unhideReview()" type="button" id="continue" value="Continue" disabled />
            <input type="text" style="width: 30px;" id="availresult" value="1" />
        <script>
            function soflow() {
                var var_date = $('#datebox').val();
                var var_time = $('#timebox').val();
                var var_room = $('#roombox').val();

                $.post('checkAvailability.php', {info: 'start', date: var_date, time: var_time, room: var_room}, function(data) { 
                    document.getElementById('availResult').innerHTML = data;
                });
            }
        </script>
    </body>
</html>

(test.php):

<?php
    if(isset($_POST['info'])) {
        $con = mysqli_connect("x", "x", "x", "x");
        if (mysqli_connect_errno()) {   // Check connection
            echo "Failed to connect to MySQL: " . mysqli_connect_error();
        }

        $date = mysqli_real_escape_string($con, $_POST['date']);
        $time = mysqli_real_escape_string($con, $_POST['time']);
        $room = mysqli_real_escape_string($con, $_POST['room']);

        $sql="SELECT COUNT(*) FROM `Existing_Bookings` WHERE Date = '$date' AND Time = '$time' AND Room = '$room'";

        if ($result=mysqli_query($con,$sql)) {
            // Return the number of rows in result set
            $rowcount = mysqli_num_rows($result);
            // Free result set
            mysqli_free_result($result);
        }
        mysqli_close($con);
        echo $rowcount; // echo the data you want to send over ajax
    }
?>

You could also do ajax with pure JavaScript, but this is simpler.
Also note that this is just an example on how to do an ajax connection in the first place.

Sign up to request clarification or add additional context in comments.

2 Comments

This works great as a starting point - thank you very much. In my index.php file, I have 3 text input boxes (datebox, timebox, roombox) which I need to transfer over to the 'test.php' file to be inserted into the 'WHERE' clause of the SQL Query. I was just wondering if you could point out how I would go about transferring the values entered into these input boxes over to the 'test.php' and then into the SQL query?
You're a genius. I really appreciate your help with both helping me solve this issue, but also learn more about php and js, and the very basics of AJAX. Many thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.