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>
?>
Related
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>
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'm stuck in a problem here that I tried all google answers and nothing did this work out. Specially because I prefer to do a pure JavaScript solution if possible... I have a menu, with a cart. This menu shows something like: Your cart (0)
where 0 is the number of items inside the cart. The items number are query from a SQL table 'cart', where I save all users products added to cart. So they don't lose the items on cart when the session closes. But I want to update this menu span everytime they add something inside the cart, without the need to refresh the page. The items are being added this way:
In the table where products are displayed I have:
<td id="add'.htmlspecialchars($row['id'], ENT_QUOTES, 'UTF-8').'"> <label><b><img src="/img/cart.gif" /></b></label> </td>
so I call javascript:addtocart passing 'id' of the product as parameter. This function does:
function addtocart(id)
{
document.getElementById('add'+id).innerHTML='<b>On your cart!</b>';
load('/index.php?addtocart&id='+id);
}
Ok, function load does:
function load(url) {
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( xmlhttp.responseText );
}
}
xmlhttp.open('GET', url, true);
xmlhttp.send();
}
OK, so we have my index.php receiving the GET with id of the product to add to cart, and I do on index.php:
if (isset($_GET['addtocart']) && isset($_GET['id']))
{
$id = mysql_real_escape_string($_GET['id']);
mysql_query("INSERT INTO cart VALUES('$id', '$userid')");
}
This is working very well, and if I refresh the page, in the menu I get "Your cart (1)"... But how to do this refresh automatically when the client clicks on the table? Possible with pure javascript function?
//EDIT for index.php content:
<?php
include("./includes/header.php");
include("./includes/db.php");
?>
<html>
<head>
<link rel="stylesheet" href="./css/style.css">
<title>MyShop</title>
<script type="text/javascript">
function load(url) {
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('cart').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', url, true);
xmlhttp.send();
}
function addtocart(id)
{
document.getElementById('add'+id).innerHTML='<b>On your cart!</b>';
load('/index.php?addtocart&id='+id);
}
</script>
</head>
<body id="home">
<?php include 'menu.php'; ?>
<div id="container">
<?php
if (isset($_GET['news']))
{
include 'news.php';
}
else if (isset($_GET['orders']))
{
include 'orders.php';
}
else if (isset($_GET['addtocart']) && isset($_GET['id']))
{
$id = mysql_real_escape_string($_GET['id']);
mysql_query("INSERT INTO cart VALUES('$id', '$userid')");
}
?>
</div>
</body>
</html>
From your index.php page, return the number of products inserted for the current user and then use the success handler of the ajax call to update the span.
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// here get the number of products inserted and display in span
document.getElementById('span_id').innerHTML = xmlhttp.responseText;
}
}
EDIT
Do not make the ajax call to the same page. Have the id sent to some other page, let's say abc.php. Then keep only the php related code inside your update_cart_ajax.php page.
So your addtocart() becomes:
function addtocart(id)
{
document.getElementById('add'+id).innerHTML='<b>On your cart!</b>';
load('/update_cart_ajax.php?addtocart&id='+id);
}
update_cart_ajax.php
<?php
include("./includes/db.php");
if (isset($_GET['addtocart']) && isset($_GET['id']))
{
$id = mysql_real_escape_string($_GET['id']);
mysql_query("INSERT INTO cart VALUES('$id', '$userid')");
}
else
{
echo 0;
exit;
}
// get the number of products added to the cart for the current user
$total_products_in_cart = <value returned from db>;
echo $total_products_in_cart;
exit;
I have a AJAX script which i was using previously and was able to retrieve data from viewCommentsJson.php as such[{"comments":"Greta"},{"comments":"John"}]. I was wondering if its able to decode the return value such that it display it properly ?
Thanks in advance
Greta John
Main.php
<a onclick="showUser('.$row['ID'].')" method = "POST" action= "viewCommentsJson.php">Show Comments</a>
<script>
function showUser(str) {
if (str=="") {
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("Post","viewCommentsJson.php?q="+str,true);
xmlhttp.send();
}
</script>
viewCommentsJson.php
$com = $_REQUEST["q"];
include 'connectDatabase.php';
//opening sql table
$selected = mysql_select_db("2000",$dbhandle)
or die("Could not select 2000");
$arr = array();
$data = mysql_query("SELECT comments FROM comment WHERE ID = '$com'");
$rows = array();
while($r = mysql_fetch_assoc($data)) {
$rows[] = $r;
}
print json_encode($rows);
Since you don't mind a jQuery solution, here is how it can be done
function showUser(str) {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
$.ajax({
type:'post',
url: 'viewCommentsJson.php',
data:{q:str},
success:function(data)
{
data = $.parseJSON(data);
var response;
$.each(data, function(index, value){
response += value+'<br />';
});
$('#txtHint').html(response);
}
});
}
You can refer $.ajax and $.parseJSON for more information.
Note: Your SELECT comments FROM comment WHERE ID = '$com' is prone to SQL injection. At the very least, you should sanitize all incoming data before using it in your query directly.
<a onclick="showUser('1')" href="#?">Show Comments</a>
<script>
function showUser(str) {
if (str=="") {
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) {
data = eval(xmlhttp.responseText);
for(i=0;i<data.length;i++){
document.getElementById("txtHint").innerHTML = document.getElementById("txtHint").innerHTML + data[i].comments;
}
}
}
xmlhttp.open("Post","viewCommentsJson.php?q="+str,true);
xmlhttp.send();
}
</script>
<div id="txtHint"></div>
First of all remove method and action from A tag and used above code now. Removed some typos
I use ajax on my html page to load data from MySql db w.o. reload and send email notification on some event, after selecting on html page - ajax calls script.php that made request to db and return result, it works perfect; and in same time I use function that shows and hides ajax loader image until query is executed, but it calls my php script twice so that each time it sends email twice
<script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.js"></script>
<script>
function showUser(str)
{
if (str=="")
{
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","../getuser.php?q="+str,true);
xmlhttp.send();
}
// ajax loader image
function getuser(str){
$.ajax({
url: "http://site.com/getuser.php?q="+str,
beforeSend: function (XMLHttpRequest)
{
$("#loading").show();
}
})
.done(function ( data ) {
$("#txtHint").html(data);
$("#loading").hide();
});
}
$(document).ready(function(){
$("select[name='users']").change(function () {
getuser($("option:selected", this).val());
});
});
</script>
how to improve this code to call php script just one time?
HTML
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a user:</option>
<option value="1">User1</option>
<option value="2">User2</option>
</select>
</form>
<div style="display:none" id="loading">
<p><img src="../loader.gif" /></p>
</div>
<br>
<div id="txtHint"><b>User info will be listed here.</b></div>
remove onchange event from:
<select name="users" onchange="showUser(this.value)">
What are you using showUser for? This seems to be enough;
function getuser(str) {
$.ajax({
url: "/getuser.php?q=" + str, // No need to include the domain here
beforeSend: function (jqXHR) {
$("#loading").show();
}
}).done(function(data) {
$("#txtHint").html(data);
$("#loading").hide();
});
}
$(document).ready(function() {
$("select[name='users']").change(function() {
getuser($(this).val());
});
});