0

I'm doing my first experiments with AJAX PHP and MySQL in a local xampp test environment.

Hopefully this question could become useful for newbies like me that want to approach this topic.

------ Edit [Solved by Mr.Sun] ------

I translate to myself the solution as follow: it sorted out that the checkbox has to be handled. It will keep the previous value and so it does need a reset.

Also at the end of this post/question I have added the modification in the php code to achieve the goal: modify the query operand.

This question is related with the second tutorial linked here below. IF you want to follow this, you have to download the files from the tutorial page :-)

------ end ------

------ Notes ------

Note: my problem, seen later in this post, is that I can't get rid of passing the checkbox value to the php page, I suppose because of an error or missing code in the javascript.

Note: please DON'T suggest to use jQuery, thank you :-)


I have found two tutorials for newbies and they works

https://www.w3schools.com/php/php_ajax_database.asp

http://www.w3resource.com/ajax/working-with-PHP-and-MySQL.php

Though I have stick with the second updating it to use msqli. The reason: it is providing as attachment the SQL text file to make it instant to populate a dummy MySQL DB.

For the sake of simplicity, as you see, they went for the procedural manner.

Here is the mysqli version of the page book-suggestion.php

<?php
$host="localhost"; 
$username="root";  
$password="";
$db_name="book_mast"; 

$book_name = $_POST['book_name'];

if ($book_name != "") {
    $con=mysqli_connect($host, $username, $password, $db_name);

    if (!$con) {
        die('Could not connect: ' . mysqli_error($con));
    }


    mysqli_select_db($con, $db_name);

    $sql = "select book_name from book_mast where book_name LIKE '$book_name%'";

    $result = mysqli_query($con, $sql);

    while($row=mysqli_fetch_array($result))
    {
    echo "<p>".$row['book_name']."</p>";
    }

    /* close connection */
    mysqli_close($con);
}

?>

this is the form section

<form name="ajax-demo" id="ajax-demo">
    <div class="control-group">
        <label class="control-label" for="book">Book</label><br>
          <div class="controls">
          <input type="text" id="book" onKeyUp="book_suggestion()">
          <div id="suggestion"></div>
        </div>
    </div>

    <div class="control-group">
        <div class="controls">
            <button type="submit" class="btn btn-success">Submit</button>
        </div>
    </div>
</form>

Well following the tutorial, it works.

While you begin typing in the txt field, like in google, below it they are listed all the titles that begin with the typed character and progressing with typing they are matched only those beginning with the same string.

Now for the didactics I want to add one checkbox in the html page.

If checked, the checkbox should change the query in the above PHP source from

LIKE '$book_name%'

to

LIKE '%$book_name%'

in such a manner that instead to list all the book titles that begin with some char/string, they are query all of them that contains such char/string.

So inside the HTML form section, I have added this checkbox code

Search for any match <input type="checkbox" name="anychar" id="anychar" value="yes"></input>

Currently the AJAX javascript is

<script>
    function book_suggestion()
    {
    var book = document.getElementById("book").value;
    var xhr;
     if (window.XMLHttpRequest) { // Mozilla, Safari, ...
        xhr = new XMLHttpRequest();
    } else if (window.ActiveXObject) { // IE 8 and older
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }
    var data = "book_name=" + book;
         xhr.open("POST", "book-suggestion.php", true); 
         xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");                  
         xhr.send(data);
         xhr.onreadystatechange = display_data;
        function display_data() {
         if (xhr.readyState == 4) {
          if (xhr.status == 200) {
           //alert(xhr.responseText);      
          document.getElementById("suggestion").innerHTML = xhr.responseText;
          } else {
            alert('There was a problem with the request.');
          }
         }
        }
    }
</script>

I have tried to add

var anychar = document.getElementById("anychar").value;

to the javascript

and this to the PHP program

if (isset($_POST['anychar'])){
    echo $_POST['anychar']; // Displays value of checked checkbox.
}

just for test purpose, but I can't get the "yes" value of the checkbox to be printed.

Looks obvious that I'm missing something or doing something wrong in the javascript script.

Can you kindly hint how to properly process the checkbox with the AJAX javascript?

Thank you

---- the final source code for the PHP ----

...

$book_name = $_POST['book_name']; //as the original

if(isset($_POST['anychar']) && $_POST['anychar'] == 'yes') { 
    $book_name = "%".$book_name; 
    }

if (($book_name != "") and ($book_name != "%")) { //as the original
...

1 Answer 1

1

change your script to this :

<script>
function book_suggestion()
{
var book = document.getElementById("book").value;

var anychar = 'no';/*NEW CODE*/
if (document.getElementById("anychar").checked) /*NEW CODE*/
{
   anychar = 'yes';/*NEW CODE*/
} /*NEW CODE*/

var xhr;
 if (window.XMLHttpRequest) { // Mozilla, Safari, ...
    xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "book_name=" + book + "&anychar=" + anychar; /*NEW CODE*/
     xhr.open("POST", "book-suggestion.php", true); 
     xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");                  
     xhr.send(data);
     xhr.onreadystatechange = display_data;
    function display_data() {
     if (xhr.readyState == 4) {
      if (xhr.status == 200) {
       //alert(xhr.responseText);      
      document.getElementById("suggestion").innerHTML = xhr.responseText;
      } else {
        alert('There was a problem with the request.');
      }
     }
    }
}
</script>

Look at /* NEW CODE */ tag for my change.Then u can use

if($_POST['anychar'])

in your php code.

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

4 Comments

Hello there is a progress. Now I have the "yes" printed, but it prints in both cases. If I check the checkbox and also if I don't check it.
Cool, now it works! So form with checkboxes with AJAX are little tricky. Thank you for your support. Now I must leave, but I'll update the question with edit and solution. Thank you again
P.S. Is there a way to pass all the form data WITHOUT adding them one by one in the line var data = ?
Yep i'm glad that's helpful. I think using ajax with jquery can be easier : sitepoint.com/use-jquerys-ajax-function

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.