简体   繁体   English

mysql查询数据未通过ajax从php正确传递给javascript

[英]mysql query data not correctly being passed to javascript from php via ajax

i am trying to create a website that allows the user to enter an address into an html form. 我试图创建一个网站,允许用户以html形式输入地址。 when the user hits the submit button, i want php to get the form data and then use that data to access a mysql database that stores addresses, based on the form data the php will query the mysql database and return the addresses within a given distance. 当用户单击提交按钮时,我希望php获取表单数据,然后使用该数据访问存储地址的mysql数据库,基于表单数据,php将查询mysql数据库并返回给定距离内的地址。 then i want to use ajax to pass that result into javascript where i will use the data to create a google map with all the addresses plotted onto the map. 然后我想使用ajax将结果传递到javascript中,在那我将使用数据创建一个Google地图,并将所有地址绘制到该地图上。 the problem i am having right now is simply displaying the data to the console in javascript. 我现在遇到的问题只是使用javascript将数据显示到控制台。 i've noticed that every time i hit the submit button it seems as though the html page is being refreshed, so i'm thinking it is possible that the refresh is the cause of the data not being properly passed. 我注意到,每当我按下“提交”按钮时,似乎都在刷新html页面,因此,我认为刷新可能是导致数据未正确传递的原因。

HTML Form code (with javascript / ajax) HTML表单代码(使用javascript / ajax)

<html>
<head>
<title></title>
</head>
<body>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
  <div class = "container">
    <nav class = "navbar navbar-inverse">
      <div class = "container-fluid">
        <div class = "navbar-header">
          <a class = "navbar-brand" href = "home.html">YardSaleMapper.com</a>
        </div>
        <ul class = "nav navbar-nav">
          <li><a href = "home.html">Go Home</a></li>
          <li class = "active"><a href = "viewSales.php">View Sales</a></li>
          <li><a href = "addSale.html">Publish your Sale</a></li>
        </ul>
      </div>
    </nav>
    <h3>Enter Starting Point</h3>
    <hr/>
    <form method = "post" id = "myForm">
      <div class = "col-md-2">
        <div class = "form-group">
          Street:
          <input class = "form-control" type = "text" name = "start_street" ng-model = "ss" required/>
        </div>
      </div>
      <div class = "col-md-2">
        <div class = "form-group">
          City:
          <input class = "form-control" type = "text" name = "start_city" ng-model = "ss" required/>
        </div>
      </div>
      <div class = "col-md-2">
        <div class = "form-group">
          State (EX: PA):
          <input class = "form-control" type = "text" name = "start_state" ng-model = "ss" maxlength="2" required/>
        </div>
      </div>
      <div class = "col-md-2">
        <div class = "form-group">
          ZIP
          <input class = "form-control" type = "text" name = "start_zip" ng-model = "ss" maxlength="5" required/>
        </div>
      </div>
      <div class = "col-md-2">
        <div class = "form-group">
          Within <select type = "text" name = "distance" required  class = "form-control">
            <option value = 5>5</option>
            <option value = 10>10</option>
            <option value = 15>15</option>
            <option value = 20>20</option>
            <option value = 25>25</option>
          </select>
          Miles
        </div>
      </div>
      <div class = "col-md-2">
        <div class = "form-group">
          &nbsp
          <button class ="btn btn-primary btn-block" id = "submit" type = "submit" name = "submit">Submit</button>
        </div>
      </div>
    </form>
  </div>

  <script id = "source" language = "javascript" type = "text/javascript">
  $(function() {
    $('#submit').on('click', function() {
      $.ajax({
        url: 'getSales.php',
        method: 'post',
        data: $("#myForm").serialize(),
        dataType: 'json',
        success: function(data) {
          console.log(data);
        }
      })
    })
  });
  </script>

</body>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>


</html>

PHP Code accessing mysql database and echoing the results. PHP代码访问mysql数据库并回显结果。

<?php
  $servername = "localhost";
  $username = "username";
  $password = "password";
  $dbname = "yardsales";

  $data = array();

  // Create connection
  $conn = new mysqli($servername, $username, $password, $dbname);
  // Check connection
  if ($conn->connect_error) {
      die("Connection failed: " . $conn->connect_error);

  }

  $street = $_POST["start_street"];
  $city = $_POST["start_city"];
  $state = $_POST["start_state"];
  $zip = $_POST["start_zip"];
  $dist = $_POST["distance"];

  $address = $street . ", " . $city . ", " . $state . ", " . $zip;

  $geo = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address='.urlencode($address).'&sensor=false');

  // Convert the JSON to an array
  $geo = json_decode($geo, true);

  if ($geo['status'] == 'OK') {
    // Get Lat & Long
    $lat = $geo['results'][0]['geometry']['location']['lat'];
    $long = $geo['results'][0]['geometry']['location']['lng'];

  }

  $sql = "SELECT street, city, state, zip, county, sdate, edate,
  stime, etime, description, 69 * vincenty($lat, $long, lat, lon) AS distance from
  addresses where 69 * vincenty($lat, $long, lat, lon) < $dist";

  $result = $conn->query($sql);

  while($row = $result->fetch_assoc()) {
    $data[] = $row;
    //print_r($row);
  }

  echo json_encode($data);

?>

Your submit button is making a post request and refresh the page, so the Javascript loses its data. 您的“提交”按钮正在发出发布请求并刷新页面,因此Javascript丢失了数据。 You have to change this: 您必须更改此:

<form method = "post" id = "myForm"> 

or the button to another tag, like 或另一个标签的按钮,例如

<a></a>.

And use PDO instead of mysqli. 并使用PDO代替mysqli。 Will be better for you 对你会更好

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM