I have this little click counter. I would like to include each click in a mysql table. Can anybody help?
var count1 = 0;
function countClicks1() {
count1 = count1 + 1;
document.getElementById("p1").innerHTML = count1;
}
document.write('<p>');
document.write('Count');
document.write('</p>');
document.write('<p id="p1">0</p>');
Just in case anybody wants to see what I did:
var count1 = 0;
function countClicks1() {
count1 = count1 + 1;
document.getElementById("p1").innerHTML = count1;
}
function doAjax()
$.ajax({
type: "POST",
url: "phpfile.php",
data: "name=name&location=location",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
}
document.write('</p>');
document.write('Count');
document.write('</p>');
document.write('<p id="p1">0</p>');
This is phpfile.php which for testing purposes writes the data to a txt file
<?php
$name = $_POST['name'];
$location = $_POST['location'];
$myFile = "test.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $name);
fwrite($fh, $location);
fclose($fh);
?>
JavaScript, as defined in your question, can't directly work with MySql. This is because it isn't running on the same computer.
JavaScript runs on the client side (in the browser), and databases usually exist on the server side. You'll probably need to use an intermediate server-side language (like PHP, Java, .Net, or a server-side JavaScript stack like Node.js) to do the query.
Here's a tutorial on how to write some code that would bind PHP, JavaScript, and MySql together, with code running both in the browser, and on a server:
http://www.w3schools.com/php/php_ajax_database.asp
And here's the code from that page. It doesn't exactly match your scenario (it does a query, and doesn't store data in the DB), but it might help you start to understand the types of interactions you'll need in order to make this work.
In particular, pay attention to these bits of code from that article.
Bits of Javascript:
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
Bits of PHP code:
mysql_select_db("ajax_demo", $con);
$result = mysql_query($sql);
// ...
$row = mysql_fetch_array($result)
mysql_close($con);
Also, after you get a handle on how this sort of code works, I suggest you use the jQuery JavaScript library to do your AJAX calls. It is much cleaner and easier to deal with than the built-in AJAX support, and you won't have to write browser-specific code, as jQuery has cross-browser support built in. Here's the page for the jQuery AJAX API documentation.
The code from the article
HTML/Javascript code:
<html>
<head>
<script type="text/javascript">
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();
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Glenn Quagmire</option>
<option value="4">Joseph Swanson</option>
</select>
</form>
<br />
<div id="txtHint"><b>Person info will be listed here.</b></div>
</body>
</html>
PHP code:
<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'peter', 'abc123');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("ajax_demo", $con);
$sql="SELECT * FROM user WHERE id = '".$q."'";
$result = mysql_query($sql);
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "<td>" . $row['Hometown'] . "</td>";
echo "<td>" . $row['Job'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
You will have to submit this data to the server somehow. I'm assuming that you don't want to do a full page reload every time a user clicks a link, so you'll have to user XHR (AJAX). If you are not using jQuery (or some other JS library) you can read this tutorial on how to do the XHR request "by hand".
The other posters are correct you cannot connect to MySQL directly from javascript.
This is because JavaScript is at client side & mysql is server side.
So your best bet is to use ajax to call a handler as quoted above if you can let us know what language your project is in we can better help you ie php/java/.net
If you project is using php then the example from Merlyn is a good place to start, I would personally use jquery.ajax() to cut down you code and have a better chance of less cross browser issues.
http://api.jquery.com/jQuery.ajax/
Related
I found what looks like a decent introductory tutorial on AJAX using PHP and MYSQL and followed it to the letter - this is my first attempt at AJAX and PHP and I wish to run this in NetBeans but don't know how to get it running. How do I make this run in NetBeans? I have set the main file to ajax.html and attempted to run using the Green arrow but when the HTML page appears it does nothing when I enter valid data and click the "Query MySQL" button
Here us the ajax.html file
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
// Browser support code
function ajaxFunction(){
var ajaxRequest; // the variable that makes AJAX possible
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch(e){
// internet explorer browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
// something wrong in creating XMLHttpRequest
alert("Browser didn't create XMLHttpRequest");
return false;
}
}
}
// Now get the value from user and pass it to
// server script
var age = document.getElementById('age').value;
var wpm = document.getElementById('wpm').value;
var sex = document.getElementById('sex').value;
var queryString = "?age=" + age;
queryString += "&wpm=" + wpm +"&sex=" + sex;
ajaxRequest.open("GET", "ajax-example.php" + queryString, true);
ajaxRequest.send(null);
}
// -->
</script>
<form name='myForm'>
<br />
Max Age: <input type='text' id='age' /> <br />
<br />
Max WPM: <input type='text' id='wpm' />
<br />
<br />
Sex: <select id='sex'>
<option value="m">m</option>
<option value="f">f</option>
</select>
<input type='button' onClick='ajaxFunction()' value='Query MySQL' />
</form>
<div id='ajaxDiv'>Your result will be displayed here</div>
</body>
</html>
Here is the ajax-example.php file. The MySQL on my machine appears to be "localhost3306" and using the port number 7777
<?php
$dbhost = "localhost3306:7777";
$dbuser = "root";
$dbpass = "password";
$dbname = "web_prof_tracker";
// Connect to MySQL server
mysql_connect($dbhost, $dbuser, $dbpass);
// Select database
mysql_select_db($dbname) or die(mysql_error);
// Retrieve the data from Query String
$age = $_GET['age'];
$sex = $_GET['sex'];
$wpm = $_GET['wpm'];
// Escape user input to help prevent SQL injection
$age = mysql_real_escape_string($age);
$sex = mysql_real_escape_string($sex);
$wpm = mysql_real_escape_string($wpm);
// Build query
$query = "SELECT * FROM ajax_example WHERE sex = '$sex'";
if(is_numeric($age))
$query .= " AND age <= $age";
if(is_numeric($wpm))
$query .= " AND wpm <= $wpm";
// Execute query
$qry_result = mysql_query($query) or die (mysql_error());
// Build result string
$display_string = "<table>";
$display_string .= "<tr>";
$display_string .= "<th>Name</th>";
$display_string .= "<th>Age</th>";
$display_string .= "<th>Sex</th>";
$display_string .= "<th>WPM</th>";
$display_string .= "</tr>";
// Insert a new row in the table for each person returned
while($row = mysql_fetch_array($sql_result)){
$display_string = "<tr>";
$display_string .= "<td>$row[name]</td>";
$display_string .= "<td>$row[age]</td>";
$display_string .= "<td>$row[sex]</td>";
$display_string .= "<td>$row[wpm]</td>";
$display_string .= "</tr>";
}
echo "Query: " . $query . "<br />";
$display_string .= "</table>";
echo $display_string;
?>
On the officially net beans website netbeans.org they do show a tutorial on how to run php projects using netbeans
This are the steps,
I will skip the configuration of php environment as you have mentioned that you do have apache and you used to run php projects.
On your netbeans this is what you need to do :
Start the IDE, switch to the Projects window, and choose File > New
Project. The Choose Project panel opens.
In the Categories list, choose PHP.
In the Projects area, choose PHP Application and click Next. The New
PHP Project > Name and Location panel opens.
Make sure your source folder is inside htdocs in your xampp.
Then click next and select Run As a local website then specify the project url
Then you have done your setup configuration
you need to then open the projects files then when you done choose run from the menu
Then your project will display on your default netbeans projects browser.
Hope this will help, Good luck
Source : https://netbeans.org/kb/docs/php/quickstart.html
Got this website --> http://www.secureshop.gr/POOL/acrosshotels/website/
If you check on the left sidebar there is the "find a hotel" sidebar where when you choose location from the drop down menu, the Hotel menu changes the options. This works with ajax. The problem is that it's not working with all versions of IE. When you choose a destination, the hotel drop down menu is empty/blank.
The javascript code is this. Pretty simple and works onclick of the destinations options
<script type="text/javascript">
function selecthotel(str) {
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("hotelselection").innerHTML=xmlhttp.responseText;
}
}
if(str == 0) {
str = 0;
}
xmlhttp.open("GET","includes/ajaxlocationsearch.php?location="+str+"&language=<?php echo $language; ?>",true);
xmlhttp.send();
}
</script>
The ajax file is this
$language = $_GET["language"];
$location = $_GET['location'];
if($location == "0") {
$result = mysql_query("Select * from eshop_articles where
category='/WEBSITE/SEARCHENGINE/HOTELS' order by
appearance",$link_id);
}else {
$result = mysql_query("Select * from eshop_articles where
category='/WEBSITE/SEARCHENGINE/HOTELS' and
short_description='$location' order by appearance",$link_id);
} ?>
<option value="0"><?php $a = $language."_choose_hotel"; echo ${$a};
?></option>
<?php while($row = mysql_fetch_assoc($result)) { ?>
<option value="<?php echo $row['appearance']; ?>"><?php echo
$row['title']; ?></option>
<?php } ?>
Thank you in advance :)
I made some testing and I found out that your code had some issues with the structure. You should always have the code properly formatted in order to find errors and problems faster. I formatted your code and found some problems with nesting and your query.
I would also like to warn you that you had a pretty serious SQL injection problem, which I fixed in this code by using prepared statements and a small extra preg_replace to strip all unwanted characters from the query and table in general. You should totally go and learn a little bit more about preventing SQL injections. There are great topics here that are dedicated to the subject and I made a list of these articles to you:
stackoverflow.com - How can I prevent SQL injection in PHP
php.net - SQL Injection
Here is the code I formatted and fixed. I have tested it by using no parameter, an empty parameter, a value that does not exist in the database, and a value that does exist in the database. Each one returned the value accordingly: three first ones return null, while the real query returns true; in this case it returns "No hotels available" if none found, or a list of these hotels if found. If the database query fails, it will by default return null, and then return "No hotels found".
I am sorry for changing the code layout a little bit, feel free to edit it back as you like, that's up to you. I highly recommend proper formatting however (might have been because of your code editor as well).
index.php
<?php
$language = "en";
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Hotel Selection</title>
</head>
<body>
<select id="hotelselection">
<option value="null">No hotels available</option>
</select>
<script>
function selecthotel(str) {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("hotelselection").innerHTML = xmlhttp.responseText;
}
}
if (typeof(str) == "undefined" || str == null) {
str = "";
}
xmlhttp.open("GET", "run.php?location=" + str + "&language=<?php echo($language); ?>", true);
xmlhttp.send();
}
selecthotel();
</script>
</body>
</html>
run.php
<?php
$phrases = array(
"en_error_db" => "No hotels available...",
"en_choose_hotel" => "Choose a hotel..."
);
$link_id = mysqli_connect("localhost", "", "", "");
if (mysqli_connect_errno($link_id)) {
die("Error occurred when attempting to connect to database (" . mysqli_connect_errno() . ": " . mysqli_connect_error() . ").");
error_log("Error occurred when attempting to connect to database (" . mysqli_connect_errno() . ": " . mysqli_connect_error() . ").");
exit(1);
}
$language_raw = isset($_GET["language"]) ? $_GET["language"] : "en";
$location_raw = isset($_GET['location']) ? $_GET["location"] : "";
$language = preg_replace("/[^\w.-]/", "", $language_raw);
$location = preg_replace("/[^\w.-]/", "", $location_raw);
if (empty($location)) {
$query = "SELECT * FROM `eshop_articles` WHERE `category` = '/WEBSITE/SEARCHENGINE/HOTELS' ORDER BY `appearance` ASC";
}else{
$query = "SELECT * FROM `eshop_articles` WHERE `category` = '/WEBSITE/SEARCHENGINE/HOTELS' AND `short_description` = ? ORDER BY `appearance` ASC";
}
if ($stmt = mysqli_prepare($link_id, $query)) {
if (!empty($location)) {
mysqli_stmt_bind_param($stmt, "s", $location);
}
mysqli_stmt_execute($stmt);
// Thanks to Bruce Martin on php.net for the SELECT * via _fetch (http://www.php.net/manual/en/mysqli-stmt.fetch.php#107034)
$metaResults = mysqli_stmt_result_metadata($stmt);
$fields = mysqli_fetch_fields($metaResults);
$statementParams = "";
foreach ($fields as $field) {
$statementParams .= (empty($statementParams) ? "\$column['" . $field->name . "']" : ", \$column['" . $field->name . "']");
}
$statment = "\$stmt->bind_result($statementParams);";
eval($statment);
print('<option value="0">' . $phrases[(isset($phrases[$language . "_choose_hotel"]) ? $language : "en") . "_choose_hotel"] . '</option>');
while (mysqli_stmt_fetch($stmt)) {
print('<option value="' . $column['appearance'] . '">' . $column['title'] . '</option>');
}
exit(1);
}else{
print('<option value="0">' . $phrases[(isset($phrases[$language . "_choose_hotel"]) ? $language : "en") . "_error_db"] . '</option>');
error_log("The script was unable to prepare a MySQLi statement (" . $query . ").");
exit(1);
}
?>
I switched over to MySQLi database extension instead of your deprecated MySQL extension. It should no longer return PHP errors over PHP error logs. I highly recommend switching to MySQL PDO if just possible. It's very simple, easy and works a lot better in my opinion!
Also, a note on your XMLHttpRequest/ActiveXObject usage: if you want to be able to support IE 5, create a class for that and load the script if the client is using that browser, otherwise use jQuery Ajax, which is very easy to use and you will not need to worry about query strings or so. The reason for having the ActiveXObject script out there, is because jQuery is not supported on IE 5, which is a common browser despite the known security issues. IE 5 is used by old computers, some banks, offices and other businesses that have not looked into the security details.
Hopefully this helped you.
Ajax-requests are cached in Internet Explorer. Try to delete the cache and then add a random parameter to the request-URL:
var url = "http://example.com/ajax.php?random="+new Date().getTime();
You shouldn't reinvent the wheel, there are some mature cross-browsers solutions out there already.
You should try using jQuery library and it's ajax method.
https://api.jquery.com/jQuery.ajax/
If you don't want to use a library you can find some solutions to your problem already, it involves creating different types of objects for IE:
http://www.quirksmode.org/js/xmlhttp.html
Internet Explorer caches content a lot, so you might need to force it to grab new data instead of taking it from the cache. You can add a GET parameter with a timestamp which is generated client side to the URL to which you're pointing.
In jQuery you can simply do it like this:
jQuery.ajax({
type: "GET",
url: "http://example.com/",
cache: false,
success: function (data) {
// do something here
}
});
Without jQuery you would need to add it manually to the url:
var url = "http://example.com" + "?_=" + (newDate()).getTime();
Hi I struggling to find the solution for hours and wonder if you guys could help me out
I have index.php that look like this
<?php include_once"connect.php";?>
<!DOCTYPE HTML>
<html>
<head>
....
<style>
....
</style>
<!--- AJAX --->
<script>
function showData(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","getData.php?q="+str,true);
xmlhttp.send();
}
</script>
<body>
<form>
<select name="users" onchange="showData(this.value)">
<option value="">---Select Project---</option>
<?php
// query projects
$query_pr=mysql_query("SELECT * FROM GeneralInfo");
// get project names and its corresponding revision number
while($pr=mysql_fetch_assoc($query_pr)){
echo '<option value="'.$pr['pRevNum'].'">'.$pr['pName'].'</option>';
}
?>
</select>
</form>
<br>
<div id="container" align="right"></div>
<script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.7.4.min.js"></script>
<script defer="defer">
// FUTURE USE php variable within KineticJS HERE
....
</script>
</body>
The my code work great to calling getData.php after select one of the option value according to the my database. Also I using ajax to get the corresponding data of each option value. Below is the getData.php
<?php
// get the data corresponding with the selected option
$q=intval($_GET['q']);
// establish connection
...
// select the database
// query here
$query ="SELECT DISTINCT BranchInfo.bName, BranchInfo.bRevNum, GeneralInfo.pName, GeneralInfo.pRevNum,BranchItemInfo.bIName, BranchItemInfo.bIRevNum
FROM `GeneralInfo`
INNER JOIN `BranchInfo`
ON GeneralInfo.bName=BranchInfo.bName
AND GeneralInfo.bRevNum=BranchInfo.bRevNum
INNER JOIN `BranchItemInfo`
ON BranchInfo.bIName=BranchItemInfo.bIName
AND BranchInfo.bIRevNum=BranchItemInfo.bIRevNum
AND GeneralInfo.pRevNum= '".$q."'";
// initialize variable with the query
$result = mysqli_query($connection,$query);
echo "<table border='1'>
<tr>
<th>bName</th>
<th>bRevNum</th>
<th>bIName</th>
<th>bIRevNum</th>
<th>pName</th>
<th>pRevNum</th>
</tr>";
$my_arr=array();
// fectching data into array
while($info = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $info['bName'] . "</td>";
echo "<td>" . $info['bRevNum'] . "</td>";
echo "<td>" . $info['bIName'] . "</td>";
echo "<td>" . $info['bIRevNum']."</td>";
echo "<td>" . $info['pName'] . "</td>";
echo "<td>" . $info['pRevNum'] . "</td>";
echo "</tr>";
}
// close connection
...
?>
At this point all the data that I need is display as a table on my page. I want to access the variables in getData.php (e.g $info['bIRevName']) and use it in a javascript within my index.php. I tried this in my index.php
<script>
var myvar= <?php echo $info[bIRevNum];?>";
</script>
and this is not working. Is there sufficient way to do that ?
Appreciate all your helps !!
Thanks a lot !!
I realized that when I create a php variable within my index.php, the script is works. But if I create a php variable within getData.php, the script could not access that variable. Is there any solution for this?
Try something like this:
<div class="hidden"><?php echo $info[bIRevNum];?></div>
And then take info with:
$("div.hidden").text();
Or without jQuery...
document.querySelector("div.hidden").innerText;
What returns that PHP code? returns the expected data?
Easy peasy
<script type="text/javascript">
.....
var some_variable = <?php echo $phpVar; ?>;
.....
</script>
There is a syntax error in your code which you tried. Assuming the value held in the variable is a number, I suggest you try this:
<script>
var myvar = <?php echo $info[bIRevNum];?>;
</script>
If your are taking the variable name as "$info" it wont work.
Change $info to $somethingelse...
Hope it works for you...
Here I go again. I am trying to change content of a division with data retrieved from my database. This has to be done without reloading the page, therefore I am using xmlhttp and javascript. The website is running on CodeIgniter. Below is the code with a short summary of it. I have been following this tutorial, but for some reason, when I click the button, nothing is happening.
View *xampInstallFolder/htdocs/application/obs/views/test_v.php*
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$( "#next_btn" ).click(function() {
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("listA").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getnext5.php?q="true);
xmlhttp.send();
})
</script>
</head>
<body>
<div id="listA">
</div>
<div id="next_btn">
</div>
</body>
</html>
Right now I trigger the function when my button gets clicked. The function is in the head of the view,. I am not sure where should the file with the query (getnext5.php) be stored. Right now it is inside the views folder. The link to the file is this xmlhttp.open("GET","getnext5.php?q="true); should I somehow change this?
Functions xampInstallFolder/htdocs/application/obs/views/getnext5.php
<?php
$con = mysqli_connect('localhost','root','root','obs2');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"obs2");
$sql="SELECT * FROM user WHERE id > 5";
$result = mysqli_query($con,$sql);
echo "<table>";
while($row = mysqli_fetch_array($result))
{
echo "<a style="display:block" href="base_url('core/detail/'.$row[id])">";
echo "<div id="suggested" onmouseover="" style="cursor: pointer;">";
echo "<div id="info">";
echo "<div id="info_center">";
echo "<p>" . $row['name'] . "</p>";
echo "</div>";
echo "</div>";
echo "<div class="mosaic-block fade">";
echo "<a href="base_url('core/detail/'.$row[id])" class="mosaic-overlay">";
echo '<div class="details">';
echo "<p>" . $row['summary'] . "</p>";
echo "</div>";
echo "</a>";
echo "<div class="mosaic-backdrop"><img src="www.puu.sh/5DSWj.jpg">";
echo "</div>";
echo "</div>";
echo "<div id="info">";
echo "<div id="info_center">";
echo "<p>" . "Rating: 7.7" . "</p>";
echo "</div>";
echo "</div>";
echo "</div>";
echo "</a>";
}
echo "</table>";
?>
In this file I establish the connection to my DB, run the query, store the rows in an array called $pages and then style the results using a while loop. The style is echoed, because it is then returned by the xmlhttp request and displayed in the listA division, replacing the original content. I am not sure if the echoes are written right or not.
I am open to any suggestions. Have been trying to resolve this the whole day without any success.
Thank you all for reading and most importantly for your replies.
You're not concatenating the get parameter properly.
xmlhttp.open("GET","getnext5.php?q="true);
q="true <-- true is a boolean!
Try opening like this:
xmlhttp.open("GET","getnext5.php?q=true");
If you do want to concatenate proper, do "q="+variable
You can use jquery ajax api, and then on success function you can replace div content with values retrieved from db.
Whilst I'm sure it must be something really obvious, I can't see where I am going wrong with this. I have a drop down list with two options in it. When I Select an option it should use XMLHttpRequest() to get a list of customers from the database, based on the option selected.
I have two parts:
ajax2_js.php - contains the javascript and html form.
ajax2_DBAccess.php - contains the PHP that gets the list from the databse.
I have checked everything on the second page, and this works fine on it's own (and displays the relevant list as a dropdown menu), but when I select the option on the first page, nothing happens.
My code thus far is:
ajax2_js.php
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script>
function ajaxFunction()
{
var ajaxRequest;
ajaxRequest = new XMLHttpRequest();
ajaxRequest.onreadystatechange = function()
{
if(ajaxRequest.readyState == 4)
{
document.getElementById('customerDiv').innerHTML=req.responseText;
}
}
ajaxResuest.open("GET", strURL, true);
ajaxRequest.send(null);
}
</script>
</head>
<body>
<form method="post" action="" name="form1">
Network : <select name="network" onChange="ajaxFunction('ajax2_DBAccess.php?network='+this.value)">
<option value="">Select Network</option>
<option value="1">Net1</option>
<option value="2">Net2</option>
</select>
</br>
Customer : <div id="customerDiv">
<select name="select">
<option>Select Customer</option>
</select>
</div>
</form>
</body>
ajax2_DBAccess.php
<?php
$network=$_GET['network'];
$q1 = "SELECT `CustName` FROM monitor.customers where network = $network;";
$con = new mysqli('localhost:3306', 'xxx', 'xxx');
if (mysqli_connect_errno())
{
$error = mysqli_connect_error();
echo $error;
exit();
}
else
{
$ConfRes = mysqli_query($con, $q1);
if ($ConfRes)
{
echo "<select name=\"Customers\">";
echo "<option>Select Customer</option>";
while($row=mysqli_fetch_array($ConfRes, MYSQLI_ASSOC))
{
$result = $row['CustName'];
echo "<option value>$result</option>";
};
echo "</select>";
}
else
{
$error = mysqli_error();
echo $error;
exit();
}
};
?>
Any assistance would be appreciated.
Check the javascript error log.
This might be the problem, a spelling error in "Request".
ajaxResuest.open("GET", strURL, true);
Also, your SQL query suffers from an SQL injection vulnerability in the $network parameter.
You can either use XML or JSON to return list. This tutorial should help. I personally would use XML.
header("Content-type: text/xml");
// Iterate through the rows, adding XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("CustName",$row['CustName']);
}
echo $dom->saveXML();
but there are plenty of tutorials on both methods.
Thanks for all your help guys, I have tracked it down to three things (all my fault):
function ajaxFunction()
should be:
function ajaxFunction(strURL)
.
ajaxResuest.open("GET", strURL, true);
should be:
ajaxRequest.open("GET", strURL, true);
.
and finally:
document.getElementById('customerDiv').innerHTML=req.responseText;
should be
document.getElementById('customerDiv').innerHTML=ajaxRequest.responseText;
.
(and of course the SQL injection vulnerability mentioned above which I will also fix).
cheers.