0

I am trying to populate a form on my page. The information required to populate the form is pulled from a MySQL database using the ID of the drop down option as the ID in the SQL statement. I was thinking that I can store the information in $_SESSION['formBookings'] and on a refresh this will populate the form (this is already happening as I am using the session variable to populate the form after a submit.

I can not have a submit button attached to the form as I already have one and the boss doesn't want another. I would like the form to eventually automatically refresh the page on the selection of an option. If the data from the SQL statement has been stored in the session array then the form will be populated.

Here is what I have so far:

The JQuery:

<script>
$(document).ready(function(){
    $('select[name=recall]').on('change', function() {var recall = $(this).val() 
    //$(function () 
      //{
        //-----------------------------------------------------------------------
        // 2) Send a http request with AJAX http://api.jquery.com/jQuery.ajax/
        //-----------------------------------------------------------------------
        $.ajax({                                      
          url: 'recall.php',                  //the script to call to get data          
          data: "recall: recall",             //you can insert url argumnets here to pass to api.php
                                           //for example "id=5&parent=6"
          dataType: 'json',                //data format      
          success: function(data)          //on recieve of reply
          {
            var id = data[0];              //get id
            var vname = data[1];           //get name
            //--------------------------------------------------------------------
            // 3) Update html content
            //--------------------------------------------------------------------
            $('div#box1').load('DFBristol.html');//html("<b>id: </b>"+id+"<b> name: </b>"+vname); //Set output element html
            //recommend reading up on jquery selectors they are awesome 
            // http://api.jquery.com/category/selectors/
          //} 
          });
        });
      });
    });
</script>

The HTML:

<select name='recall' id='recall'>
                    <option selected></option>
                        <?php
                            session_start();
                            $user = 'root';
                            $pass = '';

                            $DBH = new PDO('mysql:host=localhost;dbname=nightlineDB;', $user, $pass);
                            $DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                            $DBH->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

                            $recall = $DBH->prepare('SELECT * FROM bookings WHERE dateInputted >= now() - INTERVAL 2 DAY');
                            $recall->execute();
                            $recallResult = $recall->fetchALL(PDO::FETCH_ASSOC);

                            foreach ($recallResult as $key) {
                                echo '<option id='.$key["ID"].'>'.$key['ID'].' - '.$key['branch'].' - '.$key['title'].' '.$key['firstName'].' '.$key['lastName'].'</option>';
                            }
                        ?>
                    </select><br />

The SQL file (recall.php):

<?php
$user = 'root';
$pass = '';

$DBH = new PDO('mysql:host=localhost;dbname=nightlineDB;', $user, $pass);
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$DBH->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

$recall = $DBH->prepare("SELECT * FROM bookings WHERE ID = '%$recall%'");
$recall->execute();
$recallFormResult = $recall->fetchALL(PDO::FETCH_ASSOC);

echo json_encode($recallFormResult);

?>

I have tried to pass the variable 'recall' from the jquery into the SQL statement using the data argument but nothing happens.

Could someone please help me understand what I am doing wrong and how I can resolve it.

1 Answer 1

2

On a quick glance there seems to be two issues with the code you've posted so far:

The AJAX request

Even though $.ajax() defaults to a request type of GET by default, it's good to specify it. There is also a syntax error in your request — you have closed the success callback with a }); where it should be a } only:

$.ajax({                                      
    url: "recall.php",
    data: {
        recall: recall
    },
    type: "GET",               // Declare type of request (we use GET, the default)
    dataType: "json",
    success: function(data)
    {
        var id = data[0];
        var vname = data[1];
        $('div#box1').load('DFBristol.html');
    }                         // The problematic closure
});

Even better: instead of using the deprecated jqXHR.success() function, use the .done() promise object instead, i.e.:

$.ajax({                                      
    url: "recall.php",
    data: {
        recall: recall
    },
    type: "GET",               // Declare type of request (we use GET, the default)
    dataType: "json"
}).done(function() {
    // Success
    var id = data[0],
        vname = data[1];
    $('div#box1').load('DFBristol.html');
});

Fixing the file recall.php

When you make an AJAX GET request to recall.php, the file needs to know what variables you intend to pass, which you have not defined. You can do that using $_GET[] (see doc), i.e.:

<?php
// Assign the variable $recall with the value of the recall query string from AJAX get request
// I recommend doing a check to see if $_GET['recall'] is defined, e.g.
// if($_GET['recall']) { $recall = $_GET['recall']; }
$recall = $_GET['recall'];

// The rest of your script, unmodified
$user = 'root';
$pass = '';

$DBH = new PDO('mysql:host=localhost;dbname=nightlineDB;', $user, $pass);
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$DBH->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

$recall = $DBH->prepare("SELECT * FROM bookings WHERE ID = '%$recall%'");
$recall->execute();
$recallFormResult = $recall->fetchALL(PDO::FETCH_ASSOC);

echo json_encode($recallFormResult);
?>

Note: However, if you choose to make a POST request, then you should use $_POST[] (see doc) instead :)

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

7 Comments

Hi Terry, thanks for the quick reply. I am not able to get your code to do anything. How is the GET receiving anything if there is no submit button? At the moment I have made the changes you suggested, however, the #box1 div is not being populated.
I realized that your data should be "recall: "+recall" because you are passing a variable. AJAX doesn't need to work with form submission. Check your browser console. What error messages do you see? Check your HTTP headers too, and see if the recall.php file is referenced/called properly.
I have adjust that and nothing, I get no errors in the console and the address bar does not have any reference to recall.php. The content of #box1 does not change. This is the changed line - data: 'recall: "+recall"',
OK I may have found an issue, I have found a notice stating that 'recall' is an unidentified index in 'recall.php'
No, you don't to wrap the variable recall with quotes. Just data: "recall="+recall. Perhaps you can declare the data as an object, ie: data: { recall: recall}
|

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.