Ajax, PHP and MySQL and append data in a page Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Ajax, PHP and MySQL and append data in a page without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I’m building a page that looks like the following:

events

What’s the goal:

  • When the user clicks in the input box and selects a particular date, it runs a php script that searches the database for records with that specific date and appends them in a specific div.

What have I done so far:

  1. HTML and CSS:
<div class="input-group col-md-8 col-sm-8 col-xs-8">
      <input type="text" class="form-control date">
      <span class="input-group-addon calendar-date-picker">
           <i class="glyphicon glyphicon-calendar"></i>
      </span>
  </div>

(…)

this is cool :<p> <?php print_r($_POST);?> </p>
<div class="results-ajax"></div>

. It uses ‘date’ in the class of the input for opening the datepicker calendar.

. It has a specific div with one class ‘results-ajax’ where the input generated by the script should be displayed at.

  1. JS and Ajax:
jQuery(function($) {

  $(".date").datepicker({
    onSelect: function(dateText) {
      display("Selected date: " + dateText + "; input's current value: " + this.value);
      $(this).change();
    }
  }).on("change", function() {
    display("Got change event from field");
    $.ajax({
      type: "POST",
      url: 'events_script.php',
      data: ({dates: this.value}),
      success: function(data) {
        $(".results-ajax").load(data);
        alert(data);
      }
  });
});
  function display(msg) {
    $("<p>").html(msg).appendTo(document.body);
  }

});

. Once new date gets picked up, the results are shown bellow under Outcomes. .

. The Ajax call is posting in events_script.php.

  1. PHP (events_script.php)
<?php
include 'config/config.php';
include 'libraries/database.php';

    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    print_r($_POST);
    echo $_POST[dates];
    $dias= $_POST[dates];

//Make database query

$sql = "SELECT *
        FROM events
        RIGHT OUTER JOIN companies ON companies.companyID = events.Ref_ID
        WHERE events.Start_Date= '$dias%'
        ORDER BY events.Start_Date DESC";

$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {

// output data of each row

  while ($row = mysqli_fetch_assoc($result)) {
      echo '<p>'.print_r($_POST).'</p>';
  }

} else { echo 'No results found.'; } } ?>

Outcomes:

1. The result of the JS display and append

events-result1

2. The result of the alert in Ajax (using the PHP script):

events-result2

Problems:

  1. Why is it the data alerted not being loaded in the div with the class ‘results-ajax’, as commanded in Ajax?

I’ve tested also using appendTo instead of load and also didn’t work.

Also,

  1. . Is there any step missing/wrong in the procedure in order for the data posted to be recognized by the database, once in the query (‘$dias%‘)?

Because rn displays ‘No results found’ (as you can see in the alert), and there’s records in the database with that specific date.

(it happened so many times that the value is exactly like the one in the database but because one was string and the other date, nothing was being displayed – just to make sure this is not one of those cases)

To note:

No errors in the PHP error log.

In the console, there’s this error: GET example.com/Array( 404 (Not Found). It shows up once the alert box is closed.

Answer

I got it working using the following code

  1. HTML and CSS:
<div class="input-group col-md-8 col-sm-8 col-xs-8">
      <input type="text" class="form-control date">
      <span class="input-group-addon calendar-date-picker">
           <i class="glyphicon glyphicon-calendar"></i>
      </span>
  </div>

(…)

this is cool :<p> <?php print_r($_POST);?> </p>
<div class="results-ajax"></div>

. It uses ‘date’ in the class of the input for opening the datepicker calendar.

. It has a specific div with one class ‘results-ajax’ where the input generated by the script is displayed at.

  1. JS and Ajax:
jQuery(function($) {

  $(".date").datepicker({
    onSelect: function(dateText) {
      display("Selected date: " + dateText + "; input's current value: " + this.value);
      $(this).change();
    }
  }).on("change", function() {
    display("Got change event from field");
    $.ajax({
      type: "POST",
      url: 'events_script.php',
      data: ({dates: this.value}),
      success: function(data) {
        $('.results-ajax').html(data);
        alert(data);
      }
  });
});
  function display(msg) {
    $("<p>").html(msg).appendTo(document.body);
  }

});

. Once new date gets picked up, the results are shown bellow under Outcomes. .

. The Ajax call is posting in events_script.php.

  1. PHP (events_script.php)
<?php
include 'config/config.php';
include 'libraries/database.php';

    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    print_r($_POST);
    echo $_POST[dates];
    $dias= $_POST[dates];
    $mysql_date = date('Y-m-d', strtotime($dias));

//Make database query

$sql = "SELECT *
        FROM events
        left JOIN companies ON companies.companyID = events.Ref_ID AND companies.Ref_Type = events.Ref_Type
        WHERE events.Start_Date= '".$mysql_date."'
        ORDER BY events.Start_Date DESC";

$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {

// output data of each row

  while ($row = mysqli_fetch_assoc($result)) {
      echo '<p>It works!</p>';
  }

} else { echo 'No results found.'; } } ?>

Outcomes:

1. The result of the alert in Ajax (using the PHP script):
enter image description here

We are here to answer your question about Ajax, PHP and MySQL and append data in a page - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji