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...
Related
I posted this earlier but it incorrectly got marked as a duplicate of Can scripts be inserted with innerHTML?, which isn't my problem. I'm not trying to run any JavaScript through using innerHTML, I'm trying to run JavaScript that is located in a PHP file called through Ajax/XmlHttp. I am using innerHTML in that JS, but I'm not writing more JS within that. So it's not a duplicate of that question and I'm trying it again now.
Not sure what's going on here. I'll explain the organization of my files first and then get into the code.
The application- Allows the user to select different attributes (i.e. year or name) and view pictures of matching results from a database.
Files- I have a gallery.php file that has a series of HTML form elements acting as selectors to get filtered results from a database. Whenever a selector is set or changed, the file sends a new request to a get.php file that uses Ajax to refresh the results without loading a new page. All that works great. My next task is to implement a modal section where I can click on an image and view a bigger version which I plan to do with JavaScript and CSS, but my intermediate goal is to just change some text at the bottom of the results from get.php again using JavaScript, just as a first step. But I can't seem to get any JavaScript written in get.php to fire.
Code-
This is gallery.php:
<?php
include_once("./../php/navbar.php");
?>
<html>
<head>
<link href="/css/siteTheme.css" rel="stylesheet">
<style>
.attributes span {
margin-right: 1rem;
}
</style>
<script>
function changeParams() {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("test").innerHTML = this.responseText;
}
};
year = document.getElementById("years_select").value;
nameFirst= document.getElementById("nameFirst_select").value;
/* Ton of other getElementById statements here that I'm excluding to keep things shorter */
url = "get.php?year="+year+......;
xmlhttp.open("GET", url, true);
xmlhttp.send();
} /* End function */
</script>
</head>
<body>
<div class="content">
<h1>Gallery</h1>
<form>Details:
<!-- -------------------- Year -------------------- -->
<select onchange="changeParams()" name="years" id="years_select">
<option value="All">Year</option>
<?php
include("/var/www/admin.php");
$conn = mysqli_connect($dbServername, $publicdbUsername, $publicdbPass, $dbName);
if (!$conn) {
die('Could not connect: ' . mysqli_error($conn));
}
$sql = "select year from db group by year order by year desc";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($result)) {
echo "<option value=" . $row['year'] . ">" . $row['year'] . "</option>";
}
mysqli_close($conn);
?>
</select>
<!-- A bunch of other selectors are created here following the same pattern as above of getting results from a DB -->
<!-- -------------------- Searchbar -------------------- -->
<input type="text" size="50" onkeyup="changeParams()" name="search" id="search" placeholder="Search"></input>
</form>
<div id="test">Choose some filters to see some results!</div>
</form>
</div> <!-- Ends content div -->
</body>
</html>
This is get.php:
<html>
<head>
<style>
/* Bunch of CSS that's not relevant here */
</style>
<script type="text/javascript">
console.log(".....");
var parts = document.querySelectorAll("div.imgContainer");
console.log("Found something:", parts);
parts.addEventListener("click", function(){
document.getElementById("anID").innerHTML = "Test...";
});
</script>
</head>
<body>
<?php
include("/var/www/admin.php");
$year = $_GET['year'];
//Bunch of other variables set here following the same logic, getting data from gallery.php
$conn = mysqli_connect($dbServername, $publicdbUsername, $publicdbPass, $dbName);
if (!$conn) {
die('Could not connect: ' . mysqli_error($conn));
echo '$conn';
}
$sql = 'select * db';
/* ---------- Creating SQL statement ---------- */
$clauses = 0;
if ($year != "All") {
if ($clauses == 0) {
$sql = $sql . ' where year = "' . $year . '" and';
$clauses = $clauses + 1;
} else {
$sql = $sql . ' year = "' . $year . '" and';
}
} /* Bunch of other if statements to get set information and add to sql statement as such */
// Need to chop of the last ' and' from the sql statement
$sql = substr($sql, 0, -4);
$sql = $sql . ' order by year desc';
$result = mysqli_query($conn, $sql);
$num_results = mysqli_num_rows($result);
if ($num_results == 0 or $clauses == 0) {
echo "<p>No matches to your query. Try refining your search terms to get some results.</p>";
} else {
echo "<p>" . $num_results . " results matched your query.</p>";
echo "<div class=results>";
//echo "<div>";
echo '<script type="text/javascript">
function modalFunction() {
document.getElementById("anID").innerHTML = "test";
}
</script>';
while ($row = mysqli_fetch_array($result)) {
$pic = $row['pathToPic'];
$wwwImg = substr($pic, 13);
//echo "<span id=aCard><img src=" . $wwwImg . " height ='250px'>";
//echo "<span class=text>" . $row['fullCardInfo'] . "</span></span>";
echo "<div class=fullContainer><div class='imgContainer'><img class=image src=" . $wwwImg ."></div><p class=text>" . $row['fullInfo'] . "</p></div>";
} // End while of results
echo "</div>";// End results div//</div>";
//echo '<div class="modal"><p id="anID"></p></div>';
} // End else of "if results"
mysqli_close($conn);
?>
<script>
</script>
<div>
<p id="anID">This in a div</p>
</div>
<!--<span>
<p id="anID">This in a span</p>
</span>-->
</body>
</html>
Sorry if that was messy, I chopped out a bunch of stuff that just gets/selects/filters some data. All that works and all variables that are left in there are set in my full code.
But the issue I'm having is writing JavaScript in get.php to change the text in the <p id="anID"> tags. I've tried JS in a few different areas of get.php, from in the <head> tags, to echoing it in <script> tags in the PHP, to pure <script> tags after the PHP statements are done (I think I left them in a few different places).
Problem is that nothing I do works to change the text in the <p> tags I references. Additionally, the console.log statements in the header of get.php don't seem to get called either. They don't fire no matter where I place them in get.php. Console.log works fine in gallery.php so it's not some issue with my browser or anything.
Long term, I will be adding JS query selectors to bring up a bigger image when an image is clicked on, but for now I'm just trying to make ANY JavaScript work in get.php and I'm struggling to do so. I don't see how this is a duplicate of the suggested repeat as I'm not trying to run JavaScript through innerHTML here.
Scratch that, it actually is trying to pass JavaScript through innerHTML as the information from get.php comes from this section of gallery.php:
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("test").innerHTML = this.responseText;
console.log("Response: ", this.responseText);
}
So it appears this is a duplicate of the question I linked after all. Apologies. However, there are not great answers to that question, so any tips would be appreciated.
This line:
document.getElementById("test").innerHTML = this.responseText;
Is simply going to add the contents of this.responseText to the element test. I'm sure you understand that much, but what you want to do is completely wrong. The scripts within the output of get.php will NOT be executed at all and you have corrupted your HTML as well by including a second <html><head> and more.
A better approach would be if get.php returned the data from you DB query as a JSON string like so:
$data;
while ($row = mysqli_fetch_array($result)) {
$data[]['pic'] = $row['pathToPic'];
$data[]['wwwImg'] = substr($row['pathToPic'], 13);
}
echo json_encode($data);
exit;
And then back on gallery.php you do something like:
if (this.readyState == 4 && this.status == 200) {
formatResult(this.responseText);
}
// ... snip ...
function confirmJson(str) {
var j = null;
if (str) {
try { j = JSON.parse(str); }
catch (e) { j = null; }
}
return j;
}
function formatResult(str) {
var data = confirmJson(str);
if (! data) {
console.log("result is not JSON");
return;
}
// do stuff with the data
var i, max = data.length;
var h = document.createElement("div");
var img;
for(i=0;i<max;i++) {
img = document.createElement("src");
img.src = data[i].wwwImg;
img.addEventListener("click",function(){ alert("pic:["+ data[i].pic +"]"); },true);
h.appendChild(img);
}
document.getElementById("test").innerHTML = h;
}
I just started to use AJAX, so I apologize if the question is very basic.
I use a simple AJAX script to update a session variable depending on which button you click, but I cant get it to update the heading with the new value when clicking the button. At the moment I got a button to reload the page, but I want to remove that and make the header update on each buttonclick.
index.php
<?php session_start(); ?>
<html>
<head>
<script type='text/javascript'>
function setSession( value) {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "setSession.php?variable=rider&value=" + value, true);
xmlhttp.send();
}
</script>
</head>
<body>
<?php
echo "<h1>You selected: " . $_SESSION['rider'] . "</h1>";
echo "<button type='button' onclick='javascript:setSession(this.value)' value='Kristoff'>Kristoff</button> ";
echo "<button type='button' onclick='javascript:setSession(this.value)' value='Edvald Boasson Hagen'>Edvald Boasson Hagen</button> ";
echo "<input type='submit' value='Re-Load Page'>";
?>
</body>
</html>
setSession.php
<?php
session_start();
if(isset($_REQUEST['variable']) && isset($_REQUEST['value']))
{
$variable = $_REQUEST['variable'];
$value = $_REQUEST['value'];
$_SESSION[$variable] = $value;
}
?>
#Chris and #tej explains the procedure.This is how you do it.
setSession.php
<?php
session_start();
if(isset($_REQUEST['variable']) && isset($_REQUEST['value'])){
$variable = $_REQUEST['variable'];
$value = $_REQUEST['value'];
$_SESSION[$variable] = $value;
echo $_SESSION[$variable];
}
?>
index.php
echo "<h1 id='selection'>You selected: " . $_SESSION['rider'] . "</h1>";
function setSession( value) {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "setSession.php?variable=rider&value=" + value, true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("selection").innerHTML = "You selected ".xmlhttp.responseText;
}
}
xmlhttp.send();
}
At the moment index.php is only loaded once. Therefore $_SESSION['rider'] has been output once and only once so it won't change. You need to use javascript to read the response from the xhr you're doing (and at the same time output $_SESSION['rider'] in the setSession.php file.
I'm not sure of what your application is trying to do but this can be achieved without any php at all.
After triggering ajax call you have to modify the h1 already displayed.
Add a class to h1 and use jQuery or JavaScript to modify the value once ajax is complete.
if(xhr.status===200){
$('.header').text(//rider text);
}
This will set the value after ajax and if user refreshes page it will automatically load from session.
But as other answer suggests this can easily be attained without php itself but I will leave application technology decision to you.
Having the issue here where my jquery work fine when viewing it as a single page however when I try and include that PHP file in another page either using php include or ajax the jquery doesnt seem to load.
I'm rather new to all this stuff so its very possible I'm doing something silly, any help would be greatly appreciated!
HTML Code
<html>
<head>
<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.open("GET","jquery.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="users" ID="option" onChange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">ID One</option>
<option value="2">ID Two</option>
<option value="3">ID Three</option>
<option value="4">ID Four</option>
</select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here.</b></div>
</body>
</html>
PHP/Jquery
<html>
<head>
<link href="../../Styles/tablestyles.css" rel="stylesheet" type="text/css" />
<?php include "db.php" ?>
<script type="text/javascript" src="../../JS/tablesorter/jquery-latest.js"></script>
<script type="text/javascript" src="../../JS/tablesorter/jquery.tablesorter.js"></script>
<script type="text/javascript" src="../../JS/sorter.js"></script>
<script>
$(document).ready(function() {
// call the tablesorter plugin
$("table").tablesorter({
// sort on the first column and third column, order asc
sortList: [[0,0],[2,0]]
});
});
</script>
<?php
$q = intval($_GET['q']);
$result = mysqli_query($db_connection, "SELECT * FROM student WHERE Student_Id = '".$q."' or Student_Id = 7");
echo "<table id=\"myTable\" class=\"tablesorter\">
<thead>
<tr>
<th>Student ID</th>
<th>B-Code</th>
<th>First Name</th>
<th>Second Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['Student_Id'] . "</td>";
echo "<td>" . $row['B-code'] . "</td>";
echo "<td>" . $row['Student_Forename'] . "</td>";
echo "<td>" . $row['Student_Surename'] . "</td>";
echo "<td>" . $row['Student_Email'] . "</td>";
echo "</tr>";
}
echo"</tbody>
</table> ";
mysqli_close($con);
?>
Your AJAX request is going to getuser.php, which is what I'm going to assume your second code block represents? Basically instead of making a call to some PHP code that does your processing and sending you a response, you're actually calling back a PHP script AND an HTML page to boot, then embedding that into an existing page.
I recommend doing the following:
First, remove the HTML from getuser.php so that all you have left is the PHP code.
Then, in the page making the AJAX call, as part of your "success" function, include your sorter function so that it occurs after you've gotten your response and written out the new HTML. Something to the effect of the following:
getuser.php:
<?php include "db.php";
$q = intval($_GET['q']);
$result = mysqli_query($db_connection, "SELECT * FROM student WHERE Student_Id = '".$q."' or Student_Id = 7");
echo "<table id=\"myTable\" class=\"tablesorter\">
<thead>
<tr>
<th>Student ID</th>
<th>B-Code</th>
<th>First Name</th>
<th>Second Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['Student_Id'] . "</td>";
echo "<td>" . $row['B-code'] . "</td>";
echo "<td>" . $row['Student_Forename'] . "</td>";
echo "<td>" . $row['Student_Surename'] . "</td>";
echo "<td>" . $row['Student_Email'] . "</td>";
echo "</tr>";
}
echo"</tbody>
</table> ";
mysqli_close($con);
Then, in your calling page success code:
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
$("table").tablesorter({
// sort on the first column and third column, order asc
sortList: [[0,0],[2,0]]
});
}
}
Also, move your necessary CSS and JavaScript includes to the calling page as well so that you have your jQuery object available, etc. I would also recommend changing that code to use jQuery contructs and functions instead of raw JavaScript. It'll help keep your code clean, consistent, and easier to read :)
NOTE: I typed this up in a hurry, so anyone feel free to call me out and correct me on any mistakes.
Pretty much what I thnk is the issue is that when your jQuery script fires,the default functionality of the selector statements is select and do this on the current instances of this selector.
So if you do:
$(document).ready(function() {
// call the tablesorter plugin
$("table").tablesorter({
// sort on the first column and third column, order asc
sortList: [[0,0],[2,0]]
});
});
That finds all of the table tags on the page, and calls tablesorter on them. But, if additional table tags are added to the page, or the first table tag is added to the page when the page has already loaded, then jquery does not call table sorter onto it because it did not exist previously when it ran the $("table") selector.
This is not tested, but you can try and hook the .tablesorter onto the $("table") selector once everytime ajax finishes loading.
$( document ).ajaxComplete(function() {
$("table").tablesorter({
// sort on the first column and third column, order asc
sortList: [[0,0],[2,0]]
});
});
A similiar situation is when you use something like:
$( "#target" ).click(function() {
alert( "Handler for .click() called." );
});
The .click event is only bound to the #target elements that existed on the page when the page first loaded. Any subsequent #target elements added to the page later on will not have the .click event bound to them.
So say. You have header.php, where your script lives. Then you have index.php, and then you have table.php. If you include header.php inside index.php, the scripts inside header.php will effect the elements in index.php. But if you also include table.php inside of index.php, the scripts in header.php will not effect the elements in table.php unless you use the appropriate event binding like the .on() event below. I think...?
To resolve this, you have to use the .on event:
$( "#target" ).on( "click", function() {
alert( $( this ).text() );
});
The .on event will bind itself to all current, and later instances of the selector, in this example the selector is #target.
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.
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/