简体   繁体   English

如何将php变量传递给ajax成功函数并分配给JavaScript变量

[英]how to pass php variable in to ajax success function and assign in to JavaScript variable

I want to access back end php variable in front end ajax success call back function.how do do it?我想在前端ajax成功回调函数中访问后端php变量。怎么做? my code php code我的代码 php 代码

    if($_POST["action"] == 'check_ot_count')
      { 

        $totaltime = 0;

        $ot_hours = $_POST["test"];
        $month = $_POST["month"];

         foreach ($ot_hours as $time_val) {
            $totaltime +=explode_time($time_val); // this fucntion will convert all hh:mm to seconds
         }
          $tablecount = second_to_hhmm($totaltime);
          $approval = GetApprovedOt($connect,$_SESSION["dept_Id"],$month);

          if($approval == ':00'){

            echo 'Before the time allocate you need get approval department group OT request';
          }else{
          if($approval < $tablecount){

          list ($hour1, $min1) = explode(':', $tablecount);
          list ($hour2, $min2) = explode(':', $approval);

         $sumHour = sprintf('%02d', $hour1 - $hour2);
         $sumMin = sprintf('%02d', $min1 - $min2);

         $temp = $sumHour.':'.$sumMin;
         //$sumSec = sprintf('%02d', $sec1 - $sec2);
            echo 'You Need to get Sub OT Approval '.$temp.' Hours to Time allocate in the department';
          }
          elseif($approval > $tablecount){
          list ($hour1, $min1) = explode(':', $approval);
          list ($hour2, $min2) = explode(':', $tablecount);

         $sumHour = sprintf('%02d', $hour1 - $hour2);
         $sumMin = sprintf('%02d', $min1 - $min2);
         $temp01 = $sumHour.':'.$sumMin;

            echo 'You can allocate time period succefully.Anyway '.$temp01.' Hours are still avilable to allocate' ;
          }elseif($approval == $tablecount){

            echo 'You are fully allocate the approval OT hours count';
          }
        }
      }
}

java script code java脚本代码

$.ajax({
      url: 'ot_divide_action.php',
      type: 'POST',
      data: { action:'check_ot_count', test:test,month:month},
      success:function(data)
      {
      /**/
   if(data == 'Before the time allocate you need get approval department group OT request')
   {
    setTimeout(function () { 
   swal({
     title: "OverTime Status!",
     text: "Before the time allocate you need get approval department group OT request",
     type: "warning",
     confirmButtonText: "OK"
    },
 function(isConfirm){
    if (isConfirm) {
       //window.location.href = "index.php";
      }
   }); }, 1);
    }/*no month procces if end*/
  else if (data == 'You are fully allocate the approval OT hours count'){
  setTimeout(function () { 
   swal({
     title: "OverTime Status!",
     text: "You are fully allocate the approval OT hours count",
     type: "success",
     confirmButtonText: "OK"
    },
 function(isConfirm){
    if (isConfirm) {
       //window.location.href = "index.php";
      }
   }); }, 1);
    }
 else if (data == "You Need to get Sub OT Approval" + <?php echo $temp; ?> + "Hours to Time allocate in the department"){
  var temp = <?php echo $temp; ?>;
  setTimeout(function () { 
   swal({
     title: "OverTime Status!",
     text: "You Need to get Sub OT Approval "+ temp + "Hours to Time allocate in the department",
     type: "info",
     confirmButtonText: "OK"
    },
 function(isConfirm){
    if (isConfirm) {
       //window.location.href = "index.php";
      }
   }); }, 1);
    }
  else if (data == 'You can allocate time period succefully.Anyway '.$temp01.' Hours are still avilable to allocate'){
    var temp01 = 0;
  setTimeout(function () { 
   swal({
     title: "OverTime Status!",
     text: "You can allocate time period succefully.Anyway "+ temp01 +" Hours are still avilable to allocate",
     type: "info",
     confirmButtonText: "OK"
    },
 function(isConfirm){
    if (isConfirm) {
       //window.location.href = "index.php";
      }
   }); }, 1);
    }
   }
  });

I want to get 4 type of alert box in different condition, first two alert box is working but last 2 alert does'nt work because of the php variable correctly not coming to the ajax success call back function, How I can solve the above issue?我想在不同条件下获得 4 种类型的警报框,前两个警报框正在工作,但最后 2 个警报不起作用,因为 php 变量没有正确地进入 ajax 成功回调函数,我如何解决上述问题?

You're declaring a variable $temp within the POST request.您在 POST 请求中声明了一个变量$temp So it's basically to late to inject this variable - this needs to be done on the initial GET request where the resource (index.html containing your JS for example) is build.因此,注入此变量基本上为时已晚 - 这需要在构建资源(例如包含您的 JS 的 index.html)的初始 GET 请求上完成。

You have two options here.您在这里有两个选择。

  1. Inject a token while serving the content.在提供内容时注入令牌。 Since you should not use inline JS, you could include a hidden field containing your token / date to check in a later POST request.由于您不应该使用内联 JS,您可以包含一个包含您的令牌/日期的隐藏字段,以便在以后的 POST 请求中进行检查。
  2. Get your token / date in advance to the POST request with a separate AJAX call.使用单独的 AJAX 调用提前获取您的令牌/日期到 POST 请求。

General: You should not use plain text responses - especially if you are processing them with JS.一般:您不应该使用纯文本响应 - 特别是如果您使用 JS 处理它们。 Better encode your response as JSON, where you are able to give a structured response.更好地将您的响应编码为 JSON,您可以在其中提供结构化响应。 See json_encode ( https://www.geeksforgeeks.org/php-json_encode-function/ ).请参阅 json_encode ( https://www.geeksforgeeks.org/php-json_encode-function/ )。

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

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