I am developing a online bus booking website like redbus using an api service.
Stuck with calculating the total amount of booked seats.
Here is the work flow
Getting list of buses from api and shows them in an html table:
<?php $i=0; foreach($result['apiAvailableBuses'] as $value){?>
?>
//display each bus details
<?php }?>
Make an ajax request to getting the each bus seat structure with some parameters (ajax request is in a loop).
$.ajax({
url:'<?php echo base_url();?>agentdashboard/ajax_buslayout',
method:"POST",
data:{
source:$("input[name=source]").val(),
dest:$("input[name=dest]").val(),
doj:$("input[name=doj]").val()
},
success:function(data){
$('#result'+id).html(data);
},
error:function(err){
}
});
php code
foreach($result['seats'] as $value)
{
echo "<div class='seat $booked' data-number='$seat' $book_seat amount='$total'><img src='".base_url()."assets/images/seat.png' width='20' height='20' title='$seat'></div>";
}
echo "<div class='clearfix'></div><br><center><strong id='amount'>Amount:0</strong></center>";
When click on each seat I will store the clicked seat numbers to seat_count array to find the total amount.
$(document).on("click",".seat",function(){
//store the number of clicked seats.
var seat_count = [];
//seat number of each seat.
var seat_no = $(this).attr("data-number");
seat_count.push(seat_no);
alert(seat_count.length);
$("#amount").text('Amount: '+seat_count.length * amount);
});
But the problem is I can't get the values in seat_count array, I get only one value .
alert(seat_count.length)
only returns 1.
Declare the 'var seat_count = [];' outside the click event handler function. Every time 'seat_count' is getting re-initialized.
var seat_count = [];
$(document).on("click", ".seat", function () {
//seat number of each seat.
var seat_no = $(this).attr("data-number");
seat_count.push(seat_no);
alert(seat_count.length);
$("#amount").text('Amount: ' + seat_count.length * amount);
});
Related
this is my javascript
<script>
function multiply(id) {
var quantity = $("#quantity"+id).val();
var price = $("#price"+id).text();
var dataArray= 'quantity1='+ quantity + '&price1='+ price;
$.ajax({
url: "ajaxmultiply.php",
data: dataArray,
type: 'POST',
success: function (data) {
$("#total"+id).(data);
}
});
}
</script>
I am able to get the total of the products but i am having issue in getting net total of the product, i am doing this using ajax, when i add the total it will give me previous value as concatenated with next value,i tried using through array but it also didn't work, now i store the total value in new table and then fetch it from there and add it but i didn't give me required answer, i tried to use array in it but it also didn't work for me
This is my ajaxmultiply.php file code
<?php
include 'connection.php';
$quantity=$_POST['quantity1'];
$price = $_POST['price1'];
$total= $quantity * $price;
//echo $total;
$query =mysqli_query ($conn,"INSERT INTO grand_total (total) VALUES
('$total')");
$getdata=mysqli_query($conn,"SELECT * FROM grand_total");
while ($fetchdata=mysqli_fetch_assoc($getdata)){
$newtotal = $fetchdata['total'];
$id = $fetchdata['id'];
$grandTotal=$newtotal + $newtotal;
echo $grandTotal;
}
Your while loop should be like below:
$grandTotal = 0;
while ($fetchdata=mysqli_fetch_assoc($getdata)){
$newtotal = $fetchdata['total'];
$id = $fetchdata['id'];
$grandTotal += $newtotal;
}
echo $grandTotal;
I have PHP loop. I take the id, lat, lon data from record, passed it to script to do some calculations, then I passed this data to AJAX which will save the results of that calculation in MySQL DB, if it's successful then it will add the line of confirmation text to a results div.
My Code (I did trim it to keep focus on the issue)
<div id="distance_results"></div>
<?php
$result = $mysqli->query("SELECT * FROM test")
while($row = $result->fetch_array()) {
$id = $row['id'];
$city = $row['city'];
$lat = $row['lat'];
$lon = $row['lon'];
$driving_from = "51.528308,-0.3817765";
$driving_to = "$lat,$lon";
?>
<script>
var id = '<?php echo $id ?>';
var city = '<?php echo $city ?>';
var start = '<?php echo $driving_from ?>';
var end = '<?php echo $driving_to ?>';
// code
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
// code
var mi = response.routes[0].legs[0].distance.value;
console.log(id);
console.log(city);
console.log(mi);
//Ajax Begin
$.ajax({
type: 'post',
url: 'test-dc-upd.php',
data: {'updateid': id, 'distance': mi},
success: function() {
html="Distance between London and " + city + " is " + mi;
$("#distance_results").append("<p>"+html+"</p>");
}
});
//Ajax End
} else {}
});
</script>
<?php } ?>
AND CODE FOR "test-dc-upd.php"
$id = $_POST['updateid'];
$distance = $_POST['distance'];
$result = $mysqli->query("UPDATE test SET distance='$distance' WHERE id='$id' LIMIT 1");
So PHP is looping thru MySQL DB, when but when I look at console:
'mi' values are calculated well according to lat / lon;
PROBLEMS:
1) 'id' and 'city' values stay the same (values of last record in the loop);
2) AJAX is updating value of last record in the loop only
So it obvious there is a some issue with the loop.
Any suggestion to what i do wrong?
Change this
$("<p>"+ html +"</p>").append("#distance_results");
To
$("#distance_results").append("<p>"+ html +"</p>");
Your jquery code is wrong. First you have to put selector and in append function the html code.
Nita, change the success function from:
success: function() {
html="Distance between CITYX and " + city + " is " + mi;
$("<p>"+ html +"</p>").append("#distance_results");
}
});
To
success: function() {
html="Distance between CITYX and " + city + " is " + mi;
$("#distance_results").append(<p>"+ html +"</p>);
// this will append the dynamic content to #distance_results
}
});
Explanation:
To put a dynamic content is some html object you have to first prepare
the content than select the html object and put the content into it.
In a loop calling ajax request is not a good practice we can easily pass array of values to javascript using the function implode like this
this implode function is for single dimensional array,
var ar = <?php echo '["' . implode('", "', $ar) . '"]' ?>;
For your question you need to create a multi dimensional array for the result like this ..
<?php
$result = $mysqli->query("SELECT * FROM test");
$arr= array();
while($row = $result->fetch_array()) {
$arr[]=array('id'=>$row['id'],'city'=>$row['city],'lat'=>$row['lat']...etc);
}
?>
afetr that you can pass each item in the array to javascript like this
var idArray= <?php echo '["' . implode(', ', array_column($arr, 'id')); . '"]' ?>;
var cityArray= <?php echo '["' . implode(', ', array_column($arr, 'city')); . '"]' ?>;
you can get each tag as array in javascript after that using a sing ajax request pass all javascript array to php script. and manipulate in the server side .
Your ajax request is like this
$.ajax({
type: 'post',
url: 'test-dc-upd.php',
data: {
'idArray':idArray,
'cityArray':cityArray, //etc you need pass all array like this
},
success: function(data) {
// your success code goes here
}
});
Note that array_column() function only supported by php 5.3 or above
I manage to do it a little different way i was hoping for ( But distance and travel time has been calculate for more then 3000 locations).
So what i did is to make sure mysql (test-dc.php) finds record where distance and travel time has not been calculated, makes calculation, update record with Ajax. Ajax on succesion opens the (test-dc.php) again, And is looping thru all results till there is nothing else to calculate. Had to refesh few times but thats fine, job done.
Adjustment to Mysql query:
$result = $mysqli->query("SELECT * FROM test WHERE distance='' LIMIT 1")
and to AJAX:
success: function() {
html="Distance between London and " + city + " is " + mi;
$("#distance_results").append("<p>"+html+"</p>");
location.href = "test-dc.php"
}
So that did the trick, but i still belive there is a better way of achiving the same result, i will be happy if someone could help me to figure it out.
I have a column of buttons in a table, declared like this:
(file index.php)
echo '';
Then this script reads the data in the row of the button clicked and posts it to another php file:
<!-- scripts that gets the lecturer chosen to SHOW functionality-->
<script>
$(document).ready(function(){
$(".show-button").click(function() {
var $row = $(this).closest("tr"); // Find the row
var names = $row.find(".name").text(); // Find the name
var surname = $row.find(".surname").text(); // Find the surname
$.ajax({ type: "POST", url: "show_lecturer.php", data: { x: names, y: surname} })
});
});
</script>
That file (show_lecturer.php) stores the data read in a table (keep_track) in the database:
(file show_lecturer.php)
<?php
ob_start(); //eliminates buffer collisions
require_once('connect_db.php');
$name = $_POST['x'];
$surname = $_POST['y'];
$result = pg_query(connect(), "INSERT INTO keep_track VALUES ('$name', '$surname')");
?>
Then I create an empty dialogbox with jquery, to populate it with the data taken from the database:
(file index.php)
<!-- The following script generates the empty dialog box -->
<script src="/js/jquery.min.js"></script>
<link rel="stylesheet" href="/css/jquery-ui.css">
<script src="/js/jquery-ui.min.js"></script>
<script>
$(function() {
//show lecturer dialog
$("#show_dialog").dialog({autoOpen: false});
$(".show-button").on("click", function() {$("#show_dialog").dialog("open");});
});
</script>
Then these data are taken from the table keep_track and echoed in the above dialog:
(file index.php)
$name; $surname;
require_once('connect_db.php');
$firstname = pg_query(connect(), "SELECT name FROM keep_track");
while($row = pg_fetch_array($firstname)){ $name = $row['path']." ".$row['name']; }
$lastname = pg_query(connect(), "SELECT surname FROM keep_track");
while($row = pg_fetch_array($lastname)){ $surname = $row['path']." ".$row['name']; }
echo '<div id="show_dialog" class="ui-dialog-content ui-widget-content">';
echo $name."".$surname;
echo '</div>';
?>
So when I click the button of row x, a dialogbox opens with the data from the row x.
The only thing that is not working correctly is this:
The moment I click button x, it opens a dialog but displays a value, but not that of row x. However, when i see the database, the row x is stored there. The value in the checkbox is that of the button clicked before the latest refresh on the page. Its as if there is some mistake in my chain of calls or something (that I cant figure out, thats why Im asking).
To illustrate the data I get:
(Initially the table keep_track is empty)
Press button 1 -> row 1 stored, dialogbox has no content
Press button 2 -> row 2 stored, dialogbox has no content
Press button 3 -> row 3 stored, dialogbox has no content
Refresh page manually
Press button 4 -> row 4 stored, dialogbox has content from row 3
Press button 5 -> row 5 stored, dialogbox has content from row 3
Refresh page manually
Press button 6 -> row 6 stored, dialogbox has content from row 6
Press button 7 -> row 7 stored, dialogbox has content from row 3
I suggest you return your data from the POST via JSON. And please be aware that an AJAX Call is asynchronous. So you won't know when the reply is coming.
So you need to process your results using the ajax Success callback function.
</script>
$(document).ready(function(){
$(".show-button").click(function() {
var $row = $(this).closest("tr"); // Find the row
var names = $row.find(".name").text(); // Find the name
var surname = $row.find(".surname").text(); // Find the surname
do_post_and_show_info(names, surname);
});
});
function do_post_and_show_info(names, surname){
request= $.ajax({
type: "post",
cache: false,
url: "show_lecturer.php",
data: { x: names, y: surname} ,
dataType: "json",
});
request.done(function(json){
if (json.status =="ok"){
// DO YOUR THING!
Alert(json.data.names + " " + json.data.surnames);
}
else {
alert("Error! " + json.error + " : " + json.remarks);
}
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus + ":" + jqXHR.responseJSON);
});
}//do_post_and_show_info
</script>
I usually return a datastructure like this in PHP (so in your show_lecturer.php)
<?
// get your data before this in the variable $data
// put your status "OK" or "ERROR" in $status
// put some error info in $extraInfo
// of course some processing is involved, but here's a simple example
require_once('connect_db.php');
$name = $_POST['x'];
$surname = $_POST['y'];
$result = pg_query(connect(), "INSERT INTO keep_track VALUES ('$name', '$surname')");
// obviously you need to do some error checking, but here's the happy flow
$status = "OK";
$error = "";
$data['names'] = $name;
$data['surnames'] = $surname;
echo json_encode(array(
"status" => $status,
"error" => $error,
"remark" => $extraInfo,
"data" => $data
));
?>
Please be aware this is an example that I have created here in the editor and not in a real working setup. SO please try to understand it instead of copy-pasting it and giving it a run.
I wrote the content of the dialog (div) in another file and used
$("#div").load("content.php", {x:parameter_1, y:parameter_2, ......});
instead of
$.ajax({ type: "POST", url: "show_lecturer.php", data: { x: names, y: surname} })
This did the trick.
Now the div is initially invisible and empty, but once the button is clicked, it requests the content.php page to load. Since I'm passing the search parameters when I request the content, I get the data that I wanted.
The problem from before was that when the page loaded, the div was created with the data (even though I hadn't clicked any button). Therefore, when I 'd click a button, it would show me the div with the content from the last page load (last refresh).
There were also other minor changes I had to do to make it work, but this is the main idea.
This question already has answers here:
How to select the nth row in a SQL database table?
(33 answers)
Closed 9 years ago.
I am trying to load content as the user scrolls from my database. I am trying to load 10 items at a time in order. currently I have achieved everything I want to do except I am loading the first 10 items every time. I don't really know how to keep track of what items were loaded last. If I made a variable it would reset anyways everytime the script is called.
What do I need to change in order for it to load the next 10 items instead of the first 10?
php:
<?php
// database connection info
$conn = mysql_connect('localhost','root','') or trigger_error("SQL", E_USER_ERROR);
$db = mysql_select_db('test',$conn) or trigger_error("SQL", E_USER_ERROR);
//offset
$offset=0;
// number of rows to show per page
$rowsperpage = 10;
// get the info from the db
$sql = "SELECT ID, confession, image FROM test LIMIT $offset, $rowsperpage";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
// while there are rows to be fetched...
while ($list = mysql_fetch_assoc($result)) {
echo '<table border="0" width="600px">';
echo "<tr>";
echo "<td><p>" . '<img src="' . $list['image'] . '" hspace="10" border="1" style="float:left;">' . "</p>";
echo "<p>" . "#" . $list['ID'] . ": " . $list['confession'] . "</p></td>";
echo "</tr>";
echo "</table>";
echo "<br>";
//next ten rows
$offset+=10;
}
?>
javascript:
//load content as page scrolls
function yHandler() {
var content = document.getElementById('content');
var contentHeight = content.offsetHeight;
var yOffset = window.pageYOffset;
var y = yOffset + window.innerHeight;
if (y >= contentHeight) {
// Ajax call to get more dynamic data goes here
content.innerHTML += '<div class="newData"></div>';
document.onload = $.post('test5.php', function (data) {
$('.newData').html(data);
});
}
}
window.onscroll = yHandler;
You need to set some counter to this, for example:
<input type="hidden" value ='counter_value'>
And when you send request, you have to send it with counter value, and in php file dependce on counter value select next 10 items from db. After thet using java script increase counter value by ++. And when you will send again request the value will be +1, and in php make logic to select next items
For example, when you reached the bottom of the page, you want to download next items.
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
///here you have to send ajax to php file to get items
var counter= $('#idOfInputwithCouner').attr('value');
$.ajax({
url: 'youPhpFile.php',
data: "counter=" + counter,
type: 'POST',
processData: false,
contentType: false,
success: function (data) {
alert('data'); //here you will get data from php file
$('#idOfInputwithCouner').attr('value',counter +1); //increase input value
}
})
}
});
you may use pagination logic here, send pageNumber with each call and retrieve data accordingly,
Hi I am trying to pass values using 'post' from three drop down lists to the database using php script where I insert values into the database with values of the three lists
previously I retrieved a list from another page into a div time.php using jquery ajax call
code for which looks like this :-
//This script uses jquery and ajax it is used to set the values in
// the time field whenever a day is selected.
$(document).ready(function(){
$("#day").change(function(){
var day=$("#day").val();
var doctor=$("#doctor").val();
$.ajax({
type:"post",
url:"time.php",
data:"day="+day+"&doctor="+doctor,
success:function(data){
$("#time").html(data);
}
});
});
});
code for the html section looks something like this:-
<select id="doctor">some options</select>
<select id="day">some options</select>
<div id="time"> </div>
Now the values from the two lists are going through fine. But the one I retrieved into the div is not going through. Could you point me in the right direction?
Thanks in advance.
//The php script for insertion
<?php
session_start(); //Use this to include session variables
$con=mysqli_connect("localhost","clinic","myclinic","myclinic");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "INSERT INTO appointment(username, doctor, day, time) VALUES('$_SESSION[username]', '$_POST[doctor]', '$_POST[day]', '$_POST[time]')";
if (!mysqli_query($con,$query))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
header("location:login_success.php");
?>
If you want to retrive div content like input, select etc
You have to get it like
var time = $("#time").html();
Your code will be
Add a button to your page
<input type='button' value='Send' id='send'>
Then add
$(document).ready(function(){
$("#send").click(function(){
var day=$("#day").val();
var doctor=$("#doctor").val();
var time = $("#time").find("select").val();
$.ajax({
type:"post",
url:"time.php",
data:"day="+day+"&doctor="+doctor+"&time="+time, //add param
success:function(data){
}
});
});
});