douan6931
2016-07-21 20:00
浏览 59
已采纳

将当前页面的php变量传递给XMLHttpRequest2(即$ user_id)

I am trying to figure out if a current page's php $var can be passed through to the XMLHttpRequest2. The file that is being called is located outside of the views(where the current php page is located) folder in the /assets/js directory. I am using CodeIgniter as well. Trying to pass the $user_id along to use in a SQL query in side the XMLHttpRequest2 requested file.

publication_call.php (current file)

  <form>
    <input type="hidden" id="someid" value="<?= $idz ?>"/>
    <?php
      echo form_label('Validation: (Enter Publication keywords, Matches will appear in Dropdown > )');
      echo form_label('Matching<br>Publications:');
    ?>
    <select name="matched_pub" id="matched_pub"></select>
  </form>

<script>
  jQuery(function($){
    //still want to bind the change event
    $('#matched_pub').bind('change', function(){
        $('#title').val($('#matched_pub option:selected').text());
    });
    $('#validation').keyup(function() {
        showKeywords( $('#validation').val() );
        document.getElementById('matched_pub').style.display='block';
    });
  });
</script>


  <script>
    function showKeywords(str)
    {

        if (document.getElementById("matched_pub")) {

            if (str.length==0)
            {
                document.getElementById("matched_pub").innerHTML="";
                document.getElementById("matched_pub").innerHTML=xmlhttp2.responseText;
                return;
            }
            if (window.XMLHttpRequest)
            {// code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp2=new XMLHttpRequest();
            }
            else
            {// code for IE6, IE5
                xmlhttp2=new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp2.onreadystatechange=function()
            {
                if (xmlhttp2.readyState==4 && xmlhttp2.status==200)
                {
                    document.getElementById("matched_pub").innerHTML=xmlhttp2.responseText;
                }
            }
            xmlhttp2.open("GET","/assets/keywordsearch.php?b="+str,true);
            xmlhttp2.send();

        }

    }
</script>

searchwords.php (requested/external file)

  <?php

$user   = 'root';
$pass   = 'root';
$db     = 'hey_there';
$host   = 'localhost';

$conn = mysql_connect($host, $user, $pass);
$db_selected = mysql_select_db($db, $conn);

//trying to display special chars
mysql_query("set names 'utf8'");
if(!$db_selected) {
    echo 'broke';
}
//echo 'db connected';
$q = $_GET["b"];
//explode and parse $q into all the fragments separated by spaces and do full text search +word1 +word2 +word3, this will ignore HTML tags as it ignores word order, will also solve the middle initial problem [db setup is not compatible with full text search, but can do likes per word, less efficient, but how it must be done]
$queryWords = explode(' ', $q);

//for services query, explode the query into words and search for each separately
$query = "SELECT DISTINCT(pub_title)
    FROM teacher_publications
    JOIN users ON teacher_publications.user_id = users.id
    WHERE keywords IS NOT NULL 
    AND pub_title IS NOT NULL
    AND teacher_publications.user_id = 103 <-- $var will go here
";
$queryServicesLoop = '';
$queryServicesEnd = ' ORDER BY pub_title ASC';

//loop through all words in string
foreach($queryWords as $queryWord) {
    $queryServicesLoop .= " AND (keywords LIKE '%{$queryWord}%')";
}
$queryServices = $queryServices.$queryServicesLoop;
$queryServices = $queryServices.$queryServicesEnd;

$resultServices = mysql_query($queryServices);
$services ='';

if(mysql_num_rows($resultServices) > 0){    
    while($rowServices = mysql_fetch_assoc($resultServices)) {
        $services .= '<option  value="' . $rowServices['pub_title'] . '">' . $rowServices['pub_title'] . '</option>';
    }
}



if( mysql_num_rows($resultServices) == 0 )
{
    echo '<option  value="">Your search failed to find any matching results.</option>';
}
else
{
    echo '' . $services . '';
}

/* ============================== Edited Code ============================== */

publication_call.php (current file)

<input type="hidden" id="someid" value="<?= $user_id ?>"/>

<script>
    function showKeywords(str)
    {

        if (document.getElementById("matched_pub")) {


            if (str.length==0)
            {
                document.getElementById("someid");
                document.getElementById("matched_pub").innerHTML="";
                document.getElementById("matched_pub").innerHTML=xmlhttp2.responseText;
                return;
            }
            if (window.XMLHttpRequest)
            {// code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp2=new XMLHttpRequest();
            }
            else
            {// code for IE6, IE5
                xmlhttp2=new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp2.onreadystatechange=function()
            {
                if (xmlhttp2.readyState==4 && xmlhttp2.status==200)
                {
                    document.getElementById("matched_pub").innerHTML=xmlhttp2.responseText;
                }
            }
            xmlhttp2.open("GET","/assets/keywordsearch.php?b="+str+"&user_id="+document.getElementById('someid'), true);
            // xmlhttp2.open("GET","/assets/keywordsearch.php?b="+str,true);
            xmlhttp2.send();

        }

    }
</script>

searchwords.php (requested/external file)

 $usr = $_GET["user_id"];

 $query = "SELECT DISTINCT(pub_title)
           FROM teacher_publications
           JOIN users ON teacher_publications.user_id = users.id
           WHERE keywords IS NOT NULL 
           AND pub_title IS NOT NULL
           AND teacher_publications.user_id = ".$usr."

";

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • drq1257 2016-07-22 07:51
    已采纳

    You can put $user_id inside of a hidden input field, and using Javascript, read the value of it to use in your Ajax request

    You can do it like this:

    <input type="hidden" id="someid" value="<?= $user_id ?>

    And then after you've done that, you can get the value by doing this:

    document.getElementById('someid'); using plain Javascript or $('#someid').value(); if you use jquery

    This will get you the user ID value which you can then use in the request.

    Like so:

    xmlhttp2.open("GET","/assets/keywordsearch.php?b="+str+"&user_id="+document.getElementById('someid').value, true); Replace your current xmlhttp2.open with the one above Now you can access the value of user ID in $_GET['user_id'] in the requested file.

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题