1

I have 2 php files, the first is BAConsult.php which is the main file, and the other is BAConsultRecordsAJAX.php. This line of code is in BAConsultRecordsAJAX.php:

while($row = mysqli_fetch_array($consultresult)) {
    $skincareinuse=explode(",",$row['skincarecurrentlyinuse']);
}

In BAConsult.php I have this:

echo $skincareinuse;

Is it possible to bring over the $skincareinuse value from the BAConsultRecordsAJAX.php page, to the $skincareinuse variable on the BAConsult.php page?

Such that, lets say whenever I do a click on the table row, the value of $skincareinuse will be updated and shown by the echo, without the page refreshing?

[EDITED TO SHOW MORE OF MY CODES]

This is BAConsult.php file, where my main code is.

<?php echo $jsonvariable; ?>//Lets say i want to store the JSON data into this variable

function showconsultationdata(str) { //face e.g and checkboxes for that date selected.

    if (str == "") {
        document.getElementById("txtHint2").innerHTML = "";
        return;
    } else { 
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
         xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("txtHint2").innerHTML = xmlhttp.responseText;                                       
                var a = JSON.parse($(xmlhttp.responseText).filter('#arrayoutput').html());
                $("textarea#skinconditionremarks").val(a.skinconditionremarks);
                $("textarea#skincareremarks").val(a.skincareremarks);  

                var test = a.skincareinuse;
                //I want to store this ^^ into the php variable of this page.
            }           
        };       
        xmlhttp.open("GET","BAConsultRecordsAJAX.php?q="+str,true);        
        xmlhttp.send();        
    }  
}

This is my BAConsultRecordsAJAX.php page.

$q = $_GET['q']; //get dateconsulted value

$consult="SELECT * FROM Counsel where nric='$_SESSION[nric]' and dateconsulted='$q'";
$consultresult = mysqli_query($dbconn,$consult);

while($row = mysqli_fetch_array($consultresult)) {
    $skincareinuse=explode(",",$row['skincarecurrentlyinuse']);
    $skincondition=explode(",",$row['skincondition']);
    $queryResult[] = $row['skincareremarks'];
    $queryResult[] = $row['skinconditionremarks'];
}
$skincareremarks = $queryResult[0];
$skinconditionremarks = $queryResult[1];
echo "<div id='arrayoutput'>";
echo json_encode(array('skincareremarks'=>$skincareremarks
                       'skinconditionremarks'=>$skinconditionremarks
                       'skincareinuse'=>$skincareinuse,
                       'skincondition'=>$skincondition));
echo "</div>";
1
  • Once your page has loaded the php part is over so you can't bring a value from your ajax page to the current page and assign it to any php variable on the current page. You can only update the current document view with returned data/html from the ajax page and/or assign/update persisting values (cookies or sessions). Commented Jul 10, 2016 at 4:54

3 Answers 3

2

You don't actually want to transfer the variable from BAConsultRecordsAJAX.php to BAConsult.php, but to BAConsult.js (I suppose that's the name of your JS file).

In reality, even that's what you wanted to do, it's impossible, because your main PHP is processed before the page even loads. What you can do, however, is overwrite the rendered value with a new one with the use of JavaScript.

To do that, send an AJAX request to BAConsultRecordsAJAX.php requesting the variable's value as shown below:

In JavaScript:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {

// Check if the AJAX request was successful
if (xhttp.readyState === 4 && xhttp.status === 200) {
    var td = document.getElementById("your table td value's id");
    var td.innerHTML = xhttp.responseText; // gets the value echoed in the PHP file
}
xhttp.open("POST", "BAConsultRecordsAJAX.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(""); // You don't need to send anything to the PHP file

In PHP:

<?php
     echo $skincareinuse;
?>

[EDIT]:

If you are using inline JavaScript use the following code:

<script type = "application/javascript">
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {

    // Check if the AJAX request was successful
    if (xhttp.readyState === 4 && xhttp.status === 200) {
        var td = document.getElementById("your table td value's id");
        td.innerHTML = xhttp.responseText; // gets the value echoed in the PHP file
}
    xhttp.open("POST", "BAConsultRecordsAJAX.php", true);
    xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhttp.send(""); // You don't need to send anything to the PHP file
</script>

[EDIT 2]:

To pass a JSON object to PHP file via an AJAX request you have to make it a string. That requires the following code:

var JSONstring = JSON.stringify(yourJSONobject);

Then you can pass it in your PHP file with the AJAX request by putting it inside send() as shown:

xhttp.send("json_object=" + JSONstring);

Then in PHP, in order to use it, you have to decode it:

<?php
    $json_object = json_decode($_POST["json_object"]);
    // Now it's ready to use
?>

[About the code]:

Notes about the first file:

  1. First of all, you have put your plain JavaScript code inside a PHP file and therefore it will not work. You have to wrap it in <script type = "application/javascript></script>

  2. I don't have a clue what you are trying to do here:

Code:

var a = JSON.parse($(xmlhttp.responseText).filter('#arrayoutput').html());
  • It seems like you are trying to filter out and parse the innerHTML of #arrayoutput.
  • If the response is a JSON string, not HTML, so you absolutely can't do that. The logic of this above line is flawed.

How I would write your code:

function showconsultationdata(str) {
    var xmlhttp;
    if (!str) {
        $("#txtHint2").empty();
    } else {
        xmlhttp = new XMLHttpRequest();
        // Providing support for a 15-year-old browser in 2016 is unnecessary

        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                $("#txtHint2").html(xmlhttp.responseText);                       
                var a = JSON.parse(xmlhttp.responseText);
                $("textarea#skinconditionremarks").val(a.skinconditionremarks);
                $("textarea#skincareremarks").val(a.skincareremarks);

                var test = a.skincareinuse; // The variable you want
                // Its saved in "text" and can use something like:
                // $("#element").html(test); to have it replace your current text
            }
        };
        xmlhttp.open("GET","BAConsultRecordsAJAX.php?q="+str,true);
        xmlhttp.send();        
    }
}

Notes about the second file:

  1. I don't know if the query works for you, but it probably shouldn't, because:
    • $_SESSION is an associative array and you pass nric, whereas it should be "nric".
    • As $_SESSION is an array, the proper method to insert its value to your query is: {$_SESSION["nric"]}.
  2. To ensure that you don't become the victim of an SQL Injection, use parameterised queries or at least sanitise somehow the received data, because GET is relatively easy to hack. Check the improved code later on how to do it.

How I would write your code:

$q = $_GET['q']; //get dateconsulted value

$dbconn = mysqli_connect("localhost", "root", "") or die("Error!");
mysqli_select_db($dbconn, "database") or die("Error!");

$consult = "SELECT * FROM Counsel where nric='{$_SESSION["nric"]}' and dateconsulted = ?";

if ($stmt = mysqli_prepare($dbconn, $consult)) { // By using a prepared statement
    mysqli_stmt_bind_param($stmt, "s", $q);      // you eliminate the chances to have
    if (mysqli_stmt_execute($stmt)) {            // an SQL Injection break your database
        $consultresult = mysqli_stmt_get_result($stmt);            
        if (mysqli_num_rows($consultresult) > 0) {
            while ($row = mysqli_fetch_array($consultresult)) {
                $skincareinuse = explode(",",$row['skincarecurrentlyinuse']);
                $skincondition = explode(",",$row['skincondition']);
                $queryResult[] = $row['skincareremarks'];
                $queryResult[] = $row['skinconditionremarks'];
            }
            $skincareremarks = $queryResult[0];
            $skinconditionremarks = $queryResult[1];
            $array = array('skincareremarks'=>$skincareremarks
                           'skinconditionremarks'=>$skinconditionremarks
                           'skincareinuse'=>$skincareinuse,
                           'skincondition'=>$skincondition);
            echo "<div id='arrayoutput'>";
            echo json_encode($array);
            echo "</div>";
            mysqli_stmt_close($stmt);
            mysqli_close($dbconn);
            exit;
        }
    }
}
Sign up to request clarification or add additional context in comments.

10 Comments

I actually want to transfer it to BAConsult.php file, its not a js file. Its a php file but also contains javascripts. Is it possible to run 2 xhttp.open at once? for example, xhttp.open("POST", "BAConsultRecordsAJAX.php", true); xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); and xmlhttp.open("GET","BAConsultRecordsAJAX.php?q="+str,true);
If you use inline JavaScript in your main PHP (not an a external file) just wrap the JavaScript code I gave you in <script></script>. Regarding your question, no. You can't execute two AJAX requests at once. The second one will wait for the first one to finish and then it will start, but in your case there is no reason to use two AJAX requests.
Hmm, i didnt post my full code here, but actually, when im generating the table out, I'm already using a AJAX script however it looks like i cant do two xhttp.open at once.. But thanks man, do you know how to go about using JSON parsed value in a javascript and storing into a php variable instead?
Do my xhttp.open have to be a 'POST'? Sorry im pretty new to using AJAX. Because now my $json_object is always undefined. My current script does a xhttp.open with a 'GET'
Not necessarily. I just use POST, because it's more robust and can transfer more data. I use GET only when I want to have a link like this: www.example.com/?ref=123. Your $json_object being undefined has nothing to do with the method the request was sent, unless the object was bigger than GET can handle.
|
0

Obviously you may change the values to suit your requirements, you must have jquery installed, the time value could be anything you want

$.ajaxSetup({ cache: false }); 
setInterval(function() { 

var url = "pagethatrequiresrefreshing.php";
$('#divtorefresh').load(url);
 }, 4000); 

Comments

0

Using include will most likely work. From the docs:

When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward.

BAConsultRecordsAJAX.php

while($row = mysqli_fetch_array($consultresult)) {
    $skincareinuse[] = explode(",",$row['skincarecurrentlyinuse']);
}

include "BAConsult.php";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.