michltm michltm - 7 months ago 14
Javascript Question

update page informations or submit to new page

I have a welcome page with a dropdown list to select cities.
By default, the first city of the list is used to display quick informations on the city.

Validating the selected city brings to a new page dedicated to this city.
This works fine.

What I'd like to do, is that selecting a new city without validation, would modify the city informations on the welcome page.

enter image description here

Here is my PHP code:

$db = app::getdatabase();

$checkinformations= new informations();

$town="city1";

if(isset($_POST['submit']) AND isset($_POST['cities']))
{
app::redirect("/city/$town/");
}

require_once'inc/welcome_page.php';


And the welcome_page.php:

<h1>Welcome</h1>

<form role="form" action="#" method="POST">

<select name="cities" id="city" >
<option value="city1">city1</option>
<option value="city2">city2</option>
<option value="city3">city3</option>
</select>

<button type="submit" class="btn" name="submit"></button>

</form>

<div>
<?php echo $checkinformations->informations($db,$town);?>
</div>

Answer

If you want to display selected city information on change on same page then you have to use AJAX. First take one blank div with id. and dump ajax response into that. I edit the code to execute "Change" event, I put $('#city').trigger('change'); this line before closing "OnReady function" and after onchange function method, because method is going to define before to trigger.

    <h1>Welcome</h1>
    <form role="form" action="#" method="POST">  

      <select name="cities" id="city" >
      <option value="city1">city1</option>
      <option value="city2">city2</option>
      <option value="city3">city3</option>
      </select>

      <button type="submit" class="btn" name="submit"></button> 

    </form>

    <div id="cityInfo">  </div>
    <script type="text/javascript">
        $(document).ready(function(){
        $("#city").on("change", function(){
        $.ajax({
                        type: 'post',
                        url: 'citydetails.php',
                        data: {cityname: $("#city").val()},
                        success: function (data) {
                                $('#cityInfo').html(data);
                        }
                });
             });
$('#city').trigger('change'); //From here you can trigger city change event.
            });
    </script>