简体   繁体   English

使用来自多个PHP页面的AJAX函数中的填充变量更新SQL查询

[英]Update SQL Query with populated variables from AJAX functions over multiple PHP Pages

i try to get help with that question. 我试图获得有关该问题的帮助。

All in all Q: It doesnt Update my DB entry like this Step by Step Order how i think it could be done. 总而言之,我不会像这样一步一步地更新数据库条目。

its a bit difficult to explain, but i try to explain it step by step with minimal and readable Code. 它有点难以解释,但是我尝试用最少的可读代码逐步解释它。 I use the original code, its hard to convert it in reproducible Examples. 我使用原始代码,很难将其转换为可复制的示例。

A.1 Page ma_aktuelle_ReadOut.php There is a php Part A.1页面ma_aktuelle_ReadOut.php有一个php部分

 <?php echo "<a href='ma_Testende.php?TestergebnisID=&TestaufstellungID=". $row['TestaufstellungID']."&TesterID=".$row['TesterID']."' title='Test stoppen' data-toggle='tooltip' class='stoppen'>   <span class='glyphicon glyphicon-stop'></span></a>";
?>

When i click this link the following javascript function is called and ask me "really stop?" 当我单击此链接时,将调用以下javascript函数,并问我“真的停止了吗?”

<script language="JavaScript" type="text/javascript">
$(document).ready(function(){
  $("a.stoppen").click(function(e){
   if(!confirm('Wirklich stoppen?')){
    e.preventDefault();
    $('.alert').show()
    return false;
    }
    return true;
            });
        });
</script>
<style>
 .alert {
  display: none;
    }
</style>

When i cklick "yes" it opens the second Page. 当我点击“是”时,它将打开第二个页面。

A 2 Page ma_Testende.php On this Page are 2 AJAX JS Functions. 2页的ma_Testende.php此页面上有2个AJAX JS函数。 The first Ajax is asking for "Datum" via type:get from the following next page and wait till success (see Page B 3): 第一个Ajax通过type:get询问“基准”,从下一页type:get并等待成功(请参见B 3页):

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">

/* function to get Stoptime for Cycle from DB.TesterCycleCount zu erhalten  */ 
$(document).ready(async function(){
var Datum;
var TesterID = "<?php echo $_GET['TesterID']; ?>"; /* value from TesterID */ 
await $.ajax({ /* First Ajax function */
            url: 'ma_get-TesterID_Testende.php',
            type: 'get', 
            data: {TesterID:TesterID}, 
            dataType: 'json',
            success:function(response){ 
                var CID = response['CID'];
                Datum = response['Datum'];
                console.log(response);
            },
             error: function(jqxhtt, status, exception) {
                 console.log(exception);
         alert('Exception:', exception)
            }
        });
console.log();
        var TestaufstellungID = "<?php echo $_GET['TestaufstellungID']; ?>";
         $.ajax({ /* Second Ajax function */
            url: 'ma_TestendeSQL.php',
            type: 'get', 
            data: {TestaufstellungID:TestaufstellungID, Datum: Datum}, 
            dataType: 'json',
            success:function(data){ 
            alert('Successfully called');
     },
     error: function(jqxhr, status, exception) {
         console.log(exception);
         alert('Exception:', exception)
            }
        });
        });
</script>

B 3 Page ma_get-TesterID_Testende.php B 3页ma_get-TesterID_Testende.php

<?php
$cinfo = array(
    "Database" => $database,
    "UID" => $username,
    "PWD" => $password
);
$conn = sqlsrv_connect($server, $cinfo);
                $sqlreadZeit = "Select TOP 1 CID,Datum from DB.dbo.TesterCycleCount where TesterID = '".$_GET['TesterID']."' order by Datum DESC";
                $result1 = sqlsrv_query($conn, $sqlreadZeit);
                $zeiten_arr = array();
                while ($row = sqlsrv_fetch_array($result1, SQLSRV_FETCH_ASSOC)) {
                $CID = $row['CID'];
                $Datum = $row['Datum']->format('d.m.Y h:m:s');
                $zeiten_arr[] = array("CID" => $CID, "Datum" => $Datum);
                                }
    header('Content-type: application/json');
  echo json_encode($zeiten_arr); 
?>

Back with the "Datum" the second AJAX is called (see Page A 2) With the "Datum" and "TestaufstellungID" as variable it should be call the next Page and Update the DB entry with the populated variablles. 返回带有“基准”的第二个AJAX(请参见第A 2页),以“基准”和“ TestaufstellungID”作为变量,应调用下一个Page,并使用填充的变量来更新数据库条目。

B. 4 Page ma_TestendeSQL.php B.第4页ma_TestendeSQL.php

<?php
$cinfo = array(
    "Database" => $database,
    "UID" => $username,
    "PWD" => $password
);
$conn = sqlsrv_connect($server, $cinfo);

$TestaufstellungID = $_GET['TestaufstellungID'];
$Testende= $_GET['Datum'];
$Testdatum = date('Y-d-m');

$stop = $connection->prepare("WITH UpdateTestende AS (
  SELECT TOP 1  * from DB.dbo.Testergebnisse 
  WHERE TestaufstellungID = :TestaufstellungID
  ORDER BY TestergebnisID DESC 
)
update UpdateTestende 
set Testende = :Testende,
Datum = :Testdatum");
$stop->execute(array(':TestaufstellungID' => $TestaufstellungID, ':Testdatum' => $Testdatum, ':Testende' => $Testende));

    header('Content-type: application/json');
?>

The php variable $Testende get the populated "Datum" from the Ajax functions. php变量$Testende从Ajax函数获取填充的“基准”。 All in all at the end it should be Update, when i click on the link the ( Page A 1) my DB entry with the populated "Datum" which i get from the first Ajax call ( Page A 2 ) from the SQL Query ( Page B 3) back to the second AJAX Call ( Page A 2 ) than with the data: {TestaufstellungID:TestaufstellungID, Datum: Datum} to the last page ( Page B 4) 总而言之,它应该是Update,当我单击链接(第A 1页)我的DB条目时,它带有从SQL查询(第一个Ajax调用(第A 2页)获得的填充的“基准”)页面B 3)返回到第二个AJAX调用(页面A 2),而不是数据: {TestaufstellungID:TestaufstellungID, Datum: Datum}到最后一页( {TestaufstellungID:TestaufstellungID, Datum: Datum} B 4)

But it doesnt Update my DB entry like this Step by Step Order how i think it could be done. 但是它并没有像我这样一步一步地更新我的数据库条目,我认为这是可以做到的。

Encapsulated is the SQL-Code working fine. 封装的SQL代码可以正常工作。 With the Code header('Content-type: application/json'); 使用Code header('Content-type: application/json'); the browser tell me the following when i click on the link from ( Page A 1 ) 当我单击(页面A 1)中的链接时,浏览器告诉我以下内容

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data SyntaxError:JSON.parse:JSON数据的第1行第1列出现意外字符

Thats why i posted all the Step i think on one point the variables are not passed right to the next page or they are empty becasue the code is not executed in the right order Server/Client PHP/JS or Asynchronous problem... The console.log tell me nothing. 这就是为什么我将所有步骤都发布在一个点上的原因,这些变量未正确传递到下一页,或者它们为空,因为未按正确的顺序执行代码服务器/客户端PHP / JS或异步问题...控制台.log什么也没告诉我。 At the moment i have no idea where to start with the debugging? 目前我不知道从哪里开始调试?

Hope someone can help me. 希望可以有人帮帮我。 thx 谢谢

Edit: iam pretty sure the ajax call is empty, but i dont see it in which step the values getting empty 编辑:我很确定ajax调用是空的,但我看不到在哪一步中值变得空

Edit2: AJAX Call is empty or is not starting. Edit2: AJAX呼叫为空或未启动。 Further invstigation: The Ajax alert me the error part with empty exception and dont alert me the success part. 进一步调查:Ajax用空异常警告我错误部分,而不警告我成功部分。 So it doesnt go to the page ma_get-TesterID_Testende.php or it doesnt return back the Datum . 因此,它不会转到ma_get-TesterID_Testende.php页面,或者不会返回Datum Could be not enabled Cross-Site-Scripting be the Problem? 无法启用跨站点脚本是问题吗?

But in another Page is a similiar Ajax Call working fine. 但是在另一个Page中,类似的Ajax Call可以正常工作。

$(document).ready(function(){

var TesterID = "<?php echo $_GET['TesterID']; ?>"; /* value der Tester erhalten */ 

        $.ajax({ /* AJAX aufrufen */
            url: 'ma_get-TesterID.php',
            type: 'get', /* Methode zum übertragen der Daten */
            data: {TesterID:TesterID}, /* Daten zu übermitteln */
            dataType: 'json',
            success:function(response){ /* Die zurückgegebenene Daten erhalten */

                var len = response.length;

                $("#Teststart").empty(); /* Die erhaltenden Daten werden bei der ID angezeigt */
                for( var i = 0; i<len; i++){
                    var CID = response[i]['CID'];
                    var Datum = response[i]['Datum'];

                    $("#Teststart").append("<option value='"+Datum+"'>"+Datum+"</option>");

                }
            }
        });


    $("#TesterID").change(function(){ /* Wenn du änderst und vom Select Feld auswählst */
        var TesterID = $(this).val(); /* value der Tester erhalten */ 

        $.ajax({ /* AJAX aufrufen */
            url: 'ma_get-TesterID.php',
            type: 'get', /* Methode zum übertragen der Daten */
            data: {TesterID:TesterID}, /* Daten zu übermitteln */
            dataType: 'json',
            success:function(response){ /* Die zurückgegebenene Daten erhalten */

                var len = response.length;

                $("#Teststart").empty(); /* Die erhaltenden Daten werden bei der ID angezeigt */
                for( var i = 0; i<len; i++){
                    var CID = response[i]['CID'];
                    var Datum = response[i]['Datum'];

                    $("#Teststart").append("<option value='"+Datum+"'>"+Datum+"</option>");

                }
            }
        });
    });

});

In this example the Ajax Call starts when i change the value from a Dropdown selection Form. 在此示例中,当我从下拉列表选择表单中更改值时,Ajax调用开始。 Is there a difference? 有区别吗?

How this Ajax should work i try to explain in my other question step by step, how it my application should be execute. 我将尝试在其他问题中逐步解释该Ajax如何工作,应如何执行我的应用程序。

Update SQL Query with populated variables from AJAX functions over multiple PHP Pages 使用来自多个PHP页面的AJAX函数中的填充变量更新SQL查询

Edit 3: JQuery Version: https://code.jquery.com/jquery-3.4.1.js 编辑3: jQuery版本: https : //code.jquery.com/jquery-3.4.1.js

One alternative is use $_SESSION superglobal; 一种选择是使用$ _SESSION超全局变量。 I offer it as this question is tagged as PHP rather than AJAX/JSON, and to avoid encode-decode common issues with JSON values or arrays. 我提供它是因为该问题被标记为PHP而不是AJAX / JSON,并且避免了JSON值或数组的常见编码问题。 If you're able to, change your strategy and use client-side to broadcast data and stop normal flow in an error response event. 如果可以,请更改策略并使用客户端广播数据并在错误响应事件中停止正常流。

With a started session_start() you can use an inner temporary array in $_SESSION to attach/detach step by step data, in this example "step" array, like this: 通过启动session_start(),您可以在$ _SESSION中使用内部临时数组来附加/分离逐步数据,在此示例中为“ step”数组,如下所示:

<?php
// step 1
$_SESSION['step'][1]['TesterID']            = 64;
$_SESSION['step'][1]['var2']                = 'bar';
// step 2
$_SESSION['step'][2]['TestaufstellungID']   = 65;
$_SESSION['step'][2]['var4']                = 100;
$_SESSION['step'][2]['var5']                = 256.04;
?>

When you send data, over AJAX, is not necesarry to convert it to JSON, because you can work with $_POST object. 通过AJAX发送数据时,不必将其转换为JSON,因为您可以使用$ _POST对象。 Meanwhile, response can give to you every $_SESSION['step'] values in JSON format. 同时,响应可以JSON格式给您每个$ _SESSION ['step']值。

<?php
header("Content-type:application/json")
// conditions goes here
if ( $conditions == true ) {
    echo json_encode($_SESSION['step']);
}
?>

This way, and considering is a "step by step" process, you can chose to save an json_encode() object updating in every step, or use session superglobal to save it only when process finish, considering all "step" array or just relevant values, users id in this case 这样,考虑到这是一个“逐步”的过程,您可以选择保存每个步骤中更新的json_encode()对象,或者使用会话超全局变量仅在过程完成时保存它,并考虑所有“步骤”数组或仅相关值,在这种情况下为用户ID

https://www.php.net/manual/es/reserved.variables.session.php https://www.php.net/manual/es/reserved.variables.session.php

https://www.php.net/manual/es/function.session-id.php https://www.php.net/manual/es/function.session-id.php

https://www.php.net/manual/es/function.json-encode.php https://www.php.net/manual/es/function.json-encode.php

I have been into programming since last 5 years, while that does not make me an expert. 我从最近5年开始从事编程工作,但那并不使我成为专家。 Find Correct Solution 寻找正确的解决方案

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

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