PHP page not returning value - php

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 );
});

Related

Generating new id each time button is clicked

I am working on a reservation system where I need to generate a unique id for each reservation and display it on the form inside the modal when the user clicks on "Add new reservation"
I used ajax and SQL to do that however sometimes I get duplicates of ids. What I do is each time the button is clicked I insert the id into a table and
That's is my code
<script>
function showId() {
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 (this.readyState==4 && this.status==200) {
document.getElementById("show-id").defaultValue=this.responseText;
}
}
xmlhttp.open("GET","getid.php?=",true);
xmlhttp.send();
}
</script>
<script>
$(function () {
$('#openModal').on('click', function () {
showId();
var mx_val=$("#show-idi").val();
$.ajax({
type: "POST",
url: "insert-id.php",
data: {mx_val:mx_val},
dataType: "JSON",
success: function(data) {
/* $("#message").html(data); */
getDu();
/* $("p").addClass("alert alert-success");*/
},
error: function(err) {
$("#message").html("Saved!");
$("p").addClass("alert alert-success");
console.log(err);
}
});
});
});
</script>
insert-id.php
<?php
include('db.php');
$mx_val=$_POST['mx_val'];
require_once("dbcontroller.php");
$db_handle = new DBController();
$query ='SELECT max(mx_val) from mxvalue';
$results = $db_handle->runQuery($query);
foreach($results as $references) {
$maxvalue = $references["max(mx_val)"] +1;
}
$stmt = $DBcon->prepare("INSERT INTO mxvalue (mx_val) VALUES ('$maxvalue')");
if($stmt->execute())
{
$res="Data Inserted Successfully:";
echo json_encode($res);
}
else {
$error="Not Inserted,Some Problem occured.";
echo json_encode($error);
}
getid.php
<?php
$con = mysqli_connect('','','','');
if (!$con) { die('Could not connect: ' . mysqli_error($con));
} mysqli_select_db($con,"ajax_demo");
$sql="SELECT max(mx_val) from mxvalue";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
$maxid = $row["max(mx_val)"] +1;
?><?php echo $maxid; ?><?php } mysqli_close($con);
?>
You can either use ids based on unix timestamp mixed with some random number, or use a uuid generator Like:
https://github.com/ramsey/uuid
By this two ways you will not get duplicate ids ever

MySQL query result doesn't show using AJAX

I have a database called opera_house with a table called room that has a field room_name and a field capacity. I want to show the room_name 's that have a capacity larger than the one entered by the user.
The Available Room text disappears, but my code only shows the MySQL query if I echo it, but I'm not sure if it is reaching to search the database.
This is my script code:
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
function showRoom(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 (this.readyState === 4 && this.status === 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","ajax_events.php?q="+str,true);
xmlhttp.send();
}
}
This is my html:
<body>
<form>
<input type="text" name="room" onkeyup="showRoom(this.value)">
</form>
<br>
<div id="txtHint"><b>Available Room...</b></div>
</body>
This is my php:
<?php
include('dbconnect.php');
$q = intval($_GET['q']);
mysqli_select_db($connection,"opera_house");
$sql="SELECT room_name FROM room WHERE capacity >= '".$q."'";
echo $sql;
$result = mysqli_query($connection,$sql);
while($row = mysqli_fetch_array($result)) {
echo "<td>" . $row['room_name'] . "</td>";
}
?>
My php file is called ajax_events.php
And my dbconnect.php is one that I constantly use to connect to this database.
Would really appreciate some help!!
I propose an answer using jquery. You've embedded it in your question but you're not using it ...
Explanations : You call the following url ajax_events.php with the parameter "q" only if str is defined, otherwise it fills the selector txtHint with nothing.
AJAX
if (str != "") {
$.ajax({
type: 'GET',
url: 'ajax_events.php',
dataType: 'JSON',
data : {
q: str
}
}).done(function (data) {
$('#txtHint').text = data;
}).fail(function() {
alert('Fatal error');
})
} else {
$('#txtHint').text = '';
}
With this configuration, it is important to return result with echo json_encode in your server side code.
PHP
<?php
include('dbconnect.php');
$q = intval($_GET['q']);
mysqli_select_db($connection, "opera_house");
$sql = 'SELECT room_name FROM room WHERE capacity >= '.$q; // Some corrections
$result = mysqli_query($connection, $sql);
$return = '';
while($row = mysqli_fetch_array($result)) {
$return .= '<td>' . $row["room_name"] . '</td>';
}
echo json_encode($return); // Return Json to ajax
?>
While thinking of JS it's fine. I think the problems are in the php code. Try this one.
<?php
include('dbconnect.php');
$q = intval($_GET['q']);
mysqli_select_db($connection,"opera_house");
$sql="SELECT room_name FROM room WHERE capacity >= " . $q;
$result = mysqli_query($connection,$sql);
if (!$result) {
echo mysqli_error();
exit();
} // this is to do debugging. remove when you get it fixed
$ret = ""; //variable to hold return string
while($row = mysqli_fetch_array($result)) {
$ret .= "<td>" . $row['room_name'] . "</td>";
}
echo $ret;

Perform Server Side & Client Side Operations In One Project

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>

Ajax Based search PHP

I am trying to create an AJAX based search in PHP. The code I have written so far does not seem to be working uptil now. Any suggesstions would be of great help. Thanks in advance. Here is my code.
index.php
<head>
<script src = "http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<input type="text" name="text" id="text" autocomplete="off" onkeyup="showHint(this.value)"/>
<div id="inner"></div>
<script type="text/javascript">
function showHint(str) {
if(str.length == 0) {
document.getElementById('inner').innerHTML = "search";
return;
}
if(window.XMLHttpRequest) {
xmlhttp = XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if(xmlhttpreadystate == 4 && xmlhttp.status == 200) {
document.getElementById('inner').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("REQUEST", "search.php?text"+str, true);
xmlhttp.send();
}
</script>
</body>
</html>
search.php
<?php
$host = 'localhost';
$user = 'root';
$password= 'root';
$db = 'demo';
#$conn = mysql_connect($host, $user, $password) or die(mysql_error());
mysql_select_db($db, $conn);
/*if($result) {
echo "success";
} else { echo "fail"; }
*/
$text = $_REQUEST['text'];
$text = preg_replace('#[^a-z0-9]#i', '', $text);
$query = "SELECT * FROM users where first_name LIKE '%$text%' OR last_name LIKE '%$text%'";
$action = mysql_query($query);
$result = mysql_num_rows($action);
while($res = mysql_fetch_array($action)) {
$output .= $res['first_name']. ' '.$res['last_name'];
echo $output;
}
?>
You missed the equal sign in the script(after the text) in index.php.
xmlhttp.open("REQUEST", "search.php?text="+str, true);
Why you are doing this lengthy process, You can also try this jQuery ajax,
$.ajax({
url: 'search.php',
type: 'GET',
data: 'text='+str,
success: function(data) {
//called when successful
$('#inner').html(data);
},
error: function(e) {
//called when there is an error
console.log(e.message);
}
});
I am just getting the input in search.php. Can you try these codes:
index.html:
<html>
<head>
</head>
<body>
<input type="text" name="text" id="text" autocomplete="off" onkeyup="showHint(this.value)"/>
<div id="inner"></div>
<script type="text/javascript">
function getHttpRequest()
{
if(window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlhttp;
}
function showHint(str)
{
var xmlhttp;
if (str=="")
{
document.getElementById('inner').innerHTML = "search";
return;
}
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById('inner').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "search.php?str="+str, true);
xmlhttp.send();
}
</script>
</body>
</html>
search.php:
<?php
$text=$_GET["str"];
echo $text;
?>
Use this :
$.ajax({
url: 'search.php',
type: 'GET',
data: 'text='+str,
success: function(data) {
//called when successful
$('#inner').html(data);
},
error: function(e) {
//called when there is an error
console.log(e.message);
alert(e.message); // if you dont know how to check console
}
});

AJAX, no response received

if(isset($_GET['delete'])) {
$ID = $_GET['delete'];
echo "
<script type='text/javascript'>
var ajax = new XMLHttpRequest();
var ajax.open('POST','parser.php', true);
ajax.setRequestHeader('Content-type','application/x-www-form-urlencoded');
ajax.onreadystatechange = function () {
if(ajax.readyState ==4 && ajax.status == 200) {
alert(ajax.responseText);
}
}
ajax.send('delete=$ID')
</script>
";
}
this is my code, it is supposed to send the id to parser.php
here is parser.php
<?php
if(isset($_POST['delete'])) {
echo $_POST['delete'];
}
no response is received from parser.php, can anyone help ?
all answers are much appreciated

Categories