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);
?>
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>
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>
Related
I have this JavaScript:
<script>
if (str == "") {
document.getElementById("txtHint1").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 (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint1").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "/npsmart/umts/action_plano/?q=" + query1, true);
xmlhttp.send();
}
</script>
And this JavaScript call a page called getuser.php.
This is the code of getuser.php:
<!DOCTYPE html>
<html>
<body>
<p id="dumb"></p>
<script>
document.getElementById("dumb").innerHTML = "WORK";
</script>
</body>
</html>
What I would like is only to change the paragraph content, called dumb, to WORK. But when I call the page and it loads, my paragraph content keep null.
It's like my Ajax Call Request don't execute the Script Tag.
EDIT:
I have already solved my problem with this simple but genious solution:
function showUser() {
if(query_num == 2){
if (str == "") {
document.getElementById("txtHint1").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 (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint1").innerHTML = this.responseText;
eval(document.getElementById("runscript").innerHTML);
}
};
xmlhttp.open("GET","/npsmart/umts/action_plano/?q="+55555,true);
xmlhttp.send();
}
And in my getuser.php file:
<script type="text/javascript" id="runscript">
document.getElementById("dumb").innerHTML = "WORK";
</script>
I just putted the : eval(document.getElementById("runscript").innerHTML); in my function and then in the php file I called this script using this:
<script type="text/javascript" id="runscript">
So thanks everybody =)
Hope this post can help other people.
JS is not executed automatically from a script embedded in the response.
Since getuser.php is a PHP script there's no need to use JS and have the browser set the paragraph content. Use PHP itself:
<!DOCTYPE html>
<html>
<body>
<p id="dumb"><?php echo 'WORK'; /* or anything else */ ?></p>
</body>
</html>
Otherwise you'll have to use JS eval on the returned AJAX response to have the browser run the JS returned from your script. But I recommend against this.
i was trying to build a application that demonstrate the use of ajax. as i am a newbie in ajax i couldnt able to find the error for my code. xmlhttp object is creating, rest of the things are not working,
the ready state is not changing to 1 or more than that, i have tried by printing all status values.
<html>
<head>
<title>Home</title>
<script type="text/JavaScript">
function process()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp.readyState==4 && xmlhttp.readyState==0)
{
food= document.getElementById("username").value;
xmlhttp.open("GET","food.php?food="+food,true);
xmlhttp.onreadystatechange=handleServerResponse();
xmlhttp.send();
}
else
{
setTimeout("process()",1000);
}
}
response function,
function handleServerResponse()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
xmlResponse=xmlhttp.ResponseXML;
xmlDocumentElement= xmlResponse.documentElement;
message=xmlDocumentElement.firstChild.data;
document.getElementById("status").innerHTML="message";
setTimeout("process()",1000);
}
}
</script>
</head>
<body >
<form method="post">
<fieldset><center><h2>Login</h2></center>
<label>Username</label>
<input type="text" id="username" value="" maxlength="20" />
<div id="status" ></div>
<input type="button" value=" Login " onClick="process()" />
</fieldset>
</form>
</body>
</html>
php code is below
<?php
echo "<?xml version='1.0' encoding='UTF-8' standalone='yes'?>";
echo "<response";
$food=$_GET['food'];
if($food=="ajith")
echo "Successs";
else
echo "Invalid";
echo "</response>";
?>
var is not optional, use it.
First var xmlhttp; is a local variable, so you would not be able to use it in the other method. Needs to be moved outside of the process function.
Your if check is is impossible
xmlhttp.readyState==4 && xmlhttp.readyState==0
How can something be 2 values at once?
xmlhttp.readyState==4 || xmlhttp.readyState==0
Next issue is the fact you are not assigning an event handler you are calling it
xmlhttp.onreadystatechange=handleServerResponse();
needs to be
xmlhttp.onreadystatechange=handleServerResponse;
There is no ResponseXML, there is responseXML
"message" is a string, not the variable you defined beforehand.
var xmlhttp;
function process () {
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp) {
var food= document.getElementById("username").value;
xmlhttp.open("GET","food.php?food="+food,true);
xmlhttp.onreadystatechange=handleServerResponse;
xmlhttp.send();
} else {
//alert("Can not make Ajax request");
}
}
function handleServerResponse () {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var xmlResponse=xmlhttp.responseXML;
var xmlDocumentElement= xmlResponse.documentElement;
var message=xmlDocumentElement.firstChild.data;
document.getElementById("status").innerHTML = message;
window.setTimeout(process,1000);
}
}
I've a multiple select on my code with the onchange function ajax call,when the value is passed through the ajax it gets data from database and plot the chart by highcharts script,my problem is javascript is not worrking on ajax call,please suggest anything best,thanks in advance
source.php
<script>
function something(str)
{
if (str=="")
{
document.getElementById("div1").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("div1").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","destination.php?q="+str,true);
xmlhttp.send();
} </script>
<body>
<select multiple="multiple" onchange="something(this.value);">
<option>value1</option>
......
<option>valuen</option></select>
<div id="div1"></div>
destination.php
on here (destination page) get data from the database using the requested value from ajax
<?php
include("config.php");
$var=$_REQUEST['str'];
$query=mysql_query("select * from table where column=$var");
while($row=mysql_fetch_array($query))
{
$value[]=$row['data'];
}
<script>
<!--- here my highcharts script for ploting graph by the above fetching value from database --!>
</script>
?>
This question already has answers here:
Can scripts be inserted with innerHTML?
(26 answers)
Closed 8 years ago.
Hi I am trying to insert a JavaScript code in my HTML document using the following AJAX-PHP code inside the function called exJS(), following is the content of the function exJS()
var xmlhttp;
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("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax.php", false);
xmlhttp.send();
This what ajax.php is
<?php
echo '<script language="javascript">
alert("Hello World");
var testVAR = "Hello World";
</script>';
?>
Now whenever I execute this function exJS() the alert doesn't work but when I view the source code using F12 and see the contents of the div#myDiv" I see that the entire script is embedded inside the div but still the JavaScript for some reason is not getting registered.
I even tried accessing the JavaScript variable testVAR, I see the variable in the source code when I hit F12 but when I try to access that variable I get an error, that no such variable is defined.
Please note that it is simple example so there is no error and that the PHP code is echoing just fine, all the contents are returned from the PHP code, when I view the code and see what are the content of the div element the entire PHP echo content is present there but still not executing.
Also if I open the ajax.php file directly it works fine, I mean I get the alert message, but the same thing doesn't happen when I execute the function jsEx() the JavaScript code gets inserted into myDiv but nothing happens, no alert.
BTW jQuery has a specific AJAX function to get a script: http://api.jquery.com/jquery.getscript/
If you want to avoid jQuery a workaround would be to make it so you echo an iframe and from that Iframe you link to the PHP generating the actual Javascript.
E.G. a sample ajax.php
if( isset($_GET['getscript']) ){
header('Content-type: application/javascript'); #or header('Content-type: text/javascript');
echo 'alert("The script is working.")';
exit;
}
echo '<iframe src="ajax.php?getscript=1" frameborder="0"/>';
?>
try this:
tested in my WAMP (win 7, php 5.4) & works fine in IE11,Chrome,Safari,FireFox and Opera (I don't have any other ;-) )
index.html:
<head>
<title>Testing DYNAMIC JS</title>
<script type="text/javascript">
function exJS(){
var xmlhttp;
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)
{
var script = document.createElement('script');
script.onload = function() {
// alert("Script loaded and ready");
};
script.setAttribute("type","text/javascript");
script.text = xmlhttp.responseText;
document.getElementsByTagName('head')[0].appendChild(script);
}
}
xmlhttp.open("GET","ajax.php", false);
xmlhttp.send();
}
</script>
</head>
<body onload="exJS();">
</body>
</html>
in ajax.php try:
<?php
echo 'alert("Hello World"); var testVAR = "Hello World";';
?>
if you want to run script from within a div:
use:
javaScript:
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var MyDiv=document.getElementById("myDiv");
var arr = MyDiv.getElementsByTagName('script');
for (var n = 0; n < arr.length; n++)
eval(arr[n].innerHTML);
}
and php:
<?php
echo '<script language="javascript">
alert("Hello World");
var testVAR = "Hello World";
</script>';
?>
hope it'll help you.
I am trying to get the javascript function in ajax call. My code works fine and returning back my javascript code but there is a problem in my received javascript function. Here is my code for Ajax..
function media_type(id)
{
var xmlhttp;
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)
{
eval(document.getElementById("asad").innerHTML=xmlhttp.responseText);
}
}
xmlhttp.open("GET","video/media_type.php?cat_id="+id,true);
xmlhttp.send();
}
And her is the code where i am returning a simple hello world alert box.
if($num_rows==0)
{
//echo("Sorry no record found.");
echo'<script type="text/javascript">
alert("hello World");
</script>';
}
I am receiving the code back exactly but code is not executing. Please tell me how i can fix this issue. Thanks in advance.
Can I ask why you need to return JavaScript from the server? How about you return a simple response (string, boolean, number) from the server, and execute something that already lives on the client based on the return value? Much safer and easier. It may not be the solution you are looking for, but your js-fu will be much stronger for it.
Just return the JS that you want to execute (alert("hello World");) and make an eval. Remove <script type="text/javascript"> and </script>
eval(xmlhttp.responseText);
will be:
eval('alert("hello World")');
i will try with this
if($num_rows==0)
{
//echo("Sorry no record found.");
echo'<html><script type="text/javascript">
alert("hello World");
</script>
</html>';
}
i think this line is creating problem
eval(document.getElementById("asad").innerHTML=xmlhttp.responseText)
that is
eval(document.getElementById("asad").innerHTML='<script>alert("Hi");</script>';)
getting converted to
eval(document.getElementById("asad").innerHTML='< script > alert("Hi");</script>';)
I had this issue the other day...
you have to set your header in the php page to Content-Type: text/javascript; charset=utf-8
Here is the Entire Code to make this work
For your php file
<?php
header("Content-Type: text/javascript; charset=utf-8");
echo'<script type="text/javascript">
alert("hello World");
</script>
';?>
and here is the Javascript
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" type="text/javascript"></script>
<script>
$.ajax({
type:'POST',
url:'toget.php',
success:function(d)
{
$(document).append(d);
}
});
</script>
//try using this
<?php
if($num_rows==0)
{
//echo("Sorry no record found.");
?>
<script type="text/javascript">
alert("hello World");
</script>
<?php
}
?>