I have 2 pages
The first page for calling a second page to get all records from database, like this:
<script language="JavaScript">
var HttPRequest = false;
function doCallAjax(Mode,users_ID) {
HttPRequest = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
HttPRequest = new XMLHttpRequest();
if (HttPRequest.overrideMimeType) {
HttPRequest.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
try {
HttPRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
HttPRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!HttPRequest) {
alert('Cannot create XMLHTTP instance');
return false;
}
var url = 'AjaxDeleteRecord.php';
var pmeters = "tMode=" + Mode +
"&tusers_ID=" + users_ID;
HttPRequest.open('POST',url,true);
HttPRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
HttPRequest.setRequestHeader("Content-length", pmeters.length);
HttPRequest.setRequestHeader("Connection", "close");
HttPRequest.send(pmeters);
HttPRequest.onreadystatechange = function()
{
if(HttPRequest.readyState == 3) // Loading Request
{
document.getElementById("mySpan").innerHTML = "Now is Loading...";
}
if(HttPRequest.readyState == 4) // Return Request
{
document.getElementById("mySpan").innerHTML = HttPRequest.responseText;
}
}
}
</script>
<body Onload="JavaScript:doCallAjax('LIST','');">
<form name="frmMain">
<div style="margin-right:10px">
<span id="mySpan"></span>
</div>
and the second page is php that fetches data:
$strMode = $_POST["tMode"];
$users_ID = $_POST["tusers_ID"];
if($strMode == "DELETE")
{
//$strSQL = "DELETE FROM users , stores WHERE users.users_StoreId=stores.stores_ID AND users.users_ID = '".$users_ID."'";
$strSQL = "update users set users_delete='1' where users.users_ID = '".$users_ID."'";
$objQuery = mysql_query($strSQL) or die (mysql_error());
}
$strSQL = "SELECT * FROM users , stores WHERE users.users_StoreId=stores.stores_ID and users.users_delete='0' ORDER BY stores.stores_Name , users.users_Type ASC ";
$objQuery = mysql_query($strSQL) or die ("Error Query [".$strSQL."]");
The problem that I cannot make paging work for this.
Can any one help me?
Use Google's Visualization API's
table chart
Visualization: Table.
It will automatically enable paging as per your count like 10 or 20 and sorting your content ascending or descending on the basis of column.
Related
I found an example that does exactly what I am after. My only issue is that this syntax calls a secondary file of book-suggestion.php If possible, I would like a way of performing all of this function in one page.
Here is step 1 - the client side
function book_suggestion()
{
var book = document.getElementById("book").value;
var xhr;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "book_name=" + book;
xhr.open("POST", "book-suggestion.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data);
xhr.onreadystatechange = display_data;
function display_data() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
//alert(xhr.responseText);
document.getElementById("suggestion").innerHTML = xhr.responseText;
} else {
alert('There was a problem with the request.');
}
}
}
}
And here is part 2 - the server side
<?php
//provide your hostname, username and dbname
$host="";
$username="";
$password="";
$db_name="";
//$con=mysql_connect("$host", "$username", "$password")or die("cannot connect");
$con=mysql_connect("$host", "$username", "$password");
mysql_select_db("$db_name");
$book_name = $_POST['book_name'];
$sql = "select book_name from book_mast where book_name LIKE '$book_name%'";
$result = mysql_query($sql);
while($row=mysql_fetch_array($result))
{
echo "<p>".$row['book_name']."</p>";
}
?>
What do I need to do to combine these parts so that they are all in one file?
You could do it all one page, I use a .htaccess rewrite where everything is funneled through just one index page, so essentially doing the same thing. You just do the php above the output of your html and exit when done:
/index.php
<?php
# Create some defines
define('DB_HOST','localhost');
define('DB_NAME','database');
define('DB_USER','root');
define('DB_PASS','');
# Create a PDO connection, mysql_* is out of date and unsafe
# Review PDO, there are some presets to the connection that should be explored
# like emulated prepares and other such niceties
$con = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME,DB_USER,DB_PASS);
# If there is a value posted, do action
if(!empty($_POST['book_name'])) {
# Bind parameters
$sql = "select book_name from book_mast where book_name LIKE ?";
$query = $con->prepare($sql);
$query->execute(array($book_name.'%'));
# Fetch normally
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
echo "<p>".$row['book_name']."</p>";
}
##*****THE IMPORTANT PART ******##
# Stop so you don't process the rest of the page in the ajax
exit;
}
?>
<!-- THE REST OF YOUR HTML HERE -->
<script>
function book_suggestion()
{
var book = document.getElementById("book").value;
var xhr;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "book_name=" + book;
xhr.open("POST", "index.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data);
xhr.onreadystatechange = display_data;
function display_data() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
//alert(xhr.responseText);
document.getElementById("suggestion").innerHTML = xhr.responseText;
} else {
alert('There was a problem with the request.');
}
}
}
}
</script>
I am trying to calculate the sum of prices sold between two specific dates. My query is okay but it isn't returning anything when i use in PHP. It works when i directly execute in database.
Here is my code,
<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 went wrong
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var startdate = document.getElementById('startdate').value;
var enddate = document.getElementById('enddate').value;
var queryString = "?startdate=" + startdate ;
queryString += "&enddate=" + enddate;
ajaxRequest.open("GET", "ajax-example.php" + queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
<form name='myForm'>
Start Date: <input type='date' id='startdate' /> <br />
End Date: <input type='date' id='enddate' /> <br />
<input type='button' onclick='ajaxFunction()' value='Query MySQL'/>
</form>
<div id='ajaxDiv'>Your result will display here</div>
</body>
</html>
Here is my PHP Code
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "temp";
//Connect to MySQL Server
mysql_connect($dbhost, $dbuser, $dbpass);
//Select Database
mysql_select_db($dbname) or die(mysql_error());
// Retrieve data from Query String
$startdate = $_GET['startdate'];
$enddate = $_GET['enddate'];
//build query
$query = "SELECT SUM(price) FROM ajax_example WHERE daterec >= '$startdate'";
$query .= " AND daterec <= '$enddate'";
//Execute query
$qry_result = mysql_query($query) or die(mysql_error());
echo "Query: " . $query . "<br />";
?>
What am i doing wrong? Thank you in advance
Satisj Rajak! you are right!
check mysql_query
first, this function will be deprecated after PHP 5.5.0, try to dont use it.
second, to get the results you have "transform" the variable in an associative array using this example code:
while ($row = mysql_fetch_assoc($result)) {
echo $row['field_name'];
}
and if you use ajax, try to send a json format response.
hope my answer help you.
In your button click handler, try returning false. My first instinct would be that your form is being submitted by that button and your AJAX request is never being completed.
<input type='button' onclick='ajaxFunction(); return false;' value='Query MySQL'/>
If that doesn't solve it, open up google chrome and the network debugging tools. When you execute the AJAX request, check the request and response data.
In addition, you should optimize your JavaScript to be more effective.
Here is a snippet of JS which could be used in your situation:
var get = function(path) {
return new Promise(function(resolve, reject) {
var request = new XMLHttpRequest();
request.open('GET', path);
request.onload = function() {
if (request.status == 200)
resolve(request.response);
else
reject(Error(request.statusText));
};
request.onerror = function() {
reject(Error(request.statusText));
};
request.send();
});
}
function fetchQueryResults() {
get('/test.php').then(function(response) {
var el = document.getElementById('results');
el.innerHTML = response;
}).catch(function(error) {
// Something went wrong, handle the error here
});
return false;
}
this code is to autosave form in mysql database
i am unable to send multiple parameters
the main issue is here
var saved_text = document.getElementById("saved_text").value;
var content = document.getElementByID("test").value;
var params = "saved_text="+saved_text+"content="+content;
php code
<?php
$user_id = 1;
if($_SERVER["REQUEST_METHOD"]=="POST")
{
$saved_text = mysql_real_escape_string($_POST["saved_text"]);
$sql = "UPDATE asave SET saved_text = '".$saved_text."' ";
$sql.= "WHERE user_id = $user_id";
mysql_query($sql) or die(mysql_error().$sql);
echo "Your data has been saved ".date("h:m:s A");
exit;
}
$sql = "SELECT saved_text FROM asave WHERE user_id = $user_id";
$rs = mysql_query($sql) or die(mysql_error().$sql);
$arr = mysql_fetch_array($rs);
$saved_text = $arr["saved_text"];
?>
html code
<html>
<head>
<script type="text/javascript">
function init(){
window.setInterval(autoSave,10000); // 10 seconds
}
function autoSave(){
var saved_text = document.getElementById("saved_text").value;
var content = document.getElementByID("test").value;
var params = "saved_text="+saved_text+"content="+content;
var http = getHTTPObject();
http.onreadystatechange = function(){
if(http.readyState==4 && http.status==200){
msg = document.getElementById("msg");
msg.innerHTML = "<span onclick='this.style.display=\"none\";'>"+http.responseText+" (<u>close</u>)</span>";
}
};
http.open("POST", window.location.href, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.send(params);
}
//cross-browser xmlHTTP getter
function getHTTPObject() {
var xmlhttp;
/*#cc_on
#if (#_jscript_version >= 5)
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (E) {
xmlhttp = false;
}
}
#else
xmlhttp = false;
#end #*/
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}
</script>
</head>
<body onload="init();">
<span id="msg" style="cursor:pointer;"></span>
<form method="POST">
<textarea id="saved_text" name="saved_text" rows="10" cols="100"><?PHP echo $saved_text;?></textarea>
<br/>
<input id="test" type="text" value="<?php echo $content;?>">
<input type="submit" value="save now" />
</form>
</body>
You're not posting saved_text in your javascript. You're posting params (that is missing a delimiter).
To post multiple parameters check this post: Posting parameters to a url using the POST method without using a form
I am having an issue with my AJAX and MySQL/PHP script.
The first file below, is my javascript file I use to test accessing my server. This file works as far as I know and have tested.
Game = function() {};
var timer;
Game.EncodeURI = function (text) {
return encodeURIComponent(text);
}
Game.DecodeURI = function (text) {
return decodeURIComponent(text);
}
Game.AlterDiv = function(div,data) {
if (Game.ID(div)) {
Game.ID(div).innerHTML = data;
}
}
Game.ID = function(value) {
return document.getElementById(value);
}
Game.ServerRequest = function (url, data) {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest(); // code for IE7+, Firefox, Chrome, Opera, Safari
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
data = xmlhttp.responseText.split("|");
for (i = 0; i < data.length; i++){
var one = Game.DecodeURI(data[parseInt(i)]);
var two = Game.DecodeURI(data[parseInt(i) + 1]);
var three = Game.DecodeURI(data[parseInt(i) + 2]);
var four = Game.DecodeURI(data[parseInt(i) + 3]);
var five = Game.DecodeURI(data[parseInt(i) + 4]);
}
} else {
return false;
}
}
if (!data) {
data = "";
}
data = data.replace(/: /gi, "=");
data = data.replace(/:/gi, "=");
data = data.replace(/, /gi, "&");
data = data.replace(/,/gi, "&");
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(data);
}
Game.Action = function (id, seconds) {
clearTimeout(timer);
if (id) {
if (!seconds) {
Game.AlterDiv('message', 'You begin working.');
Game.ServerRequest("action.php", "id: " + id);
} else {
Game.AlterDiv('message', 'You begin working.');
Game.ID('timer').innerHTML = seconds;
if (seconds >= 2) {
seconds -= 1;
Game.ID('timer').innerHTML = seconds;
timer = setTimeout(function(){
Game.Action(id, seconds);
},1000);
} else {
Game.ID('timer').innerHTML = "Finished";
Game.ServerRequest("action.php", "id: " + id + ", x: x"); // Request it, then POST "x" to say timer has counted down.
}
}
} else {
alert("There was an error with your request.\n Please try again.");
}
}
This second file is a basic PHP web page that I use to test the said function.
<html>
<head>
<title>Test</title>
</head>
<body>
<span onClick="Game.Action('1','5');">Start Work</span><br /><br />
<div id="message"></div>
<div id="timer"></div>
</body>
</html>
<script type="text/javascript" src="game.js?<?php echo time(); ?>"></script><!-- the time() stops it cache-ing -->
This third file is my PHP/MYSQL file that I use to connect to the database.
<?php
$mysqli = new mysqli_connect("127.0.0.1", "root", "", "gurstang");
$id = $_POST['id'];
if(isset($_POST['x'])) {
$x = true;
}else{
$x = false;
}
$userid = 1;
$query = "SELECT * FROM `action_info` WHERE `actionid` = '$id'";
if($result = $mysqli->query($query)){
while ($row = $result->fetch_assoc()) {
$action_name = $row['name'];
$basetimer = $row['time'];
$gaineditem = $row['itemid'];
}
$result->free();
}
$query = "SELECT `item`,`plural` FROM `items` WHERE `itemid` = '$gaineditem' LIMIT 0,1";
if($result = $mysqli->query($query)){
while($row = $result->fetch_assoc()){
$gained_item = $row['item'];
$gained_plural = $row['plural'];
}
$result->free();
}
if($x == false){
echo "Action|$id|"5"";
$message = "You have begun working.";
echo "AlterDiv|message|$message";
}
if($x == true){
echo "Action|$id|"5"";
$itemnumber = mt_rand(1,2);
$gainedmessage = "You have gained $itemnumner $gained_item.";
echo "AlterDiv|message|$gainedmessage";
$query = "SELECT `count` FROM inventory WHERE userid = '$userid' AND itemid = '$gaineditem' LIMIT 0,1";
if($result = $mysqli->query($query)){
while($row = $result->fetch_assoc()){
$count = $row['count'];
$add = $count + $itemnumber;
$updatequery = "UPDATE `inventory` SET `count` = '$add' WHERE `userid` = '$userid' AND `itemid` = '$gaineditem'";
$mysqli->query($updatequery);
}
}
else{
$insertquery = "INSERT INTO `inventory` (`userid`, `itemid` ,`count`) VALUES ('$userid', '$gaineditem', '1')";
$mysqli->query($insertquery);
}
}
?>
Those are all 3 of the file currently to run my script. I have an onclick event in the php webpage, and it sends the values to my Javascript function of Game.Action. After testing I have concluded or at least assume that my Javascript function for Game.Action works. After testing my Game.ServerRequest function, I have concluded that there is a change somewhere happening. Although, when I check my server to see if the updates actually happened, nothing happens. It doesn't update the timer div or the message div properly.
So basically my question is, is my issue with PHP/MYSQL or AJAX?
Thanks for your help.
I have one simple html form where the fields can be auto populated by entering ID. its working fine. but, if ID not found in database, it can only return null to the form fields. i was trying to display an error message (can be a pop-up window) saying ID not found! but i failed to do it. here is my code to echo info into the form field:
if (strlen($param) > 0) {
$result = mysql_query("SELECT * FROM contact
WHERE contactid LIKE '$param%'");
if (mysql_num_rows($result) == 1) {
while ($myrow = mysql_fetch_array($result)) {
$agentname = $myrow["contactfullname"];
$agenttel = $myrow["contacttel"];
$agentsal = $myrow["contactsalutation"];
$agentid = $myrow["contactid"];
$textout .= $agentid . ", " . $agentname . ", " . $agenttel . ", " . $agentsal;
}
} else {
$textout = " , , ," . $param;
}
}
echo $textout;
here is my ajaxFunction:
function ajaxFunction(e){
var e=e || window.event;
var keycode=e.which || e.keyCode;
if(keycode==13 || (e.target||e.srcElement).value==''){
var http; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
http = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
http = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
http = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
var url = "getagentids.php?param=";
var idValue = document.getElementById("agid").value;
var myRandom = parseInt(Math.random()*99999999); // cache buster
http.open("GET", "getagentids.php?param=" + escape(idValue) + "&rand=" + myRandom, true);
http.onreadystatechange = handleHttpResponse;
http.send(null);
function handleHttpResponse() {
if (http.readyState == 4) {
results = http.responseText.split(",");
document.getElementById('agfn').value = results[0];
document.getElementById('agsal').value = results[1];
document.getElementById('agtel').value = results[2];
document.getElementById('agid').value = results[3];
}
}
}
}
Dont use mysql_* functions, use PDO or Mysqli instead.
take care about $param value
If your query should return 1 result, you can use LIMIT 1 , and also there is no need to use while.
change this :
$result = mysql_query("SELECT * FROM contact
WHERE contactid LIKE '$param%'");
if (mysql_num_rows($result) == 1) {
while ($myrow = mysql_fetch_array($result)) {
to
$result = mysql_query("SELECT * FROM contact
WHERE contactid LIKE '$escaped_param%' LIMIT 1");
if (mysql_num_rows($result) == 1) {
$myrow = mysql_fetch_array($result);
4. if you want to show a message on your ajax response, you can use json or .... as an simple example, return this string on error :
error|" , , ," . $param;
and to check if an error occured on your client :
var result = "error|anything";
if(result.substr(0,6) == 'error|')
{
alert('An error occured.');
}
else
{
//do what you need!
}
Edit :
function handleHttpResponse()
{
if (http.readyState == 4)
{
results = http.responseText;
if(results.substr(0,6) == 'error|')
{
alert('An error occured.');
}
else
{
results = results.split(",");
document.getElementById('agfn').value = results[0];
document.getElementById('agsal').value = results[1];
document.getElementById('agtel').value = results[2];
document.getElementById('agid').value = results[3];
}
}
}
try do this in your sql
LIKE '%" . $param . "%'