I am creating a forum kind of a website, where I display posts dynamically using ajax. When the user logs in he finds a 'orderby' drop down select option, where he can choose the order of the posts.
select menu
<select name="orderby" id="orderby" onchange="showposts(this.value)" >
<option value="1" selected>By Time</option>
<option value="2">By Genuine Count</option>
<option value="3">By Dubious Count</option>
</select>
when the page is loaded window.onload function is called, which calls the 'showposts()' function to display the posts.
onload()
window.onload=function(){
showposts();
};
showposts() function
function showposts(str){
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if(str != undefined){
currentType=str; //save the current type for later use
document.getElementById("postsdiv").innerHTML = "";
}else{
var e = document.getElementById("orderby");
str = e.options[e.selectedIndex].value;
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
// alert(xmlhttp.responseText);
document.getElementById("postsdiv").innerHTML=xmlhttp.responseText;
}
};
xmlhttp.open("GET","showposts.php?q="+str,true);
xmlhttp.send();
}
a part of showposts.php page which gets posts from database if the selected option is 1
if(intval($_GET['q'])==1){
while($row = $result->fetch_assoc()) {
echo "<div class='postclass'>";
echo "<span id='postspan".$row['id']."' name='postspan".$row['id']."' >";
echo "<span id='editspan".$row['id']."' name='editspan".$row['id']."' >";
echo "</br>";
echo "Posted By:          <span class='bold'> ".$row['user']."</span>";
if($username==$row['user']){
echo "<a href='javascript:void(0);' onclick='deletepost(".$row['id'].")' >DELETE </a>   ";
echo "<a href='javascript:void(0)'onclick='editpost(".$row['id'].",\"".$row['subject']."\",\"".$row['post']."\")' >EDIT </a></br>";
}else{
echo "</br>";
}
echo "<a id=".$row['id']."></a>";
echo "Date & Time: ".$row['date']."</br>";
echo "<span id=genuinecount".$row['id'].">Genuine Count: ".$row['genuine']."</span></br>";
echo "<span id=dubiouscount".$row['id'].">Dubious Count: ".$row['dubious']."</span>";
echo "</br>------------------------ </br>";
echo "Subject: <span class='bold' >".$row['subject']."</span></br>";
echo "Post: ";
echo "<div class='postbox' > • ".$row['post'] . "</div><br /></br>";
}
}
So, my question is how to add pagination for this script? Can anyone help?
query
$sql = "SELECT * FROM posts order by date desc";
$result = $connection->query($sql);
showposts() function
function showposts(str, page, pagesize){
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if(str != undefined){
currentType=str; //save the current type for later use
document.getElementById("postsdiv").innerHTML = "";
}else{
var e = document.getElementById("orderby");
str = e.options[e.selectedIndex].value;
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
// alert(xmlhttp.responseText);
document.getElementById("postsdiv").innerHTML=xmlhttp.responseText;
}
};
xmlhttp.open("GET","showposts.php?q="+str+'&page='+page+'&pagesize='+pagesize,true);
xmlhttp.send();
}
query
$page = intval($_GET['page');
$pagesize = intval($_GET['pagesize']);
$sql = "SELECT * FROM posts order by date desc limit "
. ($page-1)*$pagesize . ", " . $pagesize;
Example link
Page 1, 20 per page
Related
I'm new to AJAX and I'm trying to create two dropdownlists of options from a database depending on what the user selects in two previous dropdowns. I've checked every way shape and form I've looked up but one dropdownlist doesn't return any values and the other says internal server error 500.
This is where the onChange event is, triggering the AJAX functions:
<select required="true" id="oficinaLoc" name="oficinaLoc" onchange="getAgent(this.value); selClub(this.value)">
<option value="">Seleccione Unidad</option>
<option value="680 - Centro de Tecnología de Información">680 - Centro de Tecnología de Información</option>
<option value="681 - Educación Agrícola">681 - Educación Agrícola</option>
<option value="682 - Planificación y Evaluación">682 - Planificación y Evaluación</option>
<option value="683 - Medios Educativos e Información">683 - Medios Educativos e Información</option>
<option value="684 - Ciencias de la Familia y el Consumidor">684 - Ciencias de la Familia y el Consumidor</option>
etc...
These are my AJAX functions:
function getAgent(str) {
if (str == "") {
document.getElementById("dispAgente").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 (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("dispAgente").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getagent.php?q="+str,true);
xmlhttp.send();
}
}
function selClub(unidad) {
if (unidad == "") {
document.getElementById("dispNombre").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 (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("dispNombre").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getnombre.php?j="+unidad,true);
xmlhttp.send();
}
}
And these are the PHP pages it calls to through the XMLHttpRequest respectively:
getagent.php
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
$q = ($_GET['q']);
$con = mysqli_connect('intrasise.uprm.edu','jchristian','registro4h','4h');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"4h");
$sql="SELECT nombre FROM personal4h WHERE unidadProg LIKE '%".$q."%'";
$result = mysqli_query($con,$sql);
echo '<select name="agenteExt"';
while($row = mysqli_fetch_array($result)) {
echo "<option value = " . $row['nombre'] . ">" . $row['nombre'] . "</option>";
}
echo "</select>";
mysqli_close($con);
?>
getnombre.php
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
$j = ($_GET['j']);
$con = mysqli_connect('intrasise.uprm.edu','jchristian','registro4h','4h');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"4h");
$sql="SELECT nombreClub FROM club4h WHERE oficinaLoc LIKE '%".$j."%'";
$result = mysqli_query($con,$sql);
echo '<select name="nombreClub"';
while($row = mysqli_fetch_array($result)) {
echo "<option value = " . $row['nombreClub'] . ">" . $row['nombreClub'] . "</option>";
}
echo "</select>";
mysqli_close($con);
?>
The getAgent function doesn't return any options in the dropdownlist even though it creates the empty select. The selClub function gives me a 500 internal server error on the xmlhttp.open("GET","getagent.php?q="+str,true); line. I really don't know what else to do, I've followed every online article I've found about this to the dot.
A 500 error is a server error, so that means the problem will be in PHP and I'm seeing alot of issues there. I'm not sure that this is a complete list,...you'll need to debug it yourself, but here's a couple that aren't helping.
$j = ($_GET['j']);
$j = $_GET['j'];
//dump the ()
echo '<select name="nombreClub"';
echo '<select name="nombreClub">';
//closing > is missing
echo "<option value = " . $row['nombre'] . ">" . $row['nombre'] . "</option>";
echo "<option value=\"".$row['nombre']."\">".$row['nombre']."</option>";
//quotes around the value are missing
If you view the errors thrown by the PHP files, then you'll be on your way.
Good luck
I am trying to update my list of tweets via AJAX. I have ran the script on the page and know that script works, and I have a console.log line in my ajax call so I know that is getting hit as well.
setInterval(function () {sendRequest()}, 5000);
function sendRequest(){
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){
console.log("yay");
}
}
xmlhttp.open("GET","getTweets.php",true);
xmlhttp.send();
}
My AJAX should run every 5 seconds, and the hit the PHP script to return new results that have been stored in the database. My PHP looks like:
$conn = mysqli_connect("localhost", "*", "*", "*");
if (!$conn) {
echo("Connection failed: " . mysqli_connect_error());
}
$query = "SELECT * FROM tweets;";
$results = mysqli_query($conn, $query);
while($list = mysqli_fetch_assoc($results)){
echo '<div class="tweet-containter">';
echo '<img class="user-img" alt="user-img" src="images/gb.png">';
echo '<h3 class="tweet-username">#'.$list['username'].'</h3>';
echo '<p class="tweet-body">'.$list['tweetBody'].'</p>';
echo '<p class="tweet-body">Tweeted: '.$list['datePosted'].'Retweet: <i class="fa fa-retweet" id="retweet4" onclick="retweetAJAX()"></i> Like: <i class="fa fa-thumbs-up" id="likes4" onclick="likeAJAX()"></i> Dislike: <i class="fa fa-thumbs-down" id="dislikes4" onclick="dislikeAJAX()"></i></p>';
echo '</div>';
}
This goes for those that do not understand ReadyState codes. You should know the following codes for ReadyState:
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
And Status Code
200: "OK"
404: Page not found
with that said, try doing this:
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if(xmlhttp.status == 200){
console.log(xmlhttp.responseText);
} else if(xmlhttp.status == 400) {
alert('There was an error 400')
} else {
alert('something else other than 200')
}
}
}
ryandonohue,
PHP is a Hyper-Text Processor. PHP runs on your server & the results are generated before the page is loaded. You should not be using PHP to output results like HTML elements, it is much more appreciated if you use JavaScript to manipulate the Document Object Model (DOM).
Though, for your intermediate purposes you might not notice an immediate difference.
For PHP5 you should look into the usage of PHP-PDO http://php.net/manual/en/class.pdo.php to prevent SQL injection.
Modification:
function getall($table, $values, $conditions = null, $limit = null, $ascdesc = null){
$values_str = "";
foreach($values as $key => $value){
$values_str .= $value . ", ";
}
$cond_str = "";
$hascond = false;
if($conditions != null){
$hascond = true;
foreach($conditions as $key => $value){
$cond_str .= $key . "='" . $value . "' AND ";
}
$cond_str = rtrim($cond_str, " AND ");
}
$values_str = rtrim($values_str, ", ");
$cond_str = " WHERE (" . $cond_str . ")";
$orderby = "";
$hasorder = false;
if($ascdesc != null){
$hasorder = true;
foreach($ascdesc as $key => $value){
$orderby = " ORDER BY " . $value . " " . $key;
break;
}
}
$sql = "SELECT " . $values_str . " FROM " . $table . " " . (($hascond)? $cond_str: "") . (($hasorder)? $orderby: "") . (($limit)? " LIMIT " . $limit: "");
//echo $sql;
$sql_prep = (new PDO('mysql:host=localhost;dbname=' . 'database', 'username', 'Password'))->prepare($sql);
$sql_prep->execute();
return $result = $sql_prep->fetchAll(PDO::FETCH_ASSOC);
}
initialization: ( returns an array so you need to json encode)
getall('table',
Array(
'*'
),
null, 5, null);
AJAX:
function ajax(file,type, params, func){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//xmlhttp.responseText
func(xmlhttp.responseText);
}
}
if(type.toLowerCase() != "post"){
xmlhttp.open(
type, file + "?" + params_to_get(params),
true
);
xmlhttp.send();
}else{
xmlhttp.open(
type, file,
true
);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(params_to_get(params));
Since you have an error code of readystate of 4 with a status of 500 i would say the issue is more with the compatibility of MYSQLi or the way your table is set up with your database.
check out this POST for more information about headers:
Ajax call to PHP is returning nothing
I have two dynamically loaded dropdowns: one containing golf course holes information and another holding users- together the information will be used to generate a scorecard.
When the course is selected and a user is selected I want to click a button and then this will generate the scorecard.
Below is the code for the 'course' dropdown
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = '';
$con = mysqli_connect($db_host,$db_user,$db_pass, $db_name);
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$sql = "SELECT courseID, name FROM courses";
$result = mysqli_query($con, $sql) or die("Error: ".mysqli_error($con));
while ($row = mysqli_fetch_array($result))
{
$courses[] = '<option value="'.$row['courseID'].'">'.$row['name'].'</option>';
}
?>
Below is the code for the 'user' dropdown
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = '';
$con = mysqli_connect($db_host,$db_user,$db_pass, $db_name);
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$sql = "SELECT userID, forename, surname FROM user";
$result = mysqli_query($con, $sql) or die("Error: ".mysqli_error($con));
while ($row = mysqli_fetch_array($result))
{
$users[] = '<option value="'.$row['userID'].'">'.$row['forename'].' '.$row['surname'].'</option>';
}
?>
Below is the HTML code for the dropdowns
<form>
<select id="selectCourse" onchange="showCourse(this.value)">
<option value = "">Select Course</option>
<?php foreach($courses as $c){
echo $c;
}?>
</select>
<select id="selectUser" >
<option value = "">Select User</option>
<?php foreach($users as $u){
echo $u;
} ?>
</select>
<button type="button" >Click me</button>
</form>
At the moment I have code that uses the 'onchange' to load the first part of the scorecard which contains the hole information about that course. I am having problems changing this to the click of the button and also consider another variable from the user dropdown.
The below code is taken from W3Schools which loaded the hole information correctly based on 'onchange'.
<script>
function showCourse(str) {
if (str == "") {
document.getElementById("txtHint").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 (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","generateSC.php?cValue="+str,true);
xmlhttp.send();
}
}
</script>
The below code shows the first half of the scorecard being generated from the selection of the first dropdown.
<?php
$cValue = mysql_real_escape_string($_GET['cValue']);
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = '';
$con = mysqli_connect($db_host,$db_user,$db_pass,$db_name);
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$sql="SELECT DISTINCT holeNumber, strokeIndex, par FROM holes WHERE courseID= '".$cValue."'";
$result = mysqli_query($con,$sql) or die("Error: ".mysqli_error($con));
echo '<div class="scorecardTable">
<table>
<tr>
<th>HoleNumber</th>
<th>Par</th>
<th>Stroke Index</th>
<th>Score</th>
<th>Points</th>
</tr>';
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['holeNumber'] . "</td>";
echo "<td>" . $row['par'] . "</td>";
echo "<td>" . $row['strokeIndex'] . "</td>";
echo "<td> <input required type=text /></td>";
echo "<td> </td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</body>
</html>
What I am looking to know is can I pass two variables through at this point below:
xmlhttp.open("GET","generateSC.php?cValue="+str,true);
and if so how would I get the second variable.
EDIT
<script>
function showCourse(course, user) {
var user = document.getElementById('selectUser').value;
var course = document.getElementById('selectCourse').value;
if (user || course == "") {
document.getElementById("txtHint").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 (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","generateSC.php?course="+course+"&user="+user,true);
xmlhttp.send();
}
}
</script>
I've updated what I have above... the problem now is how do i get the button to work with the two variables?
<form>
<select id="selectCourse">
<option value = "">Select Course</option>
<?php foreach($courses as $c){
echo $c;
}?>
</select>
<select id="selectUser" >
<option value = "">Select User</option>
<?php foreach($users as $u){
echo $u;
} ?>
</select>
<button type="button" >Click me</button>
</form>
Just fetch the values from both dropdowns and concatinate the URL:
var user = document.getElementById('selectUser').value;
var course = document.getElementById('selectCourse').value;
xmlhttp.open("GET","generateSC.php?cValue="+course+"&user="+user,true);
Then your generateSC php script will of course have to fetch the value from the user parameter and work with that as well.
$_GET['user'] will fetch the value from the user parameter.
So basically I have a drop down list that displays data from a MySQL table(accounts) that would display user accounts. When the user selects one of the accounts I want it to display all facilities(facility table) that are owned by that account.
I have the drop down displaying the accounts, but it will not run the onChange() function to load my table. Here is everything I have, can someone tell me why my function is not getting triggered at all?
Index.php
<?php
require_once('sessionstart');
require_once('header.php');
require_once('dbconn.php');
//Accounts
require_once('getaccounts.php');
//Facility
echo "<div id='facilities'>";
require_once('getfacility.php');
echo "</div>";
?>
<?php
require_once 'footer.php';
?>
getaccounts.php
<?php
//require files
require_once('sessionstart.php');
require_once('dbconn.php');
//clear options variable
$options = "";
//connect to db and test connection.
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (!$dbc) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT account_id, account_name FROM accounts";
$data = mysqli_query($dbc, $sql);
//loop through data and display all accounts
while ($row = mysqli_fetch_array($data)) {
$options .="<option>" . $row['account_name'] . "</option>";
}
//account drop down form
$accountDropDown="<form id='account' name='account' method='post' action='getaccounts.php'>
<label>Accounts: </label>
<select name='account' id='account' onchange='showFacilities(this.value)'>
<option selected='selected' disabled='disabled' value=''>Select account</option>
" . $options . "
</select>
</form>";
//echo out account form
echo $accountDropDown;
?>
This works how I need it to and displays all accounts within the drop down. However I can't seem to get the showFacilities() function to work.
getfacility.php
<?php
require_once('dbconn.php');
$q = intval($_GET['q']);
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (!$dbc) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM facility "
. "INNER JOIN accounts ON accounts.account_id = facility.account_id "
. "WHERE facility.account_id = '".$q."'";
$data = mysqli_query($dbc, $sql);
echo "<table>
<tr>
<th>Facility Number</th>
<th>Facility Name</th>
<th>Facility Address</th>
<th>Facility City</th>
</tr>";
//loop through data and display all accounts
while ($row = mysqli_fetch_array($data)) {
echo "<tr>";
echo "<td>" . $row['facility_number'] . "</td>";
echo "<td>" . $row['facility_name'] . "</td>";
echo "<td>" . $row['facility_address'] . "</td>";
echo "<td>" . $row['facility_city'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
footer.php (includes showFacilities())
<script>
function showFacilities(account){
//I wrote this to test and see if this function was even being triggered.
document.alert("test");
if(account == ""){
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("facilities").innerHTML = xmlhttp.responseText;
}
}
else{
xmlhttp.open("GET","getfacility.php?q="+account,true);
xmlhttp.send();
}
}
</script>
<footer>
<p>Copyright ©</p>
</footer>
</body>
</html>
Please tell me if I am doing this all wrong, am I laying everything out properly? Why is this function not being hit?
I have tried to a bunch of different things, and I just can't seem to get this to work, any help or advice or even a push in the proper direction will be very appreciated, thanks.
Your if else clauses don't add up (so your script is generating a script error, most likely a syntax error).
else{
xmlhttp.open("GET","getfacility.php?q="+account,true);
xmlhttp.send();
}
This piece doesn't have an IF to accompany it.
This would be correct:
if(account == ""){
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 (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("facilities").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getfacility.php?q="+account,true);
xmlhttp.send();
}
On a sidenote: Why create a form wrapper around your select (the one that where you can load accounts) when you use an onchange event to fire an XmlHTTPRequest?
I have been looking through the questions on here and cant find an exact answer to what i am after :( but i have managed to get something.
i have a form select field which i populate from a db query
<select style="width:100%;" class="quform-tooltip chosen-select" id="company_select" name="company_select" title="Company Select" onChange="showUser(this.value)">
<option value="">Please select</option>
<?php
$userID = $user->getUserID();
$query = $user->database->query("SELECT * FROM tbl_businesses as business LEFT JOIN tbl_user_businesses as biz_user ON business.businessID = biz_user.businessID WHERE biz_user.userID ='$userID'");
while($row=$user->database->fetchArray($query))
{
$bizID = $row['businessID'];
$bizName = $row['businessName'];
echo "<option value='$bizID'>$bizName</option>";
}?>
</select>
and then there are currently 2 other textboxes (might increase eventually) which i want to populate when the above select box value is changed/selected
<input id="company_name" type="text" name="company_name" value="" />
<input id="company_email" type="text" name="company_email" value="" />
so i have an onchange function on my select box which is this
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("company_name").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)
{
var data = JSON.parse(xmlhttp.responseText);
for(var i=0;i<data.length;i++)
{
document.getElementById("company_name").innerHTML += data[i].id + ' - ' + data[i].name + ' - ' + data[i].web;
}
}
}
xmlhttp.open("GET","formdata.php?q="+str,true);
xmlhttp.send();
}
</script>
and my formdata.php file is like so
<?php
include("include/user.php");
$q = intval($_GET['q']);
$sql="SELECT * FROM tbl_businesses WHERE businessID = '".$q."'";
$result = $user->database->query($sql);
$info = array();
while($row=$user->database->fetchArray($result))
{
$cID = $row['bussinessID'];
$cName = $row['businessName'];
$cWeb = $row['businessWebsite'];
$info[] = array( 'id' => $cID, 'name' => $cName, 'web' => $cWeb );
}
echo json_encode($info);?>
which is making the ajax call correctly and returning the data expected but i now need help to populate the textbox values?
can anyone please help me with this, have literatly spent ages trying to figure it out, im not familiar with javascript/json so not sure where to begin
i want the company_name textbox value to be set to $cName; and
company_email textbox value to be set to $cWeb;
appreciate any help
Luke
ok the solution that i used, for anyone else wanting to know how i solved it is
my index.php which contains the javascript and the form code
javascript code
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" type="text/javascript"></script>
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("company_name").value="";
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)
{
var data = JSON.parse(xmlhttp.responseText);
for(var i=0;i<data.length;i++)
{
document.getElementById("company_name").value = data[i].name;
document.getElementById("company_email").value = data[i].web;
}
}
}
xmlhttp.open("GET","formdata.php?q="+str,true);
xmlhttp.send();
}
</script>
and the form code
<select style="width:100%;" class="quform-tooltip chosen-select" id="company_select" name="company_select" title="Company Select" onChange="showUser(this.value)">
<option value="">Please select</option>
<?php
$userID = $user->getUserID();
$query = $user->database->query("SELECT * FROM tbl_businesses as business LEFT JOIN tbl_user_businesses as biz_user ON business.businessID = biz_user.businessID WHERE biz_user.userID ='$userID'");
while($row=$user->database->fetchArray($query))
{
$bizID = $row['businessID'];
$bizName = $row['businessName'];
echo "<option value='$bizID'>$bizName</option>";
}?>
</select>
<input id="company_name" type="text" name="company_name" value="" />
<input id="company_email" type="text" name="company_name" value="" />
then my formdata.php
$q = intval($_GET['q']);
$sql="SELECT * FROM tbl_businesses WHERE businessID = '".$q."'";
$result = $user->database->query($sql);
$info = array();
while($row=$user->database->fetchArray($result))
{
$cID = $row['businessID'];
$cName = $row['businessName'];
$cWeb = $row['businessWebsite'];
$info[] = array( 'id' => $cID, 'name' => $cName, 'web' => $cWeb );
}
echo json_encode($info);?>
thats it, thanks to charlietfl for your help!
hope this helps someone :)
Here's an example with PHP and JQuery. If you are not familiar with JQuery, I suggest you take some time to digg into that before going on with your ajax, it's definitely gonna worth it. JQuery have methods like get and ajax to do async request to the server.
Now, heres some jquery we used to get JSON data from the server.
var title = '.....'
$.getJSON('getActivite.php?title=' + title, null,
function(data){
$("#currentId").val(data.ID);
$("#nomActivite").val(data.Nom);
$("#Description").val(data.Description);
$("#DateEvent").val(data.Date);
});
$("#currentId").val(data.ID); , this says : find the element with the id currentId in the DOM, and change it's value to the property ID of the data received from the ajax call.
On the PHP side, they had
<?php
header('Content-Type: application/json');
mysql_connect("localhost","root") or die (" NOPE . [" . mysql_error() . "]");
mysql_select_db("garderie");
$title = $_GET["title"]; // we received this from the json call
$query = " select a.ActiviteID as ActiviteID , rtrim(a.Nom) as Nom, a.Description from activites a inner join .....' ";
$result = mysql_query($query);
$ligne = mysql_fetch_array($result);
$data = array(
'ID' => $ligne["ActiviteID"],
'Nom' => $ligne["Nom"],
'Description' => $ligne["Description"],
'Date' => $date
);
mysql_close();
echo (json_encode($data));
?>