简体   繁体   中英

Pass PHP variable to Javascript function whitin an AJAX request possible?

I try to pass a variable from Javascript (when choosing some option in a form) to a PHP file which calls a SQL query.

The SQL query (a string) should be handed over to a Javascript function and the function should be executed. Everything in one click. Is that somehow possible?

I tried that with a AJAX request but when I use this for my last step:

var javascriptstring;
      $.getJSON('getstring.php', function(data) {
        javascriptstring = data.value;
        });

I get the exception: Uncaught TypeError: Cannot set property 'innerHTML' of null

And it prints out "undefined"

.HTML

  <!DOCTYPE html>
<html>

<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type='text/javascript'>
     function showString(time) {
  if (time=="") {
    document.getElementById("txtHint").innerHTML="";
    return;
  }
  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("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
  xmlhttp.open("GET","getstring.php?q="+time,true);
  xmlhttp.send();

      var javascriptstring;
      $.getJSON('getstring.php', function(data) {
        javascriptstring = data.value;
        });
        document.write(javascriptstring);
}
</script>
</head>
<body>

    <form>
    <select name="somestring" onchange="showString(this.value)">
    <option value="">No string selected</option>
    <option value="1">String 1</option>
    </select>
    </form>
    <br>
    <div id="txtHint"><b>String will be listed here...</b></div>

</body>
</html>

PHP

<?php
$q = intval($_GET['q']);

$con = pg_connect("host=localhost port=5432 dbname=Twitter user=postgres password=****");
if (!$con) {
    die('Could not connect: ' . pg_errormessage($con));
}

$sql="SELECT * FROM tswholeworld WHERE createdat > (NOW() - INTERVAL '".$q."hour');";
$result = pg_query($con,$sql);

    $string = "";
while($row = pg_fetch_assoc($result)){
    $lat = $row['latitude'];
    $lon = $row['longitude'];
    $string .= "new google.maps.LatLng({$lat}, {$lon}), ";
}
echo '{"value": "'.$string.'"}';
pg_close($con);
?>

You forget to close script tag

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>// close include external javascript tag

Then you call your function inside script tag

<script>
function showString(time) {

-----Your code----

</script>

I guess this much amount of AJAX should suffice. Actually document.write replaces the whole DOM with the current. I have removed that and modified your function. Also I have removed the native Ajax code since you already have jQuery so no point in adding that big code. This small function will get the JSON data and print the value that the server is sending

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type='text/javascript'>
function showString(time) {
    if (time=="") {
      document.getElementById("txtHint").innerHTML="";
      return;
    } 
    $.getJSON('getstring.php?q='+time, function(data) {
      document.getElementById("txtHint").innerHTML = data.value;
    });
}
</script>

Edit: Please close the external script tags

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type='text/javascript'>
  //your script
</script>

Keep the Javascript function definition in head or before the select tag. like below -

<!DOCTYPE html>
 <html>
   <head>
     <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
     <script type='text/javascript'>
       function showString(time) {
         if (time=="") {
         document.getElementById("txtHint").innerHTML="";
         return;
       } 
       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("txtHint").innerHTML=xmlhttp.responseText;
         }
       }
       xmlhttp.open("GET","getstring.php?q="+time,true);
       xmlhttp.send();

       var javascriptstring;
       $.getJSON('getstring.php', function(data) {
        javascriptstring = data.value;
        });
       document.write(javascriptstring);

     }

     </script>

   </head>
   <body>
     <form>
       <select name="somestring" onchange="showString(this.value)">
         <option value="">No string selected</option>
         <option value="1">String 1</option>
       </select>
     </form>
   </body>
 </html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM