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>
Related
I am new to AJAX and am trying to insert form data into a database using ajax and php. It is simply not working, I had errors to start off but now there are no more errors and the database doesn't update and there is no response text. Please Help!
AJAX
function submit(){
var vid = <?php echo $user['vid'] ?>;
var type = document.getElementById("type").value;
var rules = document.getElementById("rules").value;
var comments = document.getElementById("comments").value;
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("page").innerHTML = xhttp.responseText;
}
}
xhttp.open("POST", "/content/training/request/submit.php", false);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("vid="+vid+"&type="+type+"&rules="+rules+"&comments="+comments);
}
</script>
PHP FILE AJAX IS CALLING:
<?php
require("http://".$_SERVER["HTTP_HOST"]."/config/db.php");
$stmt = $db->prepare("INSERT INTO trainingRequests (vid, type, rules, comments, timeSubmitted) VALUES (:vid,:type,:rules,:comments,:timeSubmitted)");
$stmt->bindParam(':vid', $vid);
$stmt->bindParam(':type', $type);
$stmt->bindParam(':rules', $rules);
$stmt->bindParam(':comments', $comments);
$stmt->bindParam(':timeSubmitted', $time);
$vid = $_POST["vid"];
$type = $_POST["type"];
$rules = $_POST["rules"];
$comments = $_POST["comments"];
$time = time();
$stmt->execute();
echo "Submitted!";
Don't use an HTTP URL in require. When you access the PHP script through the webserver, it runs the script (in another server instance, so it doesn't affect the current script), it doesn't return the script contents. Change it to:
require("../../config/db.php");
When I am trying to populate my dropdown menu with ajax I am not able to get the desired values into the dropdown menu.
Could you tell me where the mistake is? The accno returned from php is json array to be filled in the drop down menu.
function showACC(str)
{
if (str == "")
{
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)
{
var doc = window.document.createElement("doc");
var myarray = JSON.parse($source);
var dropdown = document.getElementById("DropdownList");
for (var i = 0; i < myArray.length; ++i) {
dropdown[dropdown.length] = new Option(myArray[i], myArray[i]);
}
}
}
xmlhttp.open("GET","data.php?q="+str,true);
xmlhttp.send();
}
}}
<?php
/*
Connecting to the database
*/
$dbuser = 'root';
$dbpass = 'neel';
$host = 'localhost';
$db = 'library';
mysql_connect($host, $dbuser, $dbpass) or die(mysql_error());
mysql_select_db($db) or die(mysql_error());
/*
Executing SQL query
*/
$queryResult = mysql_query('SELECT acc_no FROM lib_iss_ret where stu_id="07751a1035"') or die(mysql_error());
$source = array();
/*
Building the source string
*/
while ($row = mysql_fetch_array($queryResult)) {
array_push($source, $row['acc_no']);
}
/*
Printing the source string
*/
echo json_encode($source);
?>
Problem is that, I suppose, you think that php variable $source is available in your javascript with the same name. This is a mistake. PHP knows nothing about javascript.
Response from server comes as a responseText property of xmlhttp object. So you should parse xmlhttp.responseText instead of $source:
var myarray = JSON.parse(xmlhttp.responseText);
To check what you get you could use alert or console.log with developers console.
I am trying to retrieve a value from a database through ajax and php.
The ajax code is as follows:
<script>
$(document).ready(function() {
$("#buyprice").change(function() {
if ($("#sname").val() == "") {
alert("Enter Stock name.");
} else {
var sn = $("#sname").val();
alert(sn);
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var x = xmlhttp.responseText;
};
};
xmlhttp.open("GET", "getstockprice.php?q="+sn, true);
xmlhttp.send();
alert("here");
};
alert("here");
var bp = $("#buyprice").val();
alert(bp);
alert(x.val());
if(bp>(1.1*x)||bp<(1.1*x)){
alert("Price violating 10% constraint.");
}
alert("here");
});
});
</script>
The php page is as follows:
<?php
$q = $_GET['q'];
$con = mysqli_connect('localhost','root','','stock_market');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT stock_price FROM live_prices WHERE stock_name = '".$q."'";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result);
mysqli_close($con);
?>
Can someone please tell me where I am going wrong.
you should use echo or return to return something from php.
<script>
$(document).ready(function() {
$("#buyprice").change(function() {
if ($("#sname").val() == "") {
alert("Enter Stock name.");
} else {
var sn = $("#sname").val();
alert(sn);
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var x = xmlhttp.responseText;
};
};
xmlhttp.open("GET", "getstockprice.php?q="+sn, true);
xmlhttp.send();
alert("here");
};
alert("here");
var bp = $("#buyprice").val();
alert(bp);
alert(x);
if(bp>(1.1*x)||bp<(1.1*x)){
alert("Price violating 10% constraint.");
}
alert("here");
});
});
</script>
PHP
<?php
$q = $_GET['q'];
$con = mysqli_connect('localhost','root','','stock_market');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT stock_price FROM live_prices WHERE stock_name = '".$q."'";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result);
mysqli_close($con);
echo $row['stock_price'];
?>
The php script needs to echo the value. This does not display the value on your page, it merely makes the value avalailble to the javascript.
I would suggest using jquery and use the built in ajax functionality. This works much easier.
See the jquery ajax page, and an example straight from there:
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
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 have tried a lot but I have not been able to find out what is wrong with this function to save two values into database. It has been working fine for another function to save one value. It behaves very strange here. Sometimes send 'parent' value & sometimes stop sending it but never send msg value. Here is function. It works fine for one input i.e. parent but problems start with the addition of 2nd input.
<script>
function ADDLISITEM(form)
{
var parent = form.txtInput.value;
var msg = form.msgInput.value;
form.txtInput.value = "";
form.msgInput.value = "";
var url = "send_mysql.php"
var request = null;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
request=new XMLHttpRequest();
}
else
{// code for IE6, IE5
request=new ActiveXObject("Microsoft.XMLHTTP");
}
request.open("POST", url, true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.setRequestHeader("Connection", "close");
request.onreadystatechange = function(){
if (request.readyState == 4) {
if (request.status == 200) {
//alert('POST');
} else {
alert(request.status); // fails here
}
}
}
request.send("parent=" + encodeURIComponent(parent).replace(/%20/g, '+')+"&msg=" +
encodeURIComponent(msg).replace(/%20/g, '+'));
}
</script>
This is send.php
$username = "babar";
$password = "k4541616";
$hostname = "localhost";
$dbh = mysql_connect($hostname, $username, $password) or die("Unable to connect
to MySQL");
$selected = mysql_select_db("spec",$dbh) or die("Could not select first_test");
//die(var_export($_POST,TRUE));
$parent = $_POST['parent'];
$msg = $_POST['msg'];
$name = 'Akhtar Nutt';
//$parent2 = json_decode($parent);
$msg_ID = '2q7b2sfwwe';
//$msg2 = json_decode($msg);
$query = "INSERT INTO msg2_Qualities(id,name,msg,msg_id,parent) VALUES
('','$name','$msg','$msg_ID','$parent')";
if(!mysql_query($query, $dbh))
{die('error:' .mysql_error())
;}
?>
Alter
request.send("parent=" + encodeURIComponent(parent).replace(/%20/g, '+')+"msg=" + encodeURIComponent(msg).replace(/%20/g, '+'));
to:
request.send("parent=" + encodeURIComponent(parent).replace(/%20/g, '+')+"&msg=" + encodeURIComponent(msg).replace(/%20/g, '+'));
You're missing the argument separator & in your query string...
You also might want to refrain from using values in $_REQUEST as they aren't reliable. If your script expects data from a POST then retrieve these values from $_POST.