Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

ok I have edited this to another couple of questions I've asked on a similar issue, but I really am in a rush so thought I'd start a new one, sorry if it bothers anyone.

first I have a php script on test.php on the apache server

<?php
//create connection
$con = mysqli_connect("localhost", "user", "password", "dbname");

//check connection
if (mysqli_connect_errno()){
   echo "failed to connect to MySQL: " . mysqli_connect_error();
   }
$grab = mysqli_query($con, "SELECT * FROM table");
$row = mysqli_fetch_array($grab);
$name = $row["name"];
$color = $row["color"];
$price = $row["price"];
$n1 = $name[0];
$c1 = $color[0];
$p1 = $price[0];

?>

Then I've got this ajax script set to fire onload of page a webpage written in html. so the load() function is onload of the page in the body tag. This script is in the head.

function load(){
   var xmlhttp = new XMLHttpRequest();
   xmlhttp.open("GET", "test.php", true);
   xmlhttp.send();
   xmlhttp.onreadystatecahnge = function(){
      if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
         document.getElementById("itemNameLink1").innerHTML = "<?php echo $n1;?>;
         }
      }
   }

ok so what I want is the $n1 variable in the php script to be used in the javascript ajax code. Where the script is, but I'm not sure where or how to make use of the variable, I've tried a few things. All that happens right now is the innerHTML of itemNameLink1 just disappears.

I'm quite new so any advise would be appreciated, thanks.

share|improve this question
    
Since you're using (or claim to be using) jQuery, ditch all the manual XMLHttpRequest crap. If you're not using jQuery then fix the tags. –  user2864740 23 hours ago

4 Answers 4

up vote 1 down vote accepted

The response (this is what you echo in php) returned from request you can get by responseText attribute of XMLHttpRequest object. So first your JS code should be:

function load(){
   var xmlhttp = new XMLHttpRequest();
   xmlhttp.open("GET", "test.php", true);
   xmlhttp.send();
   xmlhttp.onreadystatecahnge = function(){
      if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
         document.getElementById("itemNameLink1").innerHTML = xmlhttp.responseText;
         }
      }
   }

now in php echo $n1 variable:

....
$grab = mysqli_query($con, "SELECT * FROM table");
$row = mysqli_fetch_array($grab);
$name = $row["name"];
$color = $row["color"];
$price = $row["price"];
$n1 = $name[0];
$c1 = $color[0];
$p1 = $price[0];

// echo it to be returned to the request
echo $n1;

Update to use JSON for multiple variables

so if we do this:

$name = $row["name"];
$color = $row["color"];
$price = $row["price"];

$response = array
(
    'name'  => $name,
    'color' => $color,
    'price' => $price
);

echo json_encode($response);

Then in javascript we can parse it again to have data object containing 3 variables.

var data = JSON.parse(xmlhttp.responseText);
//for debugging you can log it to console to see the result
console.log(data);
document.getElementById("itemNameLink1").innerHTML = data.name; // or xmlhttp.responseText to see the response as text

Fetching all the rows:

$row = mysqli_fetch_array($grab); // this will fetch the data only once

you need to cycle through the result-set got from database: also better for performance to use assoc instead of array

$names = $color = $price =  array();

while($row = mysqli_fetch_assoc($grab))
{
    $names[] = $row['name'];
    $color[] = $row['color'];
    $price[] = $row['price'];
}

$response = array
(
    'names' => $names,
    'color' => $color,
    'price' => $price
);
share|improve this answer
    
this actually worked, I'm gonna have to find another way as I want to work with multiple variables. do have one problem though. for some reason I only get the first letter of the variable string not the whole string. is there some problem with my php coding. –  user3879560 13 hours ago
    
yes problem is: $name = $row["name"]; is name and $n1 = $name[0]; is the first character of that name, so you can just echo $name –  George Garchagudashvili 9 hours ago
    
Also I've updated answer to use multiple variables –  George Garchagudashvili 9 hours ago
    
surely $row["name"] is the array of names, or how would iget the array of names from the Database. –  user3879560 9 hours ago
    
also added some tips and workarounds –  George Garchagudashvili 9 hours ago

I'm pretty sure you should use json_encode for this. It returns the JSON representation of a php value.

In your php

$n1 = array();
echo json_encode($n1);

In your javascript

function (data) {
   if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
         document.getElementById("itemNameLink1").innerHTML = "+ data.n1 +";
         }
      }
}

Can't do more, I'm on my phone, this was a pain. Some documentation here.

share|improve this answer

You can dynamically generate a javascript document with php that contains server side variables declared as javascript variables, and then link this in the head of your document, and then include this into your document head whenever server side variables are needed. This will also allow you to dynamically update the variable values upon page generation, so for example if you had a nonce or something that needs to change on each page load, the correct value can be passed upon each page load. to do this, you need to do a few things. First, create a php script and declare the correct headers for it to be interpreted as a script:

jsVars.php:

<?php
//declare javascript doc type
header("Content-type: text/javascript; charset=utf-8");
//tell the request not to cache this file so updated variables will not be incorrect if they change
header('Cache-Control: no-cache, no-store, must-revalidate'); // HTTP 1.1.
header('Pragma: no-cache'); // HTTP 1.0.
header('Expires: 0'); // Proxies.

//create the javascript object
?>

var account = {
    email: <?= $n1; ?>,
    //if you need other account information, you can also add those into the object here
    username: <?= /*some username variable here for example */ ?>
}

You can repeat this for any other information you need to pass to javascript on page load, and then reference your data using the namespaced javascript object (using object namespacing will prevent collisions with other script variables that may not have been anticipated.) wherever it is needed as follows:

<script type="text/javascript>
//put this wherever you need to reference the email in your javascript, or reference it directly with account.email
var email = account.email;
</script>

You can also put a conditional statement into the head of your document so it will only load on pages where it is needed (or if any permission checks or other criteria pass as well). If you load this before your other scripting files, it will be available in all of them, provided you are using it in a higher scope than your request.

<head>

<?php
    //set the $require_user_info to true before page render when you require this info in your javascript so it only loads on pages where it is needed.
    if($require_user_info == TRUE): ?>

    <script type="text/javascript" href="http://example.com/path-to-your-script/jsVars.php" />

    <?php endif; ?>

<script type="text/javascript" href="your-other-script-files-that-normally-load" />

</head>

You can also do this for any other scripts that have to load under specific criteria from the server.

share|improve this answer
    
You can use a similar approach to return an object from an ajax call if you do not want the data available until after the document loads, though you would want to JSON_ENCODE the response in that case. This will let you fetch additional scripts, variables, etc from the server through ajax that can be dynamically generated on the server based on the criteria passed through the original ajax call. –  mopsyd yesterday

You should define the PHP variable. And use that variable in your javascript:

<?php
    $n1 = "asd";
?>
<html>
<head></head>
<body>

    <div id="itemNameLink1"></div>

    <script>
        function load()
        {
            var xmlhttp = new XMLHttpRequest();                     
            xmlhttp.open('GET', '/test.php', true);
            xmlhttp.send(null);
            //Note you used `onreadystatecahnge` instead of `onreadystatechange` 
            xmlhttp.onreadystatechange = function() {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                    document.getElementById("itemNameLink1").innerHTML = '<?=$n1?>';
                }
            }
        }

        load();
    </script>
</body>
</html>
share|improve this answer
    
ok great thanks. –  user3879560 yesterday
    
how do I make sure the php is loaded before the load function. –  user3879560 yesterday
    
Just write it earlier in the file then the javascript. So in this example the variable is defined before the javascript gets executed. –  S.Pols yesterday
    
still not working, I could try the first way. what I did was move everything except the xmlhttp.onreadystatechange part to outside the load function(before), so var ml and xml open and xml send are loaded globally not as part of the load function but still the $n1 variable just doesn't come out at all. –  user3879560 yesterday
    
I think i see what is wrong. First you define $name which i think is a string. Then you try access that string as an array with $name[0]. Try the javascript code with static data e.g. $n1 = "This is a test", then you can see if the javascript works. If it do, then there is probably something wrong with your variable definition like a said here above. –  S.Pols yesterday

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.