Moving to Ajax

Hi I am trying to move the db and table parts of this page: http://kroweb.dk/gfdev/ft_raw2/index_test.php to Ajax.  

I get this error saying that there is undefines indexes which I don't quite understand since it is working when having it all in the same php file.

Notice: Undefined index: query_start in /var/www/kroweb.dk/public_html/gfdev/ft_raw2/ajaxFtHtml.php on line 32

Notice: Undefined index: sogn in /var/www/kroweb.dk/public_html/gfdev/ft_raw2/ajaxFtHtml.php on line 33

Notice: Undefined index: amt in /var/www/kroweb.dk/public_html/gfdev/ft_raw2/ajaxFtHtml.php on line 34

Notice: Undefined index: type in /var/www/kroweb.dk/public_html/gfdev/ft_raw2/ajaxFtHtml.php on line 35


I really need a little help to get this setup right :) :)

I have this primary file (index_test.php):
                    <!DOCTYPE html>
                    <html lang="en">
                    <head>
                        <meta charset="utf-8">
                        <title>Folketællinger</title>

                        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
                        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
                        <link rel="stylesheet" type="text/css" href="style.css">

                        <script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
                        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

                        <script type="text/javascript">
                        $(function(){
                            $('#myTable').on('click', '.toggle', function() {
                                $(this).parents('tr').nextAll('tr.child').toggle();
                            });
                        });
                        </script>





                    </head>

                    <body>
                        <!-- Søge felt til folketællinger -->
                        <div class="container" style="width:100%;padding-top:10px;background-color:#f6f6f6;">
                            <!-- HEADER START -->
                            <div class="row" id="header">


                                <form method="POST" style="margin-left:30px; margin-right: 30px;"> 
                                    <label for="amt">Amt</label> 
                                    <select id="amt" name="amt" style="width: 125px; margin-right: 20px; font-weight:normal;">
                                        <option value=""></option>
                                        <option value="Bornholm">Bornholm</option>
                                        <option value="Frederiksborg">Frederiksborg</option>
                                        <option value="Færøerne">Færøerne</option>
                                        <option value="Grønland">Grønland</option>
                                        <option value="Haderslev">Haderslev</option>
                                        <option value="Hjørring">Hjørring</option>
                                        <option value="Holbæk">Holbæk</option>
                                        <option value="København">København</option>
                                        <option value="Køøge">Køge</option>               
                                        <option value="Maribo">Maribo</option>
                                        <option value="Odense">Odense</option>
                                        <option value="Præstø">Præstø</option>
                                        <option value="Randers">Randers</option>
                                        <option value="Ribe">Ribe</option>
                                        <option value="Ringkøbing">Ringkøbing</option>
                                        <option value="Roskilde">Roskilde</option>
                                        <option value="Skanderborg">Skanderborg</option>
                                        <option value="Sorø">Sorø</option>
                                        <option value="Svendborg">Svendborg</option>
                                        <option value="Sønderborg">Sønderborg</option>
                                        <option value="Thisted">Thisted</option>
                                        <option value="Tønder">Tønder</option> 
                                        <option value="Vejle">Vejle</option>
                                        <option value="Viborg">Viborg</option>
                                        <option value="Aabenraa">Aabenraa</option>
                                        <option value="Aalborg">Aalborg</option>
                                        <option value="Aarhus">Aarhus</option>
                                        <option value="Åbenrå-Sønderborg">Åbenrå-Sønderborg</option>
                                    </select>

                                    <label for="type">Type</label>
                                    <select id="type" name="type"style="width: 160px; margin-right: 20px; font-weight:normal;">
                                        <option value=""></option>
                                        <option value="">Søg i alle</option>
                                        <option value="Landdistrikt">Søg i Landdistrikter</option>
                                        <option value="Købstad">Søg i Købstæder</option>
                                        <option value="Hovedstaden">Søg i Hovedstaden</option>
                                    </select>


                                    <label for="aar">År</label>                
                                    <select id="aar" name="query_start" style=" width: 65px; margin-right: 20px; font-weight:normal; ">
                                        <option value=""></option>
                                        <option value="1787">1787</option>
                                        <option value="1801">1801</option>
                                        <option value="1803">1803</option>
                                        <option value="1834">1834</option>
                                        <option value="1835">1835</option>
                                        <option value="1840">1840</option>
                                        <option value="1845">1845</option>
                                        <option value="1850">1850</option>
                                        <option value="1855">1855</option>
                                        <option value="1860">1860</option>
                                        <option value="1861">1861</option>
                                        <option value="1870">1870</option>
                                        <option value="1878">1878</option>
                                        <option value="1880">1880</option>
                                        <option value="1890">1890</option>
                                        <option value="1901">1901</option>
                                        <option value="1906">1906</option>
                                        <option value="1911">1911</option>
                                        <option value="1916">1916</option>
                                        <option value="1921">1921</option>
                                        <option value="1925">1925</option>
                                        <option value="1930">1930</option>
                                        <option value="1940">1940</option>          
                                    </select>

                                    <label for="sogn">Sted, By, Sogn, Gade</label>
                                    <input type="text" name="sogn" id="sogn" placeholder="Fritekst" style="color: #e08a94;">
                                    <input type="button" value="Søg" name="Sog" id="Sog">
                                    <!--<input type="button" value="Nulstil"> -->
                                    <button onclick="myFunction()" id="clearButton">Nulstil</button>
                                    <script>
                                    $('#clearButton').click(function() {
                                        $('#myTable').remove();
                                    });
                                    </script>




                                </form>
                            </div>  
                            <!-- HEADER END -->        
                        </div>

           <div id="ft_items"></div>

<script>
      var SogButton=document.getElementById('Sog'); //"Søg" button
      var amt = document.getElementById('amt'); //amt dropdown
      var type = document.getElementById('type'); //type dropdown      
      var start = document.getElementById('aar'); //aar dropdown
      var sogn = document.getElementById('sogn'); //free text search field      


            // "Søg" button function
    SogButton.addEventListener('click',function (){
      $('#ft_items > table').remove();    
      $.ajax({
       url: 'ajaxFtHtml.php',
       data: {query:amt.value+' '+type.value+' '+aar.value+' '+sogn.value},
       method:'POST',
       dataType: 'html'
     }).done(function (res){             
            $('#ft_items').html(res);

          });         

   });



 
</script>

</body>
</html>

Open in new window


and I have this secondary file (ajaxFtHtml.php):
<?php
// Turn on error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

function cityVariations($city) {
    $substitute = array(
        "æ" => "ae",
        "ø" => "oe",
        "å" => "aa",
        "ae" =>"æ",
        "oe" =>"ø",
        "aa" => "å",
        );

    $flatCity = mb_convert_case($city, MB_CASE_LOWER);

    $cities[] = $flatCity;
    $cities[] = strtr($flatCity, $substitute); 

    return $cities;
}

// Do we need the database
if (!empty($_POST)):

    // Connect to the database if we have a POST
    $mysqli = mysqli_connect("db credentials") or die("Error connecting to database!");
$mysqli->set_charset("utf8");

    // Trim the input values
$start = trim($_POST['query_start']); 
$sogn = trim($_POST['sogn']);
$amt = trim($_POST['amt']);
$type = trim($_POST['type']);

            // Get the city variations
$cities = cityVariations($sogn);

            // Prepare the cities for the LIKE clause by wrapping each in %...%
array_walk($cities, function (&$city) { $city = '%'.$city.'%'; });



    if (!empty($amt) && !empty($sogn) && empty($type) && empty($start)):
                    // We have a 'amt - 'sogn' value

        $query = $mysqli->prepare("SELECT * FROM ft WHERE Amt = ? AND (AmtHerredSognGade LIKE ? OR AmtHerredSognGade LIKE ?)");
    $query->bind_param("sss",$amt, $cities[0], $cities[1]);



    elseif (!empty($amt) && !empty($start) && !empty($sogn) && empty($type)):
                    // We have a 'amt' - 'aar' - sogn' value

        $query = $mysqli->prepare("SELECT * FROM ft WHERE Amt = ? AND Aar = ? AND (AmtHerredSognGade LIKE ? OR AmtHerredSognGade LIKE ?)");
    $query->bind_param("ssss", $amt, $start, $cities[0], $cities[1]); 

    else:   


        if (!empty($amt) && !empty($type) && !empty($start) && !empty($sogn)):
            //We have 'amt' - 'type' - 'aar' - 'sted' value

            $query = $mysqli->prepare("SELECT * FROM ft WHERE Amt = ? AND Type = ? AND Aar = ? AND (AmtHerredSognGade LIKE ? OR AmtHerredSognGade LIKE ?)");
        $query->bind_param("sssss", $amt, $type, $start, $cities[0], $cities[1]);   

            //var_dump($amt, $type, $start, $cities);

        elseif (!empty($type) && !empty($sogn) && empty($start) && empty($amt)):
                    // We have a 'type' - sogn' value

            $query = $mysqli->prepare("SELECT * FROM ft WHERE Type = ? AND (AmtHerredSognGade LIKE ? OR AmtHerredSognGade LIKE ?)");
        $query->bind_param("sss", $type, $cities[0], $cities[1]); 


        else:

          if (!empty($amt) && !empty($type) && !empty($start) && empty($sogn)):
            //We have 'amt' - 'type' - 'aar' value

            $query = $mysqli->prepare("SELECT * FROM ft WHERE Amt = ? AND Type = ? AND Aar = ? ");
        $query->bind_param("sss", $amt, $type, $start);   




        elseif (!empty($amt) && !empty($type) && empty($start) && empty($sogn)):
            //We have 'amt' - 'type' value

            $query = $mysqli->prepare("SELECT * FROM ft WHERE Amt = ? AND Type = ? ");
        $query->bind_param("ss", $amt, $type);   



        else:


            if (!empty($amt) && empty($type) && empty($start) && empty($sogn)):
            //We have 'amt' value

                $query = $mysqli->prepare("SELECT * FROM ft WHERE Amt = ? ");
            $query->bind_param("s", $amt);   

        //var_dump($amt, $type, $start, $cities); 


         elseif (!empty($amt) && empty($type) && !empty($start) && empty($sogn)):
            //We have 'amt' - 'aar' value

            $query = $mysqli->prepare("SELECT * FROM ft WHERE Amt = ? AND Aar = ? ");
        $query->bind_param("ss", $amt, $start);       
        //var_dump($amt, $start); 


        else:

            if (!empty($type) && !empty($start) && !empty($sogn) && empty($amt)):
                // We have a 'type' - 'aar' - 'sogn' value

                $query = $mysqli->prepare("SELECT * FROM ft WHERE Type = ? AND Aar = ? AND (AmtHerredSognGade LIKE ? OR AmtHerredSognGade LIKE ?)");
            $query->bind_param("ssss",$type, $start, $cities[0], $cities[1]);


            elseif  (!empty($type) && !empty($start) && empty($sogn) && empty($amt)):
                // We have a 'type' - 'aar' value

                $query = $mysqli->prepare("SELECT * FROM ft WHERE Type = ? AND Aar = ?");
            $query->bind_param("ss",$type, $start); 



            else:

                if (!empty($type) && empty($start) && empty($sogn) && empty($amt)):
                // We have a 'type' value

                    echo "<h2> Feltet 'Type' skal anvendes sammen med et af de andre valg. Klik på Nulstil og prøv igen </h2>";

                //    $query = $mysqli->prepare("SELECT * FROM ft WHERE Type = ?");
                //$query->bind_param("s",$type); 


                elseif (!empty($start) && !empty($sogn) && empty($type) && empty($amt)):
                // We have a 'aar' - 'sogn' value

                    $query = $mysqli->prepare("SELECT * FROM ft WHERE Aar = ? AND (AmtHerredSognGade LIKE ? OR AmtHerredSognGade LIKE ?)");
                $query->bind_param("sss",$start, $cities[0], $cities[1]);  


                else:                

                    if (!empty($start) && empty($sogn) && empty($type) && empty($amt)):
                // We have a 'aar' value

                        $query = $mysqli->prepare("SELECT * FROM ft WHERE Aar = ? ");
                    $query->bind_param("s",$start);


                    elseif (!empty($sogn)&& empty($start) && empty($type) && empty($amt)):
                // We have a sogn' value

                        $query = $mysqli->prepare("SELECT * FROM ft WHERE (AmtHerredSognGade LIKE ? OR AmtHerredSognGade LIKE ?)");
                    $query->bind_param("ss", $cities[0], $cities[1]); 









                    endif;

                    endif;

                    endif;

                    endif;

                    endif;

                    endif; 

                    endif;   

    // Do we have a query to run
                    if (!empty($query)):
                        $query->execute();
                    $results = $query->get_result();
                    endif;

                    endif;
                    ?>

                         <div class="flex-container" style="width:site-width; background-color:white;">
                            <div class="flex-item" style="margin-top:10px; float:left; margin-left:20px;width: site-width; overflow:auto;">
                                <div class="row" style="margin-left:10px;margin-right:10px;">

                                 <!-- Have we ran a query -->
                                 <?php if (isset($results)): ?>

                                 <!-- Do we have any results -->
                                 <?php if ($results->num_rows): ?>

                                 <table id="myTable" class="table">
                                    <colgroup>
                                </colgroup>

                                <tr>
                                    <th>&nbsp;</th> <th>Sted Sogn Gade</th> <th>Amt</th> <th>Aar</th> <th>Type</th> <th>Gade (1860)</th> <th>Matr. nr. (1860)</th>  
                                </tr>

                                <!-- Loop through the results of the query -->
                                <?php while ($row = $results->fetch_object()): ?>

                                <!-- Links for the individual rows -->    
                                <?php
                                $link1 = sprintf("<a href='%s' target='_blank'>%s</a>", $row->URL, $row->AmtHerredSognGade); 
                                $link2 = sprintf("<a href='%s' target='_blank'>%s</a>", $row->Infourl, $row->Info);
                                $link3 = sprintf("<a href='%s' target='_blank'>%s</a>", $row->Infourl, $row->Gade);
                                $link4 = sprintf($row->AmtHerredSognGade);
                                ?>

                                <?php if ($row->Collapse == 'p'): ?>
                                <!-- We have a parent row -->

                                <tbody class='toggle' >
                                    <tr class="expander">
                                        <td><span class='toggle'></td>
                                        <td><?php echo (!empty($row->URL)) ? $link1 : $link4 ?></td>
                                        <td><?php echo $row->Amt ?></td>             
                                        <td><?php echo $row->Aar ?></td>
                                        <td><?php echo $row->Type ?></td>   
                                        <td><?php echo $row->Gade ?></td>            
                                        <td><?php echo $row->Kvarter ?></td>            
                                    </tr>

                                <?php elseif ($row->Collapse == 'c'): ?>
                                <!-- We have a child row -->

                                <tr class="child">
                                    <td>&nbsp;</td>
                                    <td><?php echo (!empty($row->URL)) ? $link1 : $link4 ?></td>
                                    <td><?php echo $row->Amt ?></td>             
                                    <td><?php echo $row->Aar ?></td>
                                    <td><?php echo $row->Type ?></td>
                                    <td><?php echo $row->Gade ?></td>            
                                    <td><?php echo $row->Kvarter ?></td>           
                                </tr>

                            <?php else: ?>
                            <!-- We have a non-collapsible row -->

                            <tr class="non">
                                <td>&nbsp;</td>
                                <!-- Område, link -->
                                <td><?php echo $link1 ?></td>
                                <td><?php echo $row->Amt ?></td>      
                                <td><?php echo $row->Aar ?></td>
                                <td><?php echo $row->Type ?></td>
                                <td colspan="2">&nbsp;</td>
                            </tr>

                        <?php endif; ?>

                    <?php endwhile; ?>

                </table>

            <?php else: ?>

            <p>Der er ingen resultater for denne søgning</p>

        <?php endif; ?>
    <?php endif; ?>

</div>
</div> 
</div>

Open in new window

Peter KromanSenior Proposal SpecialistAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Chris StanyonWebDevCommented:
Hey Peter,

Glad to see you moving to AJAX :)

In your PHP script, you're expecting the data to be passed in via the POST variables, so you need to ensure your AJAX request passes this data in correctly. The easiest way to do this is to serialize the form. Firstly, you should add an ID to your form:

<form id="search">

Then you have a handle so you can serialize the form:

$('#Sog').click(function(e) {
    $('#ft_items > table').remove();    
    $.ajax({
        url: 'ajaxFtHtml.php',
        data: $('#search').serialize(),
        method: 'POST',
        dataType: 'html'
    }).done(function(res) {
        $('#ft_items').html(res);
    });         
});

Open in new window

0
Peter KromanSenior Proposal SpecialistAuthor Commented:
Thanks a lot Chris. That works nicely.

Now I need to that the search also performs when hitting the Enter Key. I have prepared this code, but it does not return anything.
What am I doing wrong :)

      // Return key search function
    sogn.addEventListener('keyup',function(e){
 
      if(e.keyCode===13){            
      $.ajax({
       url: 'ajaxFtHtml.php',
       data: $('#search').serialize(),
       method:'POST',
       dataType: 'html'
     }).done(function (res){             
            $('#ft_items').html(res);

 
          });
     }
   });

Open in new window

0
Peter KromanSenior Proposal SpecialistAuthor Commented:
I just discovered another thing.

After moving to Ajax, the collapse toggle does not work anymore.

You can try e.g.
Type = Søg i Hovedstaden
Aar = 1870

And hit the "Søg" button.
0
Cloud Class® Course: Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

Chris StanyonWebDevCommented:
OK Peter.

Firstly, the Enter Key. By default, a Form will automatically submit when you press the Enter key if your form has a Submit Button. Currently your form doesn't have a Submit button - it just has a normal Button, so you need to change this:

<input type="button" value="Søg" name="Sog" id="Sog">

To this:

<input type="submit" value="Søg" name="Sog" id="Sog">

Now your form will be submitted when the Enter key is pressed.

However, we're currently binding to the Click event of that button, but we need to change that so that we bind to the Submit event of the form instead. Your Ajax method should now look like this:

$('#search').submit(function(e) {
    e.preventDefault();
    $.ajax({
        url : 'ajaxFtHtml.php',
        method: 'post',
        data : $('#search').serialize(),
        dataType: 'html'
    })
    .done(function(res){
        $('#ft_items').html(res);
    });
});

Open in new window

That code will now be fired whenever you press Enter or click on the Submit button
0
Chris StanyonWebDevCommented:
Now onto the Toggle.

What's happening here is that when the page is first loaded, you're binding the Toggle function to the #myTable element:

$('#myTable').on('click', '.toggle', function() {
    ...

Open in new window

Now, obviously that element doesn't exist when you first load the page, so there's nothing to bind the event to. You need to bind the event to something that DOES exist when you first load the page. You have the container DIV that you populate with the table (#ft_items) so it makes sense to bind the event to that instead:

$('#ft_items').on('click', '.toggle', function() {
    ...

Open in new window

0
Chris StanyonWebDevCommented:
One other thing I would suggest. Change your Reset button to an actual Reset button and bind the event with jQuery

<input type="reset" value="Nulstil">


$(':reset', '#search').click(function(e) {
    $('#ft_items').html('');
});
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Peter KromanSenior Proposal SpecialistAuthor Commented:
Thanks Chris,

I will go to work on this a little later to day. Just have to go and visit my 92 years old mother in law now :)  

I will get back later. Thanks a lot.
0
Peter KromanSenior Proposal SpecialistAuthor Commented:
Hi Chris,

I have implemented your suggestions.
Everything works just perfect now. And my sense of logic got another kick upwards :) :)

Thanks a lot.
0
Peter KromanSenior Proposal SpecialistAuthor Commented:
Thanks to Chris for a quick and easy understandable solution.
0
Chris StanyonWebDevCommented:
No worries Peter. Glad you got it working :)
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
SQL

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.