简体   繁体   English

PHP变量未传递给AJAX调用?

[英]PHP variable not being passed to AJAX call?

Im trying to get my PHP script called from AJAX (that is in my main php file). 我试图从AJAX(位于我的主要php文件中)获取我的PHP脚本。 Here's an example of what it is supposed to do: http://jsfiddle.net/xfuddzen/ 这是应该执行的示例: http : //jsfiddle.net/xfuddzen/

The HTML source code shows only desk_box DIV being created (which is in my main.php). HTML源代码仅显示正在创建的desk_box DIV(位于我的main.php中)。 station_info DIV (being created in the display_station.php) is not there. station_info DIV(在display_station.php中创建)不存在。 How can I fix this? 我怎样才能解决这个问题? thanks in advance 提前致谢

Problem: DIVs from my display_stationinfo.php are not being created by using the AJAX call. 问题:我的display_stationinfo.php文件中的DIV没有通过AJAX调用创建。

main.php with JQuery/AJAX part: main.php和JQuery / AJAX部分:

<div id="map_size" align="center">

<?php
                    //didsplay Desk stations in the map
                    while($row = mysqli_fetch_assoc($desk_coord_result)){   
                        //naming X,Y values
                        $id    = $row['coordinate_id'];
                        $x_pos = $row['x_coord'];
                        $y_pos = $row['y_coord'];
                        //draw a box with a DIV at its X,Y coord     
                        echo "<div class='desk_box' data='".$id."' style='position:absolute;left:".$x_pos."px;top:".$y_pos."px;'>id:".$id."</div>";
                } //end while loop for desk_coord_result
     ?>

    <script type="text/javascript">
        //Display station information in a hidden DIV that is toggled
        //And call the php script that queries and returns the results LIVE
        $(document).ready(function() {
            $('.desk_box').each((function(){(this).click(function()    {
            var id = $(this).attr("data")
                $("#station_info_"+id).toggle();

        $.ajax({
            url: 'station_info.php',
            data: { 'id': id },
            type: 'POST',
            dataType: 'json',
        success: function(json) {
$("#station_info_"+id).css({'left':json.x_pos ,'top': json.y_pos}).append('<p>Hello the id is:'+     json.id +'</br>Section:'+ json.sec_name +'</p>');
            }//end success
            });//end ajax
            });//end click
            });//end ready
</script>
</div> <!-- end map_size -->

display_station.php (script that I want to call): display_station.php(我要调用的脚本):

<?php
include 'db_conn.php';
//query to show workstation/desks information from DB for the DESKS
$station_sql = "SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates";
$station_result = mysqli_query($conn,$station_sql);

//see if query is good
if ($station_result === false) {
    die(mysqli_error()); 
}


//Display workstations information in a hidden DIV that is toggled
    $html = '';
if($station_result->num_rows > 0){
  while($row = $station_result->fetch_object()) {
    $id  = $row->coordinate_id;
    $html .= "<div class='station_info_' id='station_info_$id' style='position:absolute;left:{$row->x_coord}px;top:{$row->y_coord}px;'>Hello the id is:$id</br>Section:{$row->section_name}</br></div>";
  }
}
else{
  // no results - may want to do something with $html
          $html = "no result given";
}

$station_result->free(); 
$conn->close();
echo $html;
?>

Why dont you filter the coordinate in the query? 为什么不过滤查询中的坐标? Like this: 像这样:

$station_sql = "SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates WHERE coordinate_id = " . $_GET['coordinate_id'];

And in jquery code: 并在jQuery代码中:

url: 'display_stationinfo.php?coordinate_id=' + id,

Let's start with your database connection, which should be on a separate secure page. 让我们从数据库连接开始,它应该在单独的安全页面上。

connect.php : connect.php

<?php
function db(){
  return new mysqli('host', 'username', 'password', 'database');
}
?>

Obviously, your host will not be 'host' . 显然,您的主机不会是'host'

Now main.php : 现在main.php

<?php
// only use for PHP on this page for initial page load - target other pages with AJAX
?>
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
  <head>
    <meta http-equiv='content-type' content='text/html;charset=utf-8' />
    <title>This is Where Your Title Goes</title>
    <script type='text/javascript' src='//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script>
    <script type='text/javascript' src='main.js'></script>
    <link rel='stylesheet' type='text/css' href='main.css' />
  </head>
<body>
  <div id='map_container'>
    <div id='map_size'>
    </div>
  </div>
</body>
</html>

Now for main.js : 现在为main.js

//<![CDATA[
$(function(){
var ms = $('#map_size');
$.post('main_init.php', {init:'1'}, function(d){
  for(var i in d){
    var di = d[i], x = di.x, y = di.y;
    var sti = $("<div class='station_info_' id='station_info_"+i+"'></div>").css({
      left:x,
      top:y
    });
    // HTML id, class, and name attributes cannot start with a number
    $("<div class='desk_box' data='"+i+"'>id&#058;"+i+'</div>').css({
      left:x,
      top:y
    }).appendTo(ms).append(sti).click(function(){
      var info = $(this).next();
      $.post('live_info.php', {station_id:info.attr('id').replace(/^station_info_/, '')}, function(r){
        // do stuff with r
        info.html('love:'+r.love+'<br />hate:'+r.hate).toggle();
      }, 'json');
    });
  }
}, 'json');
});
// use CSS to do `.desk_box,.station_info_{position:absolute;}`
//]]>

Now for main_init.php : 现在为main_init.php

<?php
if(isset($_POST['init']) && $_POST['init'] === '1'){
  include_once 'connect.php'; $db = db(); $json = array();
  $q = $db->query("SELECT * FROM table WHERE"); // example only
  if($q->num_rows > 0){
    while($r = $q->fetch_object()){
      $json[strval($r->coordinate_id)] = array('x' => $r->x_coord, 'y' => $r->y_coord);
    }
  }
  else{
    // no results
  }
  $q->free(); $db->close();
  echo json_encode($json);
}
else{
  // could be a hack
}
?>

Here's what live_info.php might look like: 这是live_info.php样子:

<?php
if(isset($_POST['station_id'])){
  include_once 'connect.php'; $db = db(); $json = array();
  // example only - you will only get one `$row` if query is done specific, so while loop is not needed
  $q = $db->query("SELECT love,hate FROM some_table WHERE id='{$_POST['station_id']}'");
  if($q->num_rows > 0){
    $row = $q->fetch_object();
    // it's okay to overwrite array in this case
    $json = array('love' => $row->love, 'hate' => $row->hate);
  }
  else{
    // no results
  }
  $q->free(); $db->close();
  echo json_encode($json);
}
else{
  // may be a hack
}
?>

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

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