Generating new id each time button is clicked - php

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

Related

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;

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

PHP, AJAX Unable to display values based on dropdownlist

My codes were taken from http://www.w3schools.com/php/php_ajax_database.asp, however i modified to better suit me, but it isn't working as it should be.
Afile.php
<head>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
}
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) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "getDescription.php?q=" + str, true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<?php
$comCtrl = new company_controller();
$companyArray = $comCtrl->retrieveAllCompany();
foreach($companyArray as $com) {
echo "<option value ='".$com."' >".$com."</option>";
}//end foreach
?>
</select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here.</b></div>
</body>
getDescription.php
<?php
require_once('dbManager.php');
$q = intval($_GET['q']);
$dbMgr = new dbManager();
$conn = $dbMgr->getDBConnection();
$query = "select company_address from company where company_name = '$q'";
$result = mysql_query($query);
echo "<table border='1'>";
while($row = mysql_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . $row['company_address'] . "</td>";
echo "</tr>";
}
echo "</table>";
$dbMgr->closeDBConnection($conn);
?>
dbManager.php
<?php
//require('/config/config.php');
require(dirname(__FILE__) . '\..\config\config.php');
class dbManager{
function getDBConnection(){
// start connection
$connect = mysql_connect(DB_HOST, DB_USER, DB_PASS);
if (!$connect)
{
die( 'Could not connect: '.mysql_error() );
}
// Select the database
if(!mysql_select_db(DB_NAME))
{
die('The database - '. DB_NAME .' does not exist!');
}
return $connect;
}
function closeDBConnection($connect){
// close the connection
mysql_close($connect);
}
}
?>
I was expecting to have the same result as shown on the website.
Instead, when i first run the files, i would see a dropdownlist(ddl) with all the company values, and beneath that ddl is the text "person info will be listed here". When i click on the ddl, i was hoping for the company's address to be populated at the div place of the text, but instead another ddl appeared beneath the first ddl. So now i have a ddl on the first row, another ddl on the second row, and the same text "person info will be listed here". WHat am i missing?
I would recommend you to use mysqli_query() or PDO::query()
This is the required syntax for mysql_query()
mysql_query(query,$conn);
use:
$q = trim($_GET['q']);

PHP page not returning value

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

AJAX: Display Chart data as IMG

I want to show a (chart) image using AJAX. I'm not sure what's wrong, but I'm getting the following 'error' and an incorrect image:
"|xtt�I������{饗BBBN�:��}�̛7oРA7n�0l߾} QQQIIIeee�aLHH������ضm��wm���v��U�&�Z���o�# Art]]]����{���#""��'���v|�ҥKqqq���ح�~;11�ȑ#����޺u��ںm6O�7o���.��ի��?~Ȑ!��~��۷��O�0A.�cv�����TäR)�� ����˗{N����5<��&0� ���ҷo��#�NХ<0�j�0��=���]�t��۷�j�T*5�\����۳g�F�����gfm���ݻ�'OF....."
The code I'm using:
ajax_select.php:
<html>
<head>
<script type="text/javascript">
var xmlhttp;
function showUser(str,age)
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
var url="test_ajax.php";
url=url+"?q="+str+"&a="+age;
url=url+"&sid="+Math.random();
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
function stateChanged()
{
if (xmlhttp.readyState==4)
{
document.getElementById("txtHint").innerHTML="<IMG SRC='" + xmlhttp.responseText + "'/>";
}
}
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
</script>
</head>
<body>
<form>
<select id="users" name="users">
<option value="">Select a person:</option>
<?php
$con = mysql_connect(***);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("***", $con);
$sql="SELECT ***";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
}
mysql_close($con);
?>
</select>
<select id="age" name="age">
<option value="">Select a person:</option>
<?php
$con = mysql_connect('***');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("***", $con);
$sql="SELECT ***";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
}
mysql_close($con);
?>
</select>
<input type='button' value='Refresh Data' onclick="showUser(document.getElementById('users').value,document.getElementById('age').value)">
</form>
<br><br>
<div id="txtHint"><b>chart will be displayed here.</b></div>
</body>
</html>
ajax_select_NEW.php:
<script type="text/javascript">
var xmlhttp;
function showUser(str,age)
{
var url = 'test_ajax.php';
url += '?q=' + str + '&a=' + age + '&sid=' + Math.random();
document.getElementById('txtHint').innerHTML = '<img src="' + url + '" />';
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
</script>
test_ajax.php:
<?php
/* Include the pData class */
include("class/pData.class.php");
include("class/pDraw.class.php");
include("class/pImage.class.php");
/* Get user from AJAX resquest */
$user_id=$_GET["q"];
$q=$_GET["q"];
$a=$_GET["a"];
/* Create the pData object */
$MyData = new pData();
/* Connect to the MySQL database */
$db = mysql_connect("***");
mysql_select_db("***",$db);
/* Build the query that will returns the data to graph */
$Requete = "
SELECT ***
";
***
/* Render the picture (choose the best way) */
$myPicture->autoOutput("examples/example.drawBarChart.png");
?>
I have hard coded the variables in the SQL code for now. (in test_ajax.php) So if I open that page it just shows the correct chart image. But when I open the ajax_select.php page I get the error in the picture above. (so it's not a wrong chart code information, since it's okay if I open the php page directly)
I have searched a lot, but can't find the solution. Hopefully someone can help me here, would be much appreciated!
You're trying to put the binary image data into the src attribute of the img. This attribute is meant for the source URL of the image, you can do this entirely without XmlHttpRequest, just insert your image by using test_ajax.php as the src.
function showUser(str, age) {
var url = 'test_ajax.php';
url += '?q=' + str + '&a=' + age + '&sid=' + Math.random();
document.getElementById('txtHint').innerHTML = '<img src="' + url + '" />';
}
As for the broken rendering of the image, have you included a Content-Type-header?
header('Content-Type: image/png');
$myPicture->autoOutput("examples/example.drawBarChart.png");
This is what ajax_select_NEW.php should look like:
<script type="text/javascript">
function showUser(str, age) {
var url = 'test_ajax.php';
url += '?q=' + str + '&a=' + age + '&sid=' + Math.random();
document.getElementById('txtHint').innerHTML = '<img src="' + url + '" />';
}
</script>

Categories