2013-10-30 6 views
-1

$ .load에로드되는 문서에 변수를 보내고 $ .load에서 변수를 검색하지 않는 것에 대한 질문을 보았습니다.

아래에 적절한 코드 조각을 붙여 넣었습니다. 근본적으로 내가하려는 것은 PHP 함수를 매번 자주 실행하고 페이지가 처음로드 될 때입니다.

페이지가 처음로드되면 getData 함수가 실행되고 모든 것이 의도 한대로 작동합니다. 하지만 나중에 페이지 아래로, 내가 pullData.php를로드하려고하면 srcAverage가 새 값으로 업데이트되지 않습니다. JS 경고는 srcAverage 값을 보여줍니다.

예 : 페이지가 처음 실행될 때 srcAverage는 X입니다. 5 초마다 우리는 pullData.php를로드하고 index.php의 srcAverage를 새 값 (X 변경)으로 업데이트하려고합니다.

내가 정말 잘못하고있는 것처럼 느껴집니다 - 아이디어가 있습니까?

conn.php

<?php 
define("HOST", "stuff"); 
define("USER", "stuff"); 
define("PASSWORD", "stuff"); 
define("DATABASE", "stuff"); 
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE); 
// Connection info above all works as intended 
?> 

의 index.php

<?php 
include 'inc/conn.php'; 
include 'inc/function.php'; 
$src = "none"; 
getData($src, $mysqli); 
// This initial run of getData works as intended 
// Skip to further down 
// The JS alert below does NOT reflect the new srcAverage 
?> 
<script type="text/javascript"> 
$(document).ready(function() { 
setInterval(function() { 
    // each interval, get first and second values 
    $("#targetDiv").load("pullData.php"); 
    alert('New value is <?php echo $srcAverage; ?>'); 
    }, 5000); // end setInterval 
}); 
</script> 

pullData.php

<?php 
include 'incl/conn.php'; 
include 'incl/function.php'; 
$src = "none"; 
getData($src, $mysqli); 
?> 

GetData의 기능 (코드 아래 참조)를 분리 표 4의 값을 잡고, 평균 함께 (나는 그것들을 모두 문제 해결을위한 다른 진술과 변수로 분리시켰다), 그 다음에 se 변수 srcAverage는 평균값입니다. 나는 MySQLi 문장이 잘 작동하는지 테스트했으며, srcAverage 이 함수에 의해 올바른 값을 할당 받았다. Echoing 또는 JS 경고는 의도 한대로 값을 표시합니다 (이 페이지에서). 그러나 변수는 load()를 통해로드 될 때 index.php로 전달되지 않습니다. 서버에 새로운 인수 그런

$("#element").load("file.php", { 'myVar' : 'someValue'}); 

function.php

<?php 
function getData($src, $mysqli) { 

    // Check SRC for specific source 
    // If no specific source, get average of all sources 
    // If YES specific source, get that value 
    global $srcAverage; 

    if ($src == 'alt') { 
     if ($stmt = $mysqli->prepare("SELECT value FROM table ORDER BY id DESC LIMIT 1;")) { 
     $stmt->execute(); // Execute the prepared query. 
     $stmt->store_result(); 
     $stmt->bind_result($altVal); // get variables from result. 
     $stmt->fetch(); 

     if($stmt->num_rows == 1) { // The entry exists, good to go 
     // echo $altVal; 
     } 
     } else { 
     // Either no results pulled or more than one. 
     echo "Error pulling alternate data!"; 
     return false; 
     } 
    } 
    else { 

    // Value 1 
     if ($stmt = $mysqli->prepare("SELECT value FROM table ORDER BY id DESC LIMIT 1;")) { 
     $stmt->execute(); // Execute the prepared query. 
     $stmt->store_result(); 
     $stmt->bind_result($firstVal); // get variables from result. 
     $stmt->fetch(); 

     if($stmt->num_rows == 1) { 
     // echo $firstVal; // This works as intended 
     } 
     } else { 
     // Either no results pulled or more than one. 
     echo "Error pulling first value data!"; 
     return false; 
     } 

    // Value 2 
     if ($stmt = $mysqli->prepare("SELECT value FROM table ORDER BY id DESC LIMIT 1;")) { 
     $stmt->execute(); // Execute the prepared query. 
     $stmt->store_result(); 
     $stmt->bind_result($secondVal); // get variables from result. 
     $stmt->fetch(); 

     if($stmt->num_rows == 1) { // The entry exists, good to go 
     // echo $secondVal; 
     } 
     } else { 
     // Either no results pulled or more than one. 
     echo "Error pulling second value data!"; 
     return false; 
     } 

    // Value 3 
     if ($stmt = $mysqli->prepare("SELECT value FROM table ORDER BY id DESC LIMIT 1;")) { 
     $stmt->execute(); // Execute the prepared query. 
     $stmt->store_result(); 
     $stmt->bind_result($thirdVal); // get variables from result. 
     $stmt->fetch(); 

     if($stmt->num_rows == 1) { // The entry exists, good to go 
     // echo $thirdVal; 
     } 
     } else { 
     // Either no results pulled or more than one. 
     echo "Error pulling third value data!"; 
     return false; 
     } 

    // Value 4 
     if ($stmt = $mysqli->prepare("SELECT value FROM table ORDER BY id DESC LIMIT 1;")) { 
     $stmt->execute(); // Execute the prepared query. 
     $stmt->store_result(); 
     $stmt->bind_result($fourthVal); // get variables from result. 
     $stmt->fetch(); 

     if($stmt->num_rows == 1) { // The entry exists, good to go 
     // echo $fourthVal; 
     } 
     } else { 
     // Either no results pulled or more than one. 
     echo "Error pulling fourth value data!"; 
     return false; 
     } 

// So everything up to this point is working fine. Statements grab data as intended, and assign variables. 
// We have data - move forward 
     $srcCount = 4; 
     $srcTotal = $firstVal + $secondVal + $thirdVal + $fourthVal; 
     $srcAverage = $srcTotal/$srcCount; 
     $srcAverage = number_format((float)$srcAverage, 2, '.', ''); 
// echo "Total: $srcTotal .... Average: $srcAverage"; 
// If we were to echo above, it would display correctly. Problem is passing the variable to index 

     return $srcAverage; 
} 

} 
?> 
+0

@Evan :

그래서, 당신의 고정 된 버전은 다음과 같습니다 Javascript TO PHP가 아니라. – MWJump

+0

@ 에반 : 그 질문의 사본이 아닙니다. 위에서 MWJump가 말했듯이 - 나는 TO가 아닌 파일을 전달하려고했습니다. – Lent

답변

0

$ srcAverage을 통해 PHP가 출력됩니다. 브라우저는 서버에서 PHP를 얻지 못하거나 실행 방법을 알고 있지만 PHP 스크립트의 결과 만 볼 수 있습니다. 당신이 소스를 볼 경우에 따라서, 당신은 당신의 경고는 것을 볼 것은 :

PHP는 이미 실행
alert('New value is '); 

, $ srcAverage가 변환하는 를 넣어 있도록 인해 범위에 정의되지 않은 한 에코했다 빈 문자열.

$ .load에 의해로드되는 것은 pullData.php의 결과이며 이미 php로 구문 분석되어 서버를 통해 반환됩니다. pullData.php에는 출력이 없습니다. 자바 스크립트가 getData를 볼 수 있도록 getData의 결과를 표시해야합니다.

당신이 자바 스크립트에서 일을해야하는 것입니다 : 당신은 또한 #targetDiv 누락 것 같다 귀하의 예제 마크 업에

alert('New value is ' + $('#targetDiv').html()); 

를 기준으로합니다. #targetDiv에 원래 getData를 래핑하려고합니다. 문제가 PHP의 변수를 전달하고 그것의 모양에서

index.php를

<div id='targetDiv'> 
<?php 
include 'inc/conn.php'; 
include 'inc/function.php'; 
$src = "none"; 
echo getData($src, $mysqli); 
// This initial run of getData works as intended 
// Skip to further down 
// The JS alert below does NOT reflect the new srcAverage 
?> 
</div> 

<script type="text/javascript"> 
$(document).ready(function() { 
setInterval(function() { 
    // each interval, get first and second values 
    $("#targetDiv").load("pullData.php"); 
    alert('New value is ' + $('#targetDiv').html(); 
    }, 5000); // end setInterval 
}); 
</script> 

pullData.php

<?php 
include 'incl/conn.php'; 
include 'incl/function.php'; 
$src = "none"; 
echo getData($src, $mysqli); 
?> 
+0

고맙습니다 - 당신의 솔루션은 매우 유익하고 유익했습니다. 그것은 또한 효과적이었습니다 :) 문제의 맥락에서 가장 밀접하게 맞았 기 때문에이 솔루션을 가장 잘 표시했습니다. function.php에서 반환하기 전에 srcAverage를 표시 한 다음 제안 된대로 JS에서 경고를 변경했습니다. 경고에 의도 한 값이 표시되었습니다. 감사합니다. – Lent

0

패스를 :

$_POST['myVar']; 

이 값이 포함됩니다.

편집 어쩌면 당신이 부하 함수에서 데이터에 액세스하려는 경우, 당신은 콜백을 사용할 필요가 이해 MIS.

$('#element').load('file.php', function(data){ 
    //response from the server 
}); 
+0

이것은 OP가하려고하는 것의 반대입니다 –

1

PHP 페이지 수명주기를 오해하고 있습니다. <?php echo $srcAverage; ?>은 페이지가 처음로드되거나 렌더링 될 때 한 번만 평가됩니다. 새 값을 얻고 싶다면

, 당신은 아마 대신 .load()$.ajax()를 사용으로 전환해야하고, json은 그래서 당신은 자바 스크립트 응답과 함께 작업 할 수 pullData.php 그 결과를 에코했다.

+0

흠, 그 말이 맞습니다. 대신 json을 사용할 것입니다. 감사합니다 :) – Lent

관련 문제