skip to Main Content

I am using $.post() to load a page whenever someone types in a new text in id city. When I enter the city and move to another field, nothing happens. Here is the site.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="../../favicon.ico">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
 <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script>
    <!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>


    <title>Tuition Teacher</title>

    <!-- Custom styles for this template -->
    <link href="sticky-footer-navbar.css" rel="stylesheet">

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
    <style>
        .navbar-nav{
            float:right;
        }
        #slider-range, #slider-range2 {
            width:168px;
  margin-top:10px;
}
#slider-range2.ui-slider-horizontal {
    border: 0 none;
}
#slider-range2.ui-slider-horizontal .ui-slider-range, #slider-range2.ui-slider-horizontal .ui-slider-handle {
    background: url("http://unbug.ru/examples/jquery/slider/slide.png") repeat scroll 0 0 transparent;
}
#slider-range2.ui-slider-horizontal .ui-slider-range {
    background-position: 0 -42px;
    background-repeat: repeat-x;
    height: 21px;
}
#slider-range2.ui-slider-horizontal .ui-slider-handle {
    background-position: 0 0;
    background-repeat: no-repeat;
    border: 0 none;
    height: 21px;
    top: 0;
    width: 21px;
}
#slider-range2.ui-slider-horizontal .ui-slider-handle:focus {
    outline: 0 none;
}
#slider-range2.ui-slider-horizontal .ui-slider-handle + .ui-slider-handle {
    background-position: -21px 0;
}

    </style>


<script>
         $(function() {
    var availableTags = [
      "Lahore",
      "Karachi",
      "Islamabad",
      "Rawalpindi",
      "Faisalabad",
      "Multan",
      "Gujranwala",
      "Quetta",
      "Peshawar",
      "Hyderabad",
      "Sialkot"
    ];
    $( "#city" ).autocomplete({
      source: availableTags
    });
  });
</script>

  </head>

  <body>

    <!-- Fixed navbar -->
    <nav class="navbar navbar-default navbar-fixed-top">
      <div class="container">
      <!--
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>

        </div>
        -->
        <div id="navbar" class="collapse navbar-collapse text-right">
          <ul class="nav navbar-nav ">
            <li ><a href="login.html">Teachers Log In </a></li>
            <li><a href="signup.html">Teachers Sign Up</a></li>
            <li><a href="#">Tour</a></li>
            <!--Sign Up

            <li class="dropdown">
              <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
              <ul class="dropdown-menu">
                <li><a href="#">Action</a></li>
                <li><a href="#">Another action</a></li>
                <li><a href="#">Something else here</a></li>
                <li role="separator" class="divider"></li>
                <li class="dropdown-header">Nav header</li>
                <li><a href="#">Separated link</a></li>
                <li><a href="#">One more separated link</a></li>
                -->
              </ul>
            </li>
          </ul>
        </div><!--/.nav-collapse -->
      </div>
    </nav>

    <!-- Begin page content -->
    <div class="container">
        <div class="row">
        <div class="col-md-2">
        <h2>Filter</h2>
            City:<br>
              <input id="city" placeholder="<?php echo $_POST['city'] ?>">
            <hr>
            Locality:<br>
            <input id="locality" placeholder="Select Locality">
            <hr>
            Gender:<br>
            <input type="radio" name="gender" value="male">Male<br>
            <input type="radio" name="gender" value="female">Female<br>
            <hr>
            <p>
                Age range:<br>
                <input  type="text" id="amount"/>
            </p>

            <div id="slider-range"></div>
            <hr>
            Education:<br>

            <input type="radio" name="education" value="high school">High School<br>
            <input type="radio" name="education" value="intermediate">Intermediate<br>
            <input type="radio" name="education" value="professional degree">Professional Degree<br>

        </div>
<div class="col-md-9 col-md-offset-1">
        <div class="row">
            <div class="col-md-12">
            <h2>Search Results</h2>
            </div>
        </div>
        <?php
$servername = "";
$username = "";
$password = "";
$dbname = "";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
$city = $_POST["city"];
$sql = "SELECT id,full_name, email, password,full_address,city,age,contact_number,gender,education FROM users WHERE city='$city'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "Name:" . $row["full_name"]."<br> Email:". $row["email"]. "<br>City: " . $row["city"]. "<br>Age: " . $row["age"]. "<br>Contact Number:". $row["contact_number"]. "<br> Gender: " . $row["gender"]. "<br>Education:" . $row["education"];
        echo "<br><hr>";
    }

} else {
    echo "0 results";
}
$conn->close();
?>
</div>
        </div>
    </div> <!-- Container ends -->


    <footer class="footer">
      <div class="container">
        <div class="row">
        <p class="text-muted text-left col-md-6">Copyright 2015. All Rights Reserved.</p>
        <p class="text-muted text-right col-md-6">Facebook - Twitter - LinkedIn.</p>
        </div>
      </div>
    </footer>


    <!-- Bootstrap core JavaScript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="dropdown.js"></script>
    <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
    <script src="ie10-viewport-bug-workaround.js"></script>
    <script>
$(document).ready(function() {
  $(function() {
    $( "#slider-range, #slider-range2" ).slider({
      range: true,
      min: 15,
      max: 100,
      values: [15, 100 ],
      slide: function( event, ui ) {
        $( "#amount" ).val(ui.values[ 0 ] + " - " + ui.values[ 1 ] );
      }
    });
    $( "#amount" ).val($( "#slider-range" ).slider( "values", 0 ) +
      " -" + $( "#slider-range" ).slider( "values", 1 ) );
  });
  $('#city').on('blur', function() 

$.post( "search.php", { city: $('#city').val(); } );



});
});


</script>
  </body>
</html>

3

Answers


  1. this is a basic example to how to use $.post

    $('#city').on('blur', function() {
      $.post( "search.php", { city: $('#city').val() } , function(){
          alert(data);
      });
    });
    

    in search.php

    <?php 
       echo $_POST['city'];
    ?>
    

    the output should be your city value

    Edit: removed semicolon from $.post( "search.php", { city: $('#city').val() } , function(){

    Login or Signup to reply.
  2. There are some fundamental conflicts between what you are trying to achieve and what you are doing.

    Using AJAX ($.post()) requires a connection to a server that returns ONLY the data you want. Normally it would be in JSON format {“city”:”cityname”}. However, your $.post() directs itself to search.php code that publishes the entire web page and just happens to fill in the city.

    Possible solutions:

    1. Ignore AJAX, remove $.post(), and in Javascript reload the whole web page as I mentioned earlier window.location.replace("search.php?city=+"cityname); You can use Javascript to get the value of city first e.g. var cityname = $('#city').val; You will also have to change the php from $_POST['city'] to $_GET['city']

    2. create a new file called searchajax.php and put your database and echo $_POST there, and change the code to properly support ajax. I am not going to document that here, because the internet is full of “how to do ajax” such as http://labs.jonsuh.com/jquery-ajax-php-json/ and using jquery $.ajax to call a PHP function and my comments 3 hours ago showing the jquery reference.

    Most importantly, none of your code exhibits any security or sanitizing. Ajax, PHP – fetch from database http://www.peachpit.com/articles/article.aspx?p=1748185&seqNum=3 Even if you use option 1, you need to make sure no sql can be injected in your database search, and no html (and therefore no javascript) can be output from your database to the unsuspecting user.

    Login or Signup to reply.
  3. The quick answer here is post will only load a new page if you tell it to do so.
    Now let’s cover some basic things in your script that are exhibited.
    First off, you don’t need multiple document ready event handlers (that IS an event and those are handlers of that event)
    SO, simplify your script thus:

    Remove duplicate event handlers and fix small syntax in the post:

    $(document).ready(function () {
         var availableTags = [
             "Lahore",
             "Karachi",
             "Islamabad",
             "Rawalpindi",
             "Faisalabad",
             "Multan",
             "Gujranwala",
             "Quetta",
             "Peshawar",
             "Hyderabad",
             "Sialkot"];
         $("#city").autocomplete({
             source: availableTags
         });
         $("#slider-range, #slider-range2").slider({
             range: true,
             min: 15,
             max: 100,
             values: [15, 100],
             slide: function (event, ui) {
                 $("#amount").val(ui.values[0] + " - " + ui.values[1]);
             }
         });
         $("#amount").val($("#slider-range").slider("values", 0) +
             " -" + $("#slider-range").slider("values", 1));
         $('#city').on('blur', function () {
             $.post("search.php", {
                 'city': $('#city').val()
             });
         });
     });
    

    Next, let’s visit the ajax function. First off, $.post is simply an alias/shortcut for $.ajax( SO, let’s for completeness show three different ways to put in that ajax call: while adding a handler for the return from your call to the server with the new data (whatever that is here)

     // first we create a post data object to simplify our examples
     var mydata = {
         'city': $('#city').val()
     };
    
     // next we show how to add a handler to the data return success event 
     $.post("search.php", mydata, function (returndata) {
         // do somthing with returndata here
     });
    
     // same as the post but not using the alias
     $.ajax({
         type: "POST",
         url: 'search.php',
         data: mydata,
         dataType: 'JSON',
         success: function (returndata) {
              // do something with returndata here
         }
     });
    
     //finally we use the more modern example with the
     var myjqxhr = $.ajax({
         type: "POST",
         url: 'search.php',
         data: mydata,
         dataType: 'JSON'
     });
     myjqxhr.done(function (returndata) {
         // do something with returndata here
     });
    

    NOW with that understanding, we can rework the $.post to use that done also:

    $.post('search.php', mydata)
     .done(function (returndata) {
         // do something with returndata here
     });
    

    Now NONE of this actually solves your problem – what data is returned and what to do with it inside that function – you have to decide that and then DO that.
    With that in mind, what perhaps you intend is that you need to check for values of all three of your entry (city, gender, level) are filled, completed THEN redirect with window.location.replace

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search