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;
}
Related
I used tutorialspoint to guide me to insert the values from input text into the db, but unfortunately, it will not insert to the database. Is this correct implementation for AJAX?
Here's my index.php
<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;
}
}
}
// Create a function that will receive data
// sent from the server and will update
// div section in the same page.
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
// Now get the value from user and pass it to
// server script.
var fname = document.getElementById('fname').value;
var lname = document.getElementById('lname').value;
var gen = document.getElementById('gen').value;
// var queryString = "?age=" + age ;
queryString += "&fname=" + fname + "&lname=" + lname+ "&gen=" + gen;
ajaxRequest.open("GET", "ajax.php" + queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
<form name='myForm'>
First Name: <input type='text' id='fname' /> <br />
Last Name: <input type='text' id='lname' /> <br />
Sex:
<select id='gen'>
<option value="m">m</option>
<option value="f">f</option>
</select>
<input type='button' onclick='ajaxFunction()' value='Query MySQL'/>
</form>
<div id='ajaxDiv'>Your result will display here</div>
</body>
</html>
ajax.php
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "my_db";
$con = new mysqli($dbhost, $dbuser, $dbpass,$dbname);
$query="INSERT INTO table1 (fname, lname, gender)
VALUES
('$_GET[fname]','$_GET[lname]','$_GET[gen]')";
$qry_result = $con->query($query);
?>
change your code to the bellow
var queryString;
queryString = "fname=" + fname + "&lname=" + lname+ "&gen=" + gen;
ajaxRequest.open("GET", "ajax.php?" + queryString, true);
and make sure ajax.php is in the same folder as index.php
Try this in ajax.php:
$fname=$_GET['fname'];
$lname=$_GET['lname'];
$gen=$_GET['gen'];
$query="INSERT INTO table1 ('fname', 'lname', 'gender')
VALUES('$fname','$lname','$gen')";
Declare Form method="POST"
and
$query="INSERT INTO table1 (fname, lname, gender) VALUES
('".$_POST['fname']."','".$_POST['lname']."','".$_POST['gen']."')";
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 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.
I was looking around for a ajax script which could populate triple drop down list using PHP. And I came across this piece of code although the code works pretty well I would like to know what is actually happening behind the scene, as I am a newbie to AJAX or JavaScript I am unable to understand what does the below function exactly do. Here is the code:
<script language="javascript" type="text/javascript">
function getXMLHTTP() { //function to return the xml http object
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getState(countryId) {
var strURL="findState.php?country="+countryId;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('statediv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
function getCity(stateId) {
var strURL="findCity.php?state="+stateId;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('citydiv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
and here is the code from finsState.php
<?php
$countryId=intval($_GET['country']);
$host = "localhost";
$username = "username";
$password = "password";
$database = "test";
$connection = mysql_connect($host,$username,$password) or die(mysql_error());
$database = mysql_select_db($database) or die(mysql_error());
$query = "SELECT * FROM states WHERE country_id = ".$countryId;
$result = mysql_query($query) or die(mysql_error());
?>
<select name="states" onchange="getCity(this.value)">
<option>Select State</option>
<?php while($row = mysql_fetch_array($result)) { ?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['name']; ?></option>
<?php } ?>
</select>
and this is findCity.php
<?php
$stateId=intval($_GET['state']);
$host = "localhost";
$username = "username";
$password = "password";
$database = "test";
$connection = mysql_connect($host,$username,$password) or die(mysql_error());
$database = mysql_select_db($database) or die(mysql_error());
$query = "SELECT * FROM cities WHERE state_id = ".$stateId;
$result = mysql_query($query) or die(mysql_error());
?>
<select name="city">
<option>Select City</option>
<?php while($row = mysql_fetch_array($result)) { ?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['name']; ?> </option>
<?php } ?>
</select>
My questions :
a) Can anyone please summarize the first, second and third javascript function and how does it select all the values from findState.php and findCity.php
b) If I was to catch the value of the stateId and CityId the user selected how do i do it. as because the list is populated from JavaScript I am unable to catch the value from PHP ($_POST['state']).
The first function is attempting to open up and XML HTTP request, allowing the clients-side scripts to interact with server-size scripts. Since various browsers handle that differently, it trys to use the standard method before attempting a modern IE implementation, an older IE implementation and finally giving up.
The second two do roughly the same thing. They define the script they wish to interact with an use the first function to connect. If the connection was successful, it sends over the information using an HTTP GET request (traditionally GET is used for getting information, POST is used for setting it).
When information is sent using XmlHttpRequest, the onreadystatechange event fires at key points during the connection and gives access to the readyState (referring to how the stage of the request) and the status which is a standard server response (you're probably familiar with "404" meaning "file not found"). A "200" status means "everything is fine", so when that is received the script knows it can act on the information it was given. Any other response will create a popup that tells the user what went wrong.
Without seeing the actual page this script interacts with, I don't know the best way to get stateId and CityId. At a guess, they will be the value of an input when a certain button is pressed. If that's the case, something like the following piece of code would do it:
document.getElementById('id-of-submit-button').onclick = function() {
var stateId = document.getElementById('id-of-stateid-input').value,
CityId = document.getElementById('id of cityid-input').value;
};
I want to call a javascript function with parametars that are stored in MySQL. All this is happening on an onClick event.
Here is the javascript code:
function getFile() {
if (window.XMLHttpRequest) {
AJAX=new XMLHttpRequest();
} else {
AJAX=new ActiveXObject("Microsoft.XMLHTTP");
}
if (AJAX) {
AJAX.open("POST", "gmap.php", false);
AJAX.send("searchField=" + searchField.value);
return load(AJAX.responseText);
} else {
return false;
}
}
So, the gmap.php is echoing the parameters for the javascript load function. But it doesn't load the parameter because the function is called before the MySQL query in gmap.php is executed. I've tried sync and async AJAX.
If I try to call the javascript function from PHP, it doesn't get executed, because it is called on a onClick event, and this is inside a div.
Please help me, I'm doing this over a week now. I've tried everything.
Here is the php code with the MySQL query:
<?php
header( 'Content-Type: text/html; charset=UTF-8' );
mb_internal_encoding( 'UTF-8' );
$a = $_POST['searchField'];
$dbhost = "localhost";
$dbuser = "*******";
$dbpass = "*******";
$dbname = "citydb";
//connect sql
mysql_connect($dbhost, $dbuser, $dbpass);
//select db
mysql_select_db($dbname) or die(mysql_error());
//retrieve data
//$city=$_GET['city'];
//escape user input to help prevent SQL injection
//$city=mysql_real_escape_string($city);
//query
mysql_query('SET CHARACTER SET utf8');
$result=mysql_query("SELECT citystart, cityend FROM cityids WHERE city='$a' ");
if(!result) {
die("Database query failed: " . myql_error());
}
while($row=mysql_fetch_array($result)) {
$lat=$row['citystart'];
$lng=$row['cityend'];
}
echo $lat;
echo ", ";
echo $lng;
?>
pass the php url together with the variable to search.
if (AJAX) {
var url = "gmap.php?searchField="+ searchField.value;
AJAX.open("POST", "url", false);
AJAX.send(true);
return load(AJAX.responseText);
}
I think searchField.value does not contain anything.
Replace
searchField.value
With this
document.getElementById('searchField').value
assign the searchField as an id to the search box.
add this code after AJAX.open and before AJAX.send.
AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
AJAX.setRequestHeader("Content-length", searchField.value.length);
AJAX.setRequestHeader("Connection", "close");
I have succesfully tested this
<html>
<head>
<script>
function load(response) {
alert(response);
}
function getFile() {
if (window.XMLHttpRequest) AJAX=new XMLHttpRequest();
else AJAX=new ActiveXObject("Microsoft.XMLHTTP");
if (AJAX) {
var params = "foo=" + searchField.value;
AJAX.open("POST", "http://localhost/test.php", true);
AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
AJAX.setRequestHeader("Content-length", params.length);
AJAX.setRequestHeader("Connection", "close");
AJAX.onreadystatechange = function() {
var ok;
try { ok=AJAX.readyState; } catch(e) { }
if(ok==4) load(AJAX.responseText);
}
AJAX.send(params);
}
}
</script>
</head>
<body>
<input type="text" id="searchField"/>
<input type="button" onclick="getFile()"/>
<script>
searchField = document.getElementById("searchField");
</script>
</body>
</html>