0

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."

";

Danny
  • 43
  • 7
  • php runs on the server, javascript runs on the client. php cannot issue an ajax request, it can only RESPOND to them. you can have php embed anything you want at page creation time, or have php respond to an ajax call, but you cannot use php to do an xmlhttprequest (aka ajax). – Marc B Jul 21 '16 at 20:01

1 Answers1

0

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.

Florian Humblot
  • 1,121
  • 11
  • 29
  • Do you have example code for that? JS is my weakness Thanks! – Danny Jul 22 '16 at 13:49
  • But then how would I use that var ('someid') in the SQL statement in the requested/external file? $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 = ".$someid." "; – Danny Jul 22 '16 at 20:12
  • Instead of requesting, make an Ajax call using the POST method. Pass it the argument user ID, and in the php file you'll have access to $_POST['user_id'] – Florian Humblot Jul 22 '16 at 20:17
  • Can you show me, because right now I'm super confused. I'm doing a GET and I didn't think you could get a file using POST. I don't see where the var would go. Here's the process: 1. XmlHttpRequest to GET external File on keyup, 2. External file runs query and returns results. The var needs to be used in that query. – Danny Jul 22 '16 at 20:19
  • Code has been added sir. – Danny Jul 22 '16 at 20:42
  • Don't think I did it right. I'm not getting anything back. Is there a way I can give back to you for helping me? Do you drink coffee or have a favorite restaurant? – Danny Jul 22 '16 at 22:36
  • Oh, and is suggest to get rid of `mysql_*` functions and going to mysqli or pdo, mysql functions have security issues – Florian Humblot Jul 23 '16 at 06:13
  • Alright, everything is working now! Thank you so much! Can I send you a gift? Is your email available somewhere? – Danny Jul 23 '16 at 19:41
  • You can mark the answer as complete, and I'll contact you if you really want :) – Florian Humblot Jul 23 '16 at 21:33
  • If you find a way to give me an email or something – Florian Humblot Jul 23 '16 at 21:33