we are using below code to filter rows based on selected From & To date.
we can able to filter successfully & displaying results.
php
/* to show selected date */
if (isset($_POST['post_at']) && $_POST['post_at'] != '')
{
$orderFromDate = $_POST['post_at'] . " 00:00:00 ";
}
else
{
$orderFromDate = '';
}
if (isset($_POST['post_at_to_date']) && $_POST['post_at_to_date'] != '')
{
$orderToDate = $_POST['post_at_to_date'] . " 23:59:59 ";
}
else
{
$orderToDate = '';
}
/* to show selected date end*/
function getDesignerCollection()
{
/* date search */
if (isset($_POST['post_at']) && $_POST['post_at'] != '')
{
$orderFromDate = $_POST['post_at'] . " 00:00:00 ";
}
else
{
$orderFromDate = '';
}
if (isset($_POST['post_at_to_date']) && $_POST['post_at_to_date'] != '')
{
$orderToDate = $_POST['post_at_to_date'] . " 23:59:59 ";
}
else
{
$orderToDate = '';
}
/* date search end*/
$accountType = $rows['type'];
if ($accountType == "admin")
{
if ($orderFromDate != '') $order->addFieldToFilter('created_at', array(
'gteq' => $orderFromDate
));
if ($orderToDate != '') $order->addFieldToFilter('created_at', array(
'lteq' => $orderToDate
));
}
form
<form name="frmSearch" method="post" action="">
<input type="text" placeholder="From Date" id="post_at"
value="<?php
if ($orderFromDate != '')
{
$newPostStartDate = date('Y-m-d', strtotime($_POST['post_at']));
echo $newPostStartDate;
} ?>" name="post_at" />
<input type="text" placeholder="To Date" id="post_at_to_date"
value="<?php
if ($orderToDate != '')
{
$newPostEndDate = date('Y-m-d', strtotime($_POST['post_at_to_date']));
echo $newPostEndDate;
} ?>"name="post_at_to_date" />
<input type="submit" name="search" value="search" id="searchButton">
<input type="button" value="Reset" id="clear-dates">
</form>
jquery
jQuery.datepicker.setDefaults({
showOn: "button",
buttonImage: "assets/img/datepicker.png",
buttonText: "Date Picker",
buttonImageOnly: true,
dateFormat: 'yy-mm-dd'
});
$(function() {
$("#post_at").datepicker();
$("#post_at_to_date").datepicker();
});
now we want to display how many rows are selected. if result is as above image we want to display "rows : 1". i am very new to php & i tried below code , but its not displaying anything:
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if ($result = mysqli_query($link, "SELECT entity_id , created_at FROM sales_flat_order ORDER BY Name")) {
/* determine number of rows result set */
$row_cnt = mysqli_num_rows($result);
printf("Result set has %d rows.\n", $row_cnt);
/* close result set */
mysqli_free_result($result);
}
edit
now we want to display count of how many rows are displayed. so we tried below code. its displaying like below image. its displaying "rows = 3". because its considering "entity_id" column of "sales_flat_order" table. but i want "rows : 9" as you can see 9 rows in image.
require_once '../../app/Mage.php';
Mage::app();
// specify the date picker date-format
$format = 'Y-m-d';
// if posted data are not empty
if(!empty($_POST['post_at']) && !empty($_POST['post_at_to_date']))
{
if (!empty($_POST['post_at'])) {
$dateFrom = DateTime::createFromFormat($format, $_POST['post_at']);
}
if (!empty($_POST['post_at_to_date'])) {
$dateTo = DateTime::createFromFormat($format, $_POST['post_at_to_date']);
}
// Get the resource model
$resource = Mage::getSingleton('core/resource');
// Retrieve the read connection
$read = $resource->getConnection('core_read');
// MySQL query
$query = 'SELECT entity_id, created_at, dproduct_id FROM sales_flat_order WHERE created_at BETWEEN :fromdate AND :todate ;';
// Bind MySQL parameters
$binds = array(
'fromdate' => $dateFrom->format('Y-m-d H:i:s'),
'todate' => $dateTo->format('Y-m-d H:i:s')
);
// Execute the query and store the results in $results
$results = $read->fetchAll($query,$binds);
echo "rows : ".count($results);
echo "<br>";
print_r($results);
}
else {
echo "error you have not specified any dates";
}
complete code : http://pastebin.com/hMUEusvb
You can count the selected id from your mysqli query itsel.. Try this in your mysqli query
if ($result = mysqli_query($link, "SELECT count(entity_id) as Total_count,entity_id , created_at FROM sales_flat_order ORDER BY Name")) {
// Your process
}
You can count number of rows by using js. Add following code at the end of your code. Replace selector1 with class name which is used only for rows. Inspect your page in browser and find a class which is present only in rows and used once at a time in a row.
Then replace selector2 with class or id where you want to display number of rows.
<script>
$(document).ready(function () {
var count = 0;
//use class unique in each row.
$("selector1").each(function () {
count++;
});
//use class or id where you want to display count
$("selector2").prepend("Number of rows "+count);
});
If you want to handle it done through PHP. Please paste the code where it renders the search result.
Your current code is not working because your code send response back on line 293 of file http://pastebin.com/QKMj0k2p
You can find that in network tab of browser and see on search submit where it send request and what comes in response from there. If you can find where it is sending response back it will be easy to know which code is rendering rows. It will be more help full to solve your problem.
I think you have an error which is not present in your question. If you only want to fix this Issue. You can use JavaScript. You only have to know the exact selector.
$(document).ready( function (){
//your selector would direct li or td if there is no other li td then it works other wise you have select parent then li or td like below comment
//$(".class li").length
var count = $("li").length;
$("yourCounter").html(count);
} );
your PHP code should be like this
// if posted data are not empty
if(!empty($_POST['post_at']) && !empty($_POST['post_at_to_date'])) {
// specify the date picker date-format
$format = 'Y-m-d';
// create dates
$dateFrom = DateTime::createFromFormat($format, $_POST['post_at']);
$dateTo = DateTime::createFromFormat($format, $_POST['post_at_to_date']);
// if equal dates are applied to form
if($_POST['post_at']==$_POST['post_at_to_date']) {
$dateTo->add(new DateInterval('T23H59M59S'));
}
// Get the resource model
$resource = Mage::getSingleton('core/resource');
// Retrieve the read connection
$read = $resource->getConnection('core_read');
// MySQL query
$query = 'SELECT `entity_id`, `created_at` FROM `sales_flat_order` WHERE `created_at` BETWEEN :fromdate AND :todate ;';
// Bind MySQL parameters
$binds = array(
'fromdate' => $dateFrom->format('Y-m-d H:i:s'),
'todate' => $dateTo->format('Y-m-d H:i:s')
);
// Execute the query and store the results in $results
$results = $read->fetchAll($query,$binds);
echo "Orders count: ".count($results);
} else {
echo "error you have not specified any dates";
}
Related
Ok where to start, I will try and explain as much as I can.
I am using wordpress with contact form 7 and I am trying to populate 3 dropdown items on the contact form, I found some code that I was able to use with no problem but the problem with this was that it was getting the information from a excel file, the file is now to big and will not run on my website anymore so I would like to get the information from my database now.
I have made a table in my database "vehicle_information" with 3 columns "vehicle_type", "vehicle_make", vehicle_model"
I have code in my functions.php and code in my footer to be able to use the cf7 shortcodes.
Code from funtions.php
function ajax_cf7_populate_values() {
//MySQLi information
$db_host = '***';
$db_username = '***';
$db_password = '***';
$vehicles_makes_models = array();
//connect to mysqli database (Host/Username/Password)
$connection = mysqli_connect($db_host, $db_username, $db_password) or die('Error ' . mysqli_error());
//select MySQLi dabatase table
$vehicles_makes_models = mysqli_select_db($connection, 'vehicle_information') or die('Error ' . mysqli_error());
$sql = mysqli_query($connection, 'SELECT * FROM vehicle_type');
while($row = mysqli_fetch_array($sql)) {
$vehicles_makes_models[$row[0]][$row[1]][] = $row[2]; }
}
// setup the initial array that will be returned to the the client side script as a JSON object.
$return_array = array(
'vehicles' => array_keys($vehicles_makes_models),
'makes' => array(),
'models' => array(),
'current_vehicle' => false,
'current_make' => false
);
// collect the posted values from the submitted form
$vehicle = key_exists('vehicle', $_POST) ? $_POST['vehicle'] : false;
$make = key_exists('make', $_POST) ? $_POST['make'] : false;
$model = key_exists('model', $_POST) ? $_POST['model'] : false;
// populate the $return_array with the necessary values
if ($vehicle) {
$return_array['current_vehicle'] = $vehicle;
$return_array['makes'] = array_keys($vehicles_makes_models[$vehicle]);
if ($make) {
$return_array['current_make'] = $make;
$return_array['models'] = $vehicles_makes_models[$vehicle][$make];
if ($model) {
$return_array['current_model'] = $model;
}
}
}
// encode the $return_array as a JSON object and echo it
echo json_encode($return_array);
wp_die();
// These action hooks are needed to tell WordPress that the cf7_populate_values() function needs to be called
// if a script is POSTing the action : 'cf7_populate_values'
add_action( 'wp_ajax_cf7_populate_values', 'ajax_cf7_populate_values' );
add_action( 'wp_ajax_nopriv_cf7_populate_values', 'ajax_cf7_populate_values' );
Code from my footer
<script>
(function($) {
// create references to the 3 dropdown fields for later use.
var $vehicles_dd = $('[name="vehicles"]');
var $makes_dd = $('[name="makes"]');
var $models_dd = $('[name="models"]');
// run the populate_fields function, and additionally run it every time a value changes
populate_fields();
$('select').change(function() {
populate_fields();
});
function populate_fields() {
var data = {
// action needs to match the action hook part after wp_ajax_nopriv_ and wp_ajax_ in the server side script.
'action' : 'cf7_populate_values',
// pass all the currently selected values to the server side script.
'vehicle' : $vehicles_dd.val(),
'make' : $makes_dd.val(),
'model' : $models_dd.val()
};
// call the server side script, and on completion, update all dropdown lists with the received values.
$.post('<?php echo admin_url( 'admin-ajax.php' ) ?>', data, function(response) {
all_values = response;
$vehicles_dd.html('').append($('<option>').text(' -- choose vehicle -- '));
$makes_dd.html('').append($('<option>').text(' -- choose make -- '));
$models_dd.html('').append($('<option>').text(' -- choose model -- '));
$.each(all_values.vehicles, function() {
$option = $("<option>").text(this).val(this);
if (all_values.current_vehicle == this) {
$option.attr('selected','selected');
}
$vehicles_dd.append($option);
});
$.each(all_values.makes, function() {
$option = $("<option>").text(this).val(this);
if (all_values.current_make == this) {
$option.attr('selected','selected');
}
$makes_dd.append($option);
});
$.each(all_values.models, function() {
$option = $("<option>").text(this).val(this);
if (all_values.current_model == this) {
$option.attr('selected','selected');
}
$models_dd.append($option);
});
},'json');
}
})( jQuery );
The problem is I am still learning and this is the first time I have had to use this funtion.
and I am getting an error on my website
Warning: array_keys() expects parameter 1 to be array, null given in /customers/4/0/0/motobid.co.uk/httpd.www/wp-content/themes/storevilla-child/functions.php on line 38 {"vehicles":null,"makes":[],"models":[],"current_vehicle":false,"current_make":false}
any help would be very greatful.
Just like to say code was supplied by BDMW.
Where you use the method array_keys(), instead of:
$return_array['makes'] = array_keys($vehicles_makes_models[$vehicle]);
Try this:
$return_array['makes'] = ! empty($vehicles_makes_models[$vehicle]) ? array_keys($vehicles_makes_models[$vehicle]) : [];
From what I've read, the array_keys() has been an issue depending on php versions. Hope this helps!
I have a mysql table with the name of a team in one column (club_name) and an id on another (club_id).
Every team has a logo named with their respective id .png.
Then I have a text input where the user can write the name of a team. There is a jQuery function that shows the possible team names found in the database according to what the user is typing so that it can autocomplete. Once the user selects one of the options the focus moves out of the text input. At this point, I would like the image to change to the logo corresponding to the team. When the text input is empty or the name does not match any team in the database the image should be 0.png
How can I achieve this? My code so far is below:
EDIT:
I have three problems right now:
The method suggested to store the club id in the json object is only
returning the first row of the table.
The method is below (although it only returns one row of the table it does work, the image changes to the appropriate one - I ran a little test by replacing 'thisclub' with the name of the club):
<script>
var clublist = [
<?php
$search_clubs = " SELECT club_id, club_name FROM clubs ORDER BY club_id DESC";
$result_clubs = mysql_query($search_clubs);
echo json_encode(mysql_fetch_assoc($result_clubs)); //only returns one row
?>
];
</script>
Using another method I was able to have all the rows in the json object but this one did not work when I ran the same test by replacing 'thisclub' with the name of one club):
<script>
var clublist = [
<?php
$clubid = array(); $clubname = array();
$search_clubs = mysql_query(" SELECT club_id, club_name FROM clubs ");
while($row = mysql_fetch_array($search_clubs)) {
$clubid[] = $row["club_id"]; // or smth like $row["video_title"] for title
$clubname[] = $row["club_name"];
}
$res = array($clubid, $clubname);
echo json_encode($res);
?>
];
</script>
The second problem is I don't know what to replace 'thisclub' with.
In other words, how to get the value returned by the function.
I am now using two vars - one to store the name of the clubs only, for the original function, the other one for the name of the clubs and respective id, for the function that makes the image change. This is because I don't know what changes to make in the original function so that it searches for the names in the new var (which contains club_id too)
The full code is below.
<img id="team-logo" src="logos/0.png"/>
<input type="text" class="club-name" name="home" autocomplete="off"/>
<script>
var clubs = [
<?php
$search_clubs = " SELECT club_name FROM clubs ";
$result_clubs = mysql_query($search_clubs);
while($clubs = mysql_fetch_array($result_clubs)) {
$club_name = $clubs['club_name'];
echo '"'.$club_name.'",';
}
?>
];
var clublist = [
<?php
$search_clubs = " SELECT club_id, club_name FROM clubs ORDER BY club_id DESC";
$result_clubs = mysql_query($search_clubs);
echo json_encode(mysql_fetch_assoc($result_clubs)); //only returns one row
?>
];
$(".club-name").autocomplete({
source: clubs,
autoFocus: true,
minLength: 2,
delay: 0,
close: function(event, ui){
if (!event.keyCode || event.keyCode === 13){
$(this).parents('form').find('.club-name').filter(function (){
return $(this).val() === '';
}).first().focus();
//
}
clubid = "";
$.each(clublist, function (i, elem) {
if (elem.club_name === thisclub) {
clubid = elem.club_id;
$("#team-logo").attr("src", clubid+".png");
}
});
if(clubid == "") {
// show default image
$("#team-logo").attr("src", "0.png");
}
//$("#team-logo").attr("src", clubs+".png");
}
});
</script>
I would get the club_id from the original SELECT that you do.
Then on the focus out you can do something along the lines of:
$("#team-logo").attr("src", club_id+".png");
And that will set the image src to the new image.
Edit:
To expand a bit, storing the results of the sql query in a json object using json_encode() would allow you to use something like:
<script>
var clublist = [
<?php
$search_clubs = " SELECT club_id, club_name FROM clubs ";
$result_clubs = mysql_query($search_clubs);
echo json_encode(mysql_fetch_array($result_clubs));
?>
];
</script>
// Run the following code inside the focus.out section and set thisclub to the returned clubname
clubid = "";
$.each(clublist, function (i, elem) {
if (elem.club_name === thisclub) {
clubid = elem.club_id;
$("#team-logo").attr("src", clubid+".png");
}
});
if(clubid == "") {
// show default image
$("#team-logo").attr("src", "0.png");
}
Second Edit (Complete working example):
I've tested the following and I believe it includes everything you're looking for. The problem seemed to be in the formatting of the php array when passed to json encode. Pay close attention to the HTML changes.
$sql = " SELECT club_id, club_name FROM clubs ORDER BY club_id DESC";
$result_clubs = mysql_query($sql);
if (!$result_clubs) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
$clubs = array();
while($row = mysql_fetch_assoc($result_clubs)){
$clubs[] = array('club_id' => $row['club_id'], 'club_name' => $row['club_name']);
}
?>
<img id="team-logo" src="logos/0.png"/>
<input id="clubname" type="text" class="club-name" name="home" autocomplete="off"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script type="text/javascript">
var clubs = [
<?php
foreach($clubs as $club) {
$club_name = $club['club_name'];
echo '"'.$club_name.'",';
}
?>
];
var clublist = <?php echo json_encode($clubs)?>; //only returns one row
$(".club-name").autocomplete({
source: clubs,
autoFocus: true,
minLength: 2,
delay: 0,
close: function(event, ui){
if (!event.keyCode || event.keyCode === 13){
$(this).parents('form').find('.club-name').filter(function (){
return $(this).val() === '';
}).first().focus();
//
}
clubid = "";
for(var i = 0; i < clublist.length; i++) {
obj = clublist[i];
if(obj.club_name == $("#clubname").val()){
clubid = obj.club_id;
$("#team-logo").attr("src", clubid+".png");
}
}
if(clubid == "") {
// show default image
$("#team-logo").attr("src", "0.png");
}
}
});
</script>
we have a form that we can click on a number at the top of the form in order to load the according data, to be more specific i can have 4 inputs in my table in the database and when I click on number 2 which is the id of the data then it loads the data. We did that but now we want to update the clicked data and until now we cant find a way to GET the correct number(id) and place it in the UPDATE statement.
Below is the code of the clicked functions and of the UPDATE statement.
//Education Scripts
$("#updateEdu").click(function () {
$("#idE").css("display", "none");
var r = parseInt($("#idE").val(), 10) + 1;
$("#idE").val(r);
});
$('[data-row-ide]').click(function (e) {
e.preventDefault();
var fileName = 'addCV.php?idEdu='; //"addCV.php" the name of this file in your project, the "?" starts the GET parameters, idWork= sets the key for the GET parameter
var id = $(this).data('row-ide'); // this gets the id that we stored in the link's data attribute
var url = fileName + id; // then we add that id as the value for the "idWork" key
window.location = url; // esentially refresh this page with the id set as a GET parameter and make use of the logic we already have to load the info
});
<?php
$username = $_SESSION["username"];
if(isset($_POST['updateEdu'])){
$parts = parse_url($url);
parse_str($parts['query'], $query);
$id = $query['idEdu'];
$username = $_SESSION['username'];
$school = mysql_real_escape_string($_POST["school"]);
$degree = mysql_real_escape_string($_POST["degree"]);
$website = mysql_real_escape_string($_POST["website"]);
$start_date = mysql_real_escape_string($_POST["start_date"]);
$end_date = mysql_real_escape_string($_POST["end_date"]);
$start_year = mysql_real_escape_string($_POST["start_year"]);
$end_year = mysql_real_escape_string($_POST["end_year"]);
$degree_description = mysql_real_escape_string($_POST["degree_description"]);
if($start_year > $end_year){
echo 'The Start Year must be smaller than the End Year!';
$id=$id-1;
$good = false;
}
else{
$good = true;
}
if($good == true){
$query="UPDATE education
SET school = '$school', degree = '$degree', website = '$website', start_date='$start_date', end_date='$end_date', start_year='$start_year', end_year='$end_year', degree_description='$degree_description'
WHERE id='$id' AND username='$username'";
mysql_query($query)or die(mysql_error());
if(mysql_affected_rows()>0){
echo "<p>Record Updated<p>";
echo "<script type='text/javascript'>;
/window.location='addCV.php';
</script>";
}
else{
echo "<p>Error Updating Record<p>";
echo "<script type='text/javascript'>;
</script>";
}
}
}
else if(isset($_GET['idEdu'])){
// user clicked on one of oue id links to get here
// set the id the the value of the GET parameter for key "idWork"
$id = $_GET['idEdu'];
}
else{
// Formulate Query
// This is the best way to perform an SQL query
// For more examples, see mysql_real_escape_string()
$query = sprintf("SELECT school,degree,website,start_date,end_date,start_year,end_year,degree_description,id FROM education
WHERE username='%s' ORDER BY id LIMIT 1",
mysql_real_escape_string($username));
// Perform Query
$result = mysql_query($query);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(), etc.
while ($row = mysql_fetch_assoc($result)) {
$id = $row['id'];
}
}
To get the value of an elements attribute in jquery you use the attr() function like so:
$(element).attr('attributeName')
So you should change:
var id = $(this).data('row-ide');
into
var id = $(this).attr('row-ide');
in your function $('[data-row-ide]').click(function (e) {};
I want to use AJAX/Javascript with PHP to carry out this following function and not have it all done by PHP itself. I have created a function which deletes an item from the MySQL database. It gives a validation to the user if they want to remove it by selecting Yes or No.
However, how would i change this so that it does the same function but the validation appears as a popupbox, and when Yes or OK is pressed it deletes the item from the database and reloads the page to show it has been removed.
I have provided the PHP code which relates to this function, but i want to specifically change this to using AJAX/Javascript as well in accordance with PHP.
<?php
// Delete Item Question to Admin, and Delete Product if they choose
if (isset($_GET['deleteid'])) {
echo 'Do you really want to delete product with ID of ' . $_GET['deleteid'] . '? Yes | No';
exit();
}
if (isset($_GET['yesdelete'])) {
// remove item from system and delete its picture
// delete from database
$id_to_delete = $_GET['yesdelete'];
$sql = mysqli_query($link,"DELETE FROM products WHERE id='$id_to_delete' LIMIT 1") or die (mysql_error());
// unlink the image from server
// Remove The Pic -------------------------------------------
$pictodelete = ("../inventory_images/$id_to_delete.jpg");
if (file_exists($pictodelete)) {
unlink($pictodelete);
}
header("location: inventory_list.php");
exit();
}
?>
<?php
// This block grabs the whole list for viewing
$product_list = "";
$sql = mysqli_query($link,"SELECT * FROM products ORDER BY date_added DESC");
$productCount = mysqli_num_rows($sql); // count the output amount
if ($productCount > 0) {
while($row = mysqli_fetch_array($sql)){
$id = $row["id"];
$product_name = $row["product_name"];
$price = $row["price"];
$stock = $row["stock"];
$date_added = strftime("%b %d, %Y", strtotime($row["date_added"]));
$product_list .= "Product ID: $id - <strong>$product_name</strong> - £$price - Stock: $stock - <em>Added $date_added</em> <a href='inventory_edit.php?pid=$id'>edit</a> • <a href='inventory_list.php?deleteid=$id'>delete</a><br />";
}
} else {
$product_list = "You have no products listed in your store yet";
}
?>
Your JS-File
$(document).ready(function() {
$('.delete').click(function() {
event.preventDefault();
var deleteId = $(this).parent().attr('id').val();
$.get('path/to/you/phpfile', {deleteId: deleteid}, function(data) {
var confirm = confirm(data);
if (confirm==true) {
$.get('path/to/you/phpfile', {yesdelete: 1});
}
});
});
});
In your PHP-File you have to remove header('Location: ...') and the block which grabs the list, wrap it in a function or etract it to another php file to call it with the a simliar ajax-command I used above. And you have to change th $product_list in the while-loop.
Product ID: <div id="$id">$id - <strong>$product_name</strong> - £$price - Stock: $stock - <em>Added $date_added</em> <a href='inventory_edit.php?pid=$id'>edit</a> • <div class="delete">Delete</div></div><br />
jQuery get the id-value of his parent-div. It´s actually not the best way, but something like this should work.
I can't seem to work this one out. Been a few days and still no progress after re-writing it more times than I can count on my hands.
Here is the Javascript (On same page as html)
Summary: User types text into the input box. That gets sent off to be processed, which then gets sent back and displayed on the screen in the box ID'd as DisplayText on the html page.
<script type="text/javascript">
function SendText() {
if (document.getElementById("Text").innerHTML == "") {
return;
} else
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("DisplayText").innerHTML = xmlhttp.responseText;
}
}
Text = document.getElementById("Text").value;
xmlhttp.open("GET", "php/Test.php?Chat=" + Text, true);
xmlhttp.send();
}
}
</script>
Here is the HTML (Same page as the script)
<div>
<p>
<span id="DisplayText">
TEXT GOES HERE
</span>
</p>
</div>
<form action="" onsubmit="SendText();">
<input type="" name="" id="Text" />
<input type="submit" value="Send" name="Send" />
</form>
The PHP code is here
<?php
session_start();
include ("Connect.php");
$Connection = mysqli_connect("localhost", "root", "", "chatsystem");
$Create = "CREATE TABLE " . $_SESSION["Username"] . "Chat(Username VARCHAR(255), Chat VARCHAR(255))";
////////////////////////////////////////////////////////////////////////////////
$DatabaseExist = $Connection->query("SELECT 1 FROM " . $_SESSION["Username"] . "Chat");
if ($DatabaseExist !== false) {
echo "Database exists";
doSomething();
} else {
echo "Database does not exist";
mysqli_query($Connection, $Create);
doSomething();
}
////////////////////////////////////////////////////////////////////////////////
function doSomething() {
// Get the sent chat
$Input = $_REQUEST["Chat"];
// Insert into the database the new chat sent
mysqli_query($Connection, "INSERT INTO " . $_SESSION["Username"] . "chat (`Username`, `Chat`) VALUES ('$_SESSION[Username], '$Input')");
// Select everything from the database
$Result = $Connection->query("SELECT * FROM " . $_SESSION["Username"] . "Chat");
// Display everything from the database in an orderly fashion
// --
// For the length of the database
// Append to a variable the next table row
// --
while ($Row = $Result->fetch_array()) {
// Make Variable accessable
global $Input;
// Append username to the return value
$Input = $Input . $Row["Username"] . " : ";
// Append chat to the return value
$Input = $Input . $Row["Chat"] . "<br />";
}
}
// Will return the value
echo $Input;
?>
My connection to the Database is fine. I'm using it on other pages that work.
So lets assume that's not the problem. :P
Any help or insight from anyone who knows or can think of something that is wrong, I would be very grateful for.
I'm new to AJAX.
You do a wrong test with
if (document.getElementById("Text").innerHTML == "")
It should be the same way you use to get the text for sending in the AJAX
if (document.getElementById("Text").value == "")
So check its value property and not its innerHTML as input elements do not have html content..
Be careful though because your code is wide-open to SQL injection attacks.
1st : use input's value property instead innerHTML
eg. use
if (document.getElementById("Text").value == "")
instead of
if (document.getElementById("Text").innerHTML == "")
2nd : use return false; at the form's onsubmit event; to prevent current page to be refreshed as you are using ajax. Otherwise the page will get refreshed and it wont display the php page's output,
eg. use
onsubmit="SendText(); return false;"
instead of just
onsubmit="SendText();"
Try AJAX Long Polling technique for chat application. Here is example
http://portal.bluejack.binus.ac.id/tutorials/webchatapplicationusinglong-pollingtechnologywithphpandajax