I'm building a small online order system for a restaurant. My code for shoping card looks like this:
<?php
// Košarica
function ShopKosarica(){
global $link;
$UkupnoZbroj = 0;
$KosaricaSession = $_SESSION['ime'];
$rezultat = mysqli_query($link, "SELECT * FROM shop_kosarica WHERE KosaricaSession='$KosaricaSession' AND KosaricaKolicina<>0 ORDER BY KosaricaID ASC");
$num_results = mysqli_num_rows($rezultat);
if ($num_results==0){
echo "<h2><strong>Košarica je prazna</strong></h2>";
}else{
while ($redak = mysqli_fetch_array($rezultat)){
$ArtikalID = $redak['KosaricaArtikal'];
$rezultat_artikal = mysqli_query($link, "SELECT * FROM shop_artikal WHERE ArtikalID='$ArtikalID'");
$redak_artikal = mysqli_fetch_array($rezultat_artikal);
if ($redak['KosaricaVelicina']=='jumbo'){
$Cijena = $redak_artikal['ArtikalCijena2'];
} else {
$Cijena = $redak_artikal['ArtikalCijena1'];
}
$Kolicina = $redak['KosaricaKolicina'];
$Zbroj = $Cijena * $Kolicina;
$Zbroj = number_format((float)$Zbroj, 2, '.', '');
$UkupnoZbroj += $Zbroj;
$UkupnoZbroj = number_format((float)$UkupnoZbroj, 2, '.', '');
?>
<form class="ShopKosaricaBox" method="post">
<input type="hidden" id="KosaricaID" name="KosaricaID" value="<?=$redak['KosaricaID']?>">
<div class="MarginBottom15">
<input type="text" id="KosaricaKolicina" name="KosaricaKolicina" value="<?=$redak['KosaricaKolicina']?>" maxlength="2"> x <?=$redak_artikal['ArtikalNazivHr']?> (<?=$redak['KosaricaVelicina']?>) - <?=$Zbroj?> kn
</div>
<div class="right MarginBottom15">
<a onclick="ShopPromjena();">Promjeni</a> <a style="background:#c94e11;" onclick="ShopBrisanje();">Obriši</a>
</div>
<div class="clear"></div>
</form>
<script type="text/javascript">
function ShopPromjena() {
$(document).ready(function(){
var str = $(".ShopKosaricaBox").serialize();
$.ajax({
type: "POST",
url: "/funkcije?akcija=promjena&KosaricaID=<?=$redak['KosaricaID']?>",
data: str,
success: function(str){
alert( "Uspješno ste promjenili količinu!" );
}
});
return false;
});
}
function ShopBrisanje() {
$(document).ready(function(){
var str = $(".ShopKosaricaBox").serialize();
$.ajax({
type: "POST",
url: "/funkcije?akcija=brisi&KosaricaID=<?=$redak['KosaricaID']?>",
data: str,
success: function(str){
alert( "Uspješno ste obrisali jelo!" );
}
});
return false;
});
}
</script>
<?php
} ?>
<h1 class="MarginBottom25" style="font-size:25px;">Ukupno: <strong><?=$UkupnoZbroj?> kn</strong></h1>
<?php }
}
?>
And I put data in mysql via Ayax, this is the javascript:
$(document).ready(function(){
$(".ShopPonudaBox").submit(function(){
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "/funkcije?akcija=dodaj",
data: str,
success: function(str){
alert( "Uspješno ste dodali jelo!" );
$('#KosaricaBox').load("/include/funkcije.php?funkcija=ShopKosarica");
return false;
}
});
return false;
});
});
and php code;
if ($_GET['akcija']=="dodaj") {
if ($_POST['KosaricaKolicina']<>0){
$KosaricaSession = $_SESSION['ime'];
$KosaricaArtikal = clean($link, $_POST['ArtikalID']);
$KosaricaKolicina = clean($link, $_POST['KosaricaKolicina']);
$KosaricaVelicina = clean($link, $_POST['KosaricaVelicina']);
$provjera = mysqli_query($link, "SELECT * FROM shop_kosarica WHERE KosaricaSession='$KosaricaSession' AND KosaricaArtikal='$KosaricaArtikal' AND KosaricaVelicina='$KosaricaVelicina'");
$num_results = mysqli_num_rows($provjera);
if ($num_results==0){
$result = mysqli_query($link, "INSERT INTO shop_kosarica (KosaricaSession, KosaricaArtikal, KosaricaKolicina, KosaricaVelicina) VALUE ('$KosaricaSession', '$KosaricaArtikal', '$KosaricaKolicina', '$KosaricaVelicina')");
//header("Location: /online-narudzba#Shop");
} else {
$redak_provjera = mysqli_fetch_array($provjera);
$KosaricaID = $redak_provjera['KosaricaID'];
$result = mysqli_query($link, "UPDATE shop_kosarica SET KosaricaKolicina=KosaricaKolicina+$KosaricaKolicina WHERE KosaricaID='$KosaricaID'");
//header("Location: /online-narudzba#Shop");
}
} else {
//header("Location: /online-narudzba#Shop");
}
}
I tried with this method I found here
$('#KosaricaBox').load("/include/funkcije.php?funkcija=ShopKosarica");
$funkcija = $_GET["funkcija"];
if ($funkcija == "ShopKosarica") {
echo ShopKosarica();
}
but keep getting errors
Notice: Undefined variable: _SESSION in
H:\Dropbox\htdocs\include\funkcije.php on line 47
Warning: mysqli_query() expects parameter 1 to be mysqli, null given
in H:\Dropbox\htdocs\include\funkcije.php on line 48
Add
session_start();
and connect database
at the beginning of your page before any HTML
You will have something like :
$con=mysqli_connect("localhost","xxxx","xxxx","xxxxx");
//check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL:" . mysqli_connect_error();
}
session_start();
include("inc/incfiles/header.inc.php")?>
<html>
<head>
<meta http-equiv="Content-Type" conte...
Don't forget to remove the space you have before
Related
Currently, I made script, which after onclick event,sending question to the database and showing data in console.log( from array ). This all works correctly, but.. I want to show data from array in the different position in my code. When I try to use DataType 'json' and then show some data, then it display in my console.log nothing. So, my question is: How to fix problem with displaying data? Is it a good idea as you see?
Below you see my current code:
$(document).ready(function(){
$(".profile").click(function(){
var id = $(this).data('id');
//console.log(id);
$.ajax({
method: "GET",
url: "../functions/getDataFromDB.php",
dataType: "text",
data: {id:id},
success: function(data){
console.log(data);
}
});
});
});
:
public function GetPlayer($id){
$id = $_GET['id'];
$query = "SELECT name,surname FROM zawodnik WHERE id='".$id."'";
$result = $this->db->query($query);
if ($result->num_rows>0) {
while($row = $result->fetch_assoc()){
$this->PlayerInfo[] = $row;
}
return $this->PlayerInfo;
}else {
return false;
}
}
:
$info = array();
$id = $_GET['id'];
$vv = new AddService();
foreach($vv->GetPlayer($id) as $data){
$info[0] = $data['name'];
$info[1] = $data['surname'];
}
echo json_encode($info);
I think it would be better to change the line fetch_all in mysqli to rm -rf. That information in the DB is all obsolete, or completely not true.
Try this:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button class="profile" data-id="1">Click</button>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script>
$(document).ready(function(){
$(".profile").click(function(){
var id = $(this).data('id');
console.log(id);
$.ajax({
method: "GET",
url: "../functions/getDataFromDB.php",
dataType: "json",
data: {id:id},
success: function(data){
console.log(data);
$.each(data, function(idx, item) {
console.log(item.surname);
});
}
});
});
});
</script>
</body>
</html>
PHP side:
<?php
class AddService {
public function GetPlayer($id) {
if (filter_var($id, FILTER_VALIDATE_INT) === false) {
return false;
}
$query = "SELECT name, surname FROM zawodnik WHERE id={$id}";
$result = $this->db->query($query);
if ($result->num_rows <= 0) {
return false;
}
// assumming you are using mysqli
// return json_encode($result->fetch_all(MYSQLI_ASSOC));
// or
WHILE ($row = $result->fetch_assoc()) {
$data[] = $row;
}
return json_encode($data);
}
}
if (isset($_GET['id'])) {
$id = $_GET['id'];
$vv = new AddService();
// you don't need foreach loop to call the method
// otherwise, you are duplicating your results
echo $vv->GetPlayer($id);
}
i have this code:connection to database
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$conn = new mysqli("localhost", "root", "", "jquery");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
now i already have data indatabase in table called city witch it have only id and desc and this is the code
if (isset($_POST['city'])) {
$sql = "SELECT * FROM city";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$results = [];
while($row = $result->fetch_assoc()) {
$results[] = $row;
}
echo json_encode($Results);
}
else
{
echo "empty";
}
}
here is the html part:
<select required="required" id="city">
<option disabled selected value=''> select a city </option>
</select>
and here is the function:
function city() {
$.ajax({
"url": "divs.php",
"dataType": "json",
"method": "post",
//ifModified: true,
"data": {
"F": ""
}
})
.done(function(data, status) {
if (status === "success") {
for (var i = 0; i < data.length; i++) {
var c = data[i]["city"];
$('select').append('<option value="'+c+'">'+c+'</option>');
}
}
})
.always(function() {
});
}
so the problem is that there is nothing in select list its always empty, any help? thank u
One small mistake is here:
You are using
echo json_encode($Results);
instead of
echo json_encode($results);
In PHP variable names are case sensitive. So, use proper case for all the variables.
You are not getting the response data in HTML <SELECT> TAG here is what you can do.
image to table
HTML FILE CODE:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<form action="" method="post">
<select>
</select>
</form>
<script>
$(document).ready(function(){
city();
});
function city(){
$.ajax({
type:'POST',
url: 'divs.php',
data: {city:1},
success:function(data){
var res = JSON.parse(data)
for(var i in res){
var showdata = '<option value="'+res[i].city_name+'">'+res[i].city_name+'</option>';
$("select").append(showdata);
}
}
});
}
</script>
</body>
</html>
HERE IS THE PHP CODE
`
<?php
$conn = new mysqli('localhost','root','','demo');
if($conn->connect_error){
die ("Connection Failed".$conn->link->error);
}
if(isset($_POST['city'])){
$sql = "SELECT * FROM city";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$results[] = $row;
}
echo json_encode($results);
}
else
{
echo "no city available";
}
}
?>
`
HERE IS THE OUTPUT IMAGE
You have used $results but while echoing you are using $Results which is a different variable so use,
echo json_encode($results);
Also, you are telling that city has only id and desc so in JS code use desc instead of city
$.ajax({
type:'POST',
url: 'divs.php',
data: {city:1},
success:function(data) {
var res = JSON.parse(data);
$(res).each(function(){
var c = this.city_name; // use city_name here instead of city
$('select').append('<option value="'+c+'">'+c+'</option>');
});
}
});
I am trying to edit two columns using ajax and php.My code currently edits one values(name) in my table and saves it to my database.When i add the second variable (p) my ajax call it updates both columns p and y with the same value.How do i edit the third value and assign it a different value from y.I want the two different columns to have different values in my db(columns:name and capacity)
This code edits and updates two values:
<script type="text/javascript">
jQuery(document).ready(function() {
$.fn.editable.defaults.mode = 'popup';
$('.xedit').editable();
$(document).on('click','.editable-submit',function(){
var x = $(this).closest('td').children('span').attr('id');
var y = $('.input-sm').val();
var z = $(this).closest('td').children('span');
$.ajax({
url: "process.php?id="+x+"&data="+y,
type: 'GET',
success: function(s){
if(s == 'status'){
$(z).html(y);}
if(s == 'error') {
alert('Error Processing your Request!');}
},
error: function(e){
alert('Error Processing your Request!!');
}
});
});
});
</script>
And this is what i tried to edit three values:
<script type="text/javascript">
jQuery(document).ready(function() {
$.fn.editable.defaults.mode = 'popup';
$('.xedit').editable();
$(document).on('click','.editable-submit',function(){
var x = $(this).closest('td').children('span').attr('id');
var y = $('.input-sm').val();
var p = $('.input-sm').val();
var z = $(this).closest('td').children('span');
$.ajax({
url: "process.php?id="+x+"&data="+y+"&capacity="+y,
type: 'GET',
success: function(s){
if(s == 'status'){
$(z).html(y);
$(z).html(p);}
if(s == 'error') {
alert('Error Processing your Request!');}
},
error: function(e){
alert('Error Processing your Request!!');
}
});
});
});
</script>
And heres my php file(process.php)
<?php
include("connect.php");
if
($_GET['id'],$_GET['capacity'] and $_GET['data'])
{
$id = $_GET['id'];
$data = $_GET['data'];
$capacity = $_GET['capacity'];
if(mysqli_query($con,"update mytable set name='$data',capacity='$data' where id='$id'")){
echo "success";
}
else{
echo 'failed';
}
}
?>
And my table in index.php
<tbody>
<?php
$query = mysqli_query($con,"select * from mytable");
$i=0;
while($fetch = mysqli_fetch_array($query))
{
if($i%2==0) $class = 'even'; else $class = 'odd';
echo'<tr class="'.$class.'">
<td><span class= "xedit external-event bg-brown" id="'.$fetch['id'].'">'.$fetch['name'].'</span></td>
<td><span class= "xedit external-event bg-brown" id="'.$fetch['id'].'">'.$fetch['capacity'].'</span></td>
</tr>';
}
?>
</tbody>
1) your just typo error : capacity=$data look this line and change it to capacity=$capacity :
if(mysqli_query($con,"update mytable set name='$data',capacity='$capacity' where id='$id'"))
2) And take look in If condition too .finally your code should be like this .
<?php
include("connect.php");
if($_GET['id'] && $_GET['capacity'] && $_GET['data'])
{
$id = $_GET['id'];
$data = $_GET['data'];
$capacity = $_GET['capacity'];
if(mysqli_query($con,"update mytable set name='$data',capacity='$capacity' where id='$id'"))
{
echo "success";
}
else
{
echo 'failed';
}
}
?>
You have error in your sql query. As you not passing correct parameters.
Please see below code.
$id = $_GET['id'];
$data = $_GET['data'];
$capacity = $_GET['capacity'];
// Check Sql
$query = "update mytable set name='$data',capacity='$capacity' where id='$id'";
if(mysqli_query($con,$query)){
echo "success";
} else{
echo 'failed';
}
I am trying to submit a form without refreshing the page and I want an alert message to appear when the button id=fav in clicked. this is the code but I don't know what i did wrong. Should it be on button click or on form submit?
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#f1").submit(function(){
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "bookpage.php",
data: {'fav':'fav'} ,
cache: false,
success: function(response){
if(response.message){
alert(response.message);
}
}
});
}
return false;
});
});
</script>
<form action="#read" method="post" id="f1">
<div class="r1">
<button class="down" name="download" title="Add to favorites">Download</button>
<li><a class="full" href="full.php?id=<?php echo $id; ?>">Full page</a>
</li>
<button class="d-later" name="dlater">Download later</button>
<button class="fav-button" type="submit" id="fav"></button>
</div>
</form>
PHP
if(isset($_POST['fav']) && $_POST['fav'] == 'fav' && fav_exists($u , $ii)== true){
$query = "DELETE FROM favorites WHERE bid='$ii' AND email='$u'";
$result = mysql_query($query);
if(! $result ) {
die('Could not delete data: ' . mysql_error());
} $response['message'] = 'My message';
echo json_encode($response);
}else if(isset($_POST['fav']) && $_POST['fav'] == 'fav' && fav_exists($u , $ii)== false){
$query = "INSERT INTO favorites (email,book, bid) VALUES('$u','$bname','$ii')";
$result = mysql_query($query);
if(! $result ) {
die('Could not enter data: ' . mysql_error());
}
$response['message'] = 'My message';
echo json_encode($response);
}
function fav_exists($u , $ii){
$query = "SELECT id FROM favorites WHERE email='$u' AND bid='$ii'";
$result = mysql_query($query);
$count = mysql_num_rows($result);
if($count >= 1) {
return true;
} else {
return false;
}
}
I think you are passing empty data, see example below how to pass some data; If you want to run ajax+php you need to pass some data
<?php if(isset($_POST['action'] && $_POST['action'] == 'my_action') {
// do stuff;
// to send json response use json_encode;
$response['message'] = 'My message';
echo json_encode($response);
}
$.ajax({
url: "my_php.php",
type: "POST",
data: { 'action' : 'my_action' },
success: function(response){
if(response.message){
alert(response.message);
}
}
});
Also i highly recommend using PHP PDO to make SQL queries - http://php.net/manual/en/book.pdo.php
upd:
$('#fav').click(function(){
do_ajax_request('you can pass different type of acitons as param');
});
function do_ajax_request(action) {
$.ajax({
url: "my_php.php",
type: "POST",
data: { 'action' : action },
success: function(response){
if(response.message){
alert(response.message);
}
}
});
}
And at your php file you can switch or if/else different functions depending on your action;
<?php if(isset($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'favorites':
$msg = 'favorites action called';
breake;
case 'not fav':
$msg = 'not fav called';
breake;
default:
$msg = 'Nothing passed';
breake;
}
$Response['msg'] = $msg;
echo json_encode($Response);
}
This is what i use for the same task.
HTML
<form action="" method="post">
name:<input type="text" name="user" /> <br/>
<p><input type="submit" /></p>
</form>
JS
$(function() {
$('form').submit(function(e) {
e.preventDefault(); // Stop normal submission
data = $('form').serializeArray();
alert(JSON.stringify(data));
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'inc/update.php',
data: {
json: JSON.stringify(data)
},
dataType: 'json'
}
});
});
return false;
});
PHP
$str_json = file_get_contents('php://input');
$str_json = urldecode($str_json);
$str_json = str_replace('json=[', '', $str_json);
$str_json = str_replace(']', '', $str_json);
$arr_json = json_decode($str_json, true);
$name = $arr_json['name'];
$pdo = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_password);
$update = $pdo->prepare("UPDATE user SET name='".$name."' WHERE id='3';");
$update->execute();
This is my HTML Code
<input type="text" class="form-control" id="stfmail" name="staffmail" placeholder="E-Mail" required="required"><span id="result"></span>
In jQuery Ajax
<script type="text/javascript">
$(document).ready(function(){
$("#stfmail").keyup(function() {
var name = $(this).val();
if(name.length > 1)
{
$("#result").html('checking...');
$.ajax({
type : 'POST',
url : '../include/check_availability.php',
data : $(this).serialize(),
success : function(data)
{
$("#result").html(data);
}
});
return false;
}
else
{
$("#result").html('');
}
});
});
</script>
PHP
if($_POST)
{
$username = $_POST['name'];
$ob->useravailable($username);
}
public function useravailable($username)
{
$stmt=$this->conn->prepare("select user_name from users where user_name=:uname and delet='0'");
$stmt->execute(array(':uname'=>$username));
if($stmt->rowCount()>0)
{
echo "<span style='color:brown;'>Sorry username already taken !!!</span>";
}
else
{
echo "<span style='color:green;'>available</span>";
}
}
Here i type a username..but in useravailable function only else part is working.. I type Existing username it works the else part available message is shown..
Please help me
thanks
<script type="text/javascript">
$(document).ready(function(){
$("#stfmail").keyup(function() {
var name = $(this).val();
if(name.length > 1)
{
$("#result").html('checking...');
$.ajax({
type : 'POST',
url : '../include/check_availability.php',
data : $(this).serialize(),
success : function(data)
{
$("#result").html(data);
if(data) {
$(".redbold").html('already this username is there ').show();
$("#username").focus();
}
}
});
return false;
}
else
{
$("#result").html('');
}
});
});
</script>
if($_POST)
{
$username = $_POST['name'];
$query = mysql_query("SELECT user_name from users where user_name ='".$username ."' ", $con);
while ($row = mysql_fetch_assoc($query)) {
echo $row['user_name '];
}
}