2014-10-14 2 views
0

Im пытается получить мой PHP-скрипт из AJAX (то есть в моем основном файле php). Вот пример того, что он должен делать: http://jsfiddle.net/xfuddzen/Переменная PHP не передается на вызов AJAX?

Исходный код HTML показывает только созданный файл desk_box DIV (который находится в моем main.php). Station_info DIV (создается на display_station.php) не существует. Как я могу это исправить? заранее спасибо

Проблема: DIVs из моего display_stationinfo.php не создаются с помощью вызова AJAX.

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 (сценарий, который я хочу назвать):

<?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; 
?> 

ответ

0

Почему бы вам не фильтровать координаты в запрос? Как это:

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

И в Jquery код:

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

Код впрыска SQL-кода – Brewal

+0

это не поможет – mario

0

Давайте начнем с подключением к базе данных, которая должна быть на отдельной защищенной странице.

connect.php:

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

Очевидно, что ваш хозяин не будет 'host'.

Теперь 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> 

Теперь 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;}` 
//]]> 

Теперь для 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 
} 
?> 

Вот что 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 
} 
?> 
+0

Почему я не хотел бы конкатенации непосредственно в цикле while вместо этого оператора If-Else? Кроме того, должно ли эхо $ html быть правильным до закрытия соединения? спасибо – mario

+0

Если вы делаете '$ html = 'anything';' в цикле он заменяет старое значение '$ html'. Что делать if-else? Нет, закрытие соединения просто освобождает серверные ресурсы, он не убивает ваш скрипт. – PHPglue

+0

проверил ваш код. такая же ошибка возникает – mario

Смежные вопросы