dota220141003 2012-11-28 20:26
浏览 58

麻烦将JavaScript变量传递给PHP

The solution to my problem now seems very basic. Although I understood php runs server-side I didn't know that that the php ran on pageload even if the include was nestled in the ajax callback. Although I could display the query results by returning the php in the javascript value attribute, if I didn't include the reference to the php script I got unterminated string errors. What I now realize is that (I think) the include caused the php to run before the ajax was fired which is why the php squawked about an undefined index. Hard coding an ID into php would run fine since it didn't need anything from ajax to run the query. Removing the include in the callback caused an undefined literal error because, having nothing to reference, the php broke causing the parser to see .value = " which is literally unterminated. By removing the php include and returning the query results via JSON, everything works perfectly. Seemed my road block was being stuck at how I learned to return php data to html. Anyway, valuable and useful lesson learned...

The application is to pull log data, make modifications and save as a new or updated log file. The ajax sends an ID to the php script for the query to get the old info and populate each row cell. The second cell (act-col) is dynamically loaded based on the selection in the first cell (reg-col). To allow the user the ability to not only see the old info but also make changes, a second ajax call to get the right options is made. Anything already there is then emptied out and the new options are loaded. This also makes sure that the select box is defined since, initially, until something is put in the the reg-col cell, the act-col cell is basically an empty box. After that the rest of the cells are loaded with the old info, a new row is created and it loops through until all the info is displayed. Putting the add row function at the bottom of loop causes an extra row to be added but when the loop is completed I found that using javascript to delete it actually triggers all the math functions that occur as if the user creates a log from scratch. Probably not the best solution but prevents having to pull data from another table to populate those fields on the initial button click.

Now that I understand it better I can clearly see all the suggestions pointing me to this. Oh, well...not the first time and surely not the last that hind site has humbled (and humiliated) me. Here's what finally worked:

Here's the javascript/jquery:

$(function(){
            $.ajax({
                  type:'POST',
                   url: 'phpScripts/lastSession.php',
              dataType: 'json',
                  data: {'id': pt_id},
                 cache:false,
               success:function(data){

        for(var j=0; j<data.length; j++){            

                    var reg=data[j].region;
                    $(".reg-col:eq("+j+")").val(reg);

                        if ((reg)==="knee/hip"){  $(function(){ $.ajax({
                                    url: 'phpScripts/getKneeHip.php',
                                    dataType: 'json',
                                    cache:false,
                                    async:false,
                                    success: function (json) {
                                        $(".act-col:eq("+j+")").empty().end();
                                        $.each(json, function(i, value) {
                                            $('<option>').text(value).attr('value', value).appendTo( $(".act-col:eq("+j+")"));

                                        });
                                    }
                                });
                            });
                        }//end if

                        else if ((reg)=="shoulder"){  $(function() { $.ajax({
                                    url: 'phpScripts/getShoulder.php',
                                    dataType: 'json',
                                    cache:false,
                                    async:false,
                                    success: function (json) {
                                        $(".act-col:eq("+j+")").empty().end()
                                        $.each(json, function(i, value) {
                                            $('<option>').text(value).attr('value', value).appendTo( $(".act-col:eq("+j+")"));

                                        })
                                    }
                                });
                            });

                        }//end if

                                            $(".act-col:eq("+j+")").val(data[j].activity);
                                            $(".reps-col:eq("+j+")").val(data[j].reps);
                                                   $(".weight-col:eq("+j+")").val(data[j].weights);
                                                   $(".prps-col:eq("+j+")").val(data[j].purposes);
                                                   $(".time-col:eq("+j+")").val(data[j].time);
                                                   $(".type-col:eq("+j+")").val(data[j].type);

                        addRow('dataTable');

          }
        document.getElementsByName("chk[]")[j].checked=true;
        document.getElementById('deleteBtn').click();

Here's the php:

      $ID = $_POST['id'];
  $return = array(); 
  $query = mysql_query("SELECT * FROM history WHERE patient_id = '$ID' AND date_of_service IN (SELECT MAX(date_of_service) FROM history WHERE patient_id = $ID)"); 
while ($row = mysql_fetch_array($query,MYSQL_ASSOC)) { 
array_push($return,array('region'=>$row['region'],'activity'=>$row['exercise'], 'reps'=>$row['reps'], 'weights'=>$row['weight'], 'purposes'=>$row['purpose'], 'time'=>$row['time'], 'type'=>$row['type'])); 
 } 
  header('Content-type: application/json');
  echo(json_encode($return)); 
  • 写回答

1条回答 默认 最新

  • doumou5109 2012-11-28 20:36
    关注

    You're trying to execute a server-side script phpScripts/lastSession.php on the client, which obviously isn't going to work. I'm not entirely clear on what you want to have happen there, but it seems like you would want that script to execute as part of your ajax call.

    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?