Edit multiple values in ajax - php

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

Related

Ajax response not returning

I am having a table with data where I have an action button in last column to delete that particular row. I want to make the delete via ajax and without refreshing the page. I am using the following code but their is no response coming from the ajax page. Also the queries at the ajax page is not executing. Can I have some insight over what could be possibly wrong.
<script type="text/javascript" >
$(function() {
$(".delbutton").click(function() {
var del_id = $(this).attr("id");
var info = 'id=' + del_id;
var $tr = $(this).closest('tr');
if (confirm("Sure you want to delete this post? This cannot be undone later.")) {
$.ajax({
type : "POST",
url : "delete_entry.php", //URL to the delete php script
data: info,
success : function(response) {
if(response=='deletion success'){
$tr.find('td').fadeOut(1000,function(){ $tr.remove(); });
}
}
});
}
return false;
});
});
</script>
And at delete_entry.php
<?php
header('Content-Type: application/json');
session_start();
require("../config.php");
require("../Database.class.php");
require("../site.php");
$db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
$fnc=new site_functions($db);
$id = $_POST['id'];
$deleted_date = date("Y-m-d h:i:s");
$deleted_by = $_SESSION['session_admin_id'] ;
$nots = $db->idToField("tbl_ques","notes",$id);
if ($nots == "")
{
$date_string = "last deleted on|".$deleted_date."|" ;
}
else {
$date_string = $nots."last deleted on|".$deleted_date."|" ;
}
$fnc->update_is_not_deleted_for_Pearsonvue("tbl_ques",$id, "$deleted_date", $deleted_by);
$notes_data = array("notes"=>$date_string);
if($db->query_update("tbl_ques", $notes_data, "id=$id")){
http_response_code();
echo json_encode('deletion success');
}else{
http_response_code(204);
}
?>
Change your java script function as below
<script type="text/javascript" >
$(function() {
$(".delbutton").click(function() {
var del_id = $(this).attr("id");
var info = 'id=' + del_id;
if (confirm("Sure you want to delete this post? This cannot be undone later.")) {
$.ajax({
type : "POST",
url : "delete_entry.php", //URL to the delete php script
data: info,
//changes from
success : function(response) {
if(response=='deletion success'){
$(this).parents(".record").animate("fast").animate({
opacity : "hide"
}, "slow");
}
}
});
//changes to
}
return false;
});
});
</script>
Also change you php file
<?php
header('Content-Type: application/json'); // Add this line its must
session_start();
$db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
$id = $_POST['id'];
$deleted_date = date("Y-m-d h:i:s");
$deleted_by = $_SESSION['session_admin_id'] ;
$nots = $db->idToField("tbl_question","notes",$id);
if ($nots == "")
{
$date_string = "last deleted on|".$deleted_date."|" ;
}
else {
$date_string = $nots."last deleted on|".$deleted_date."|" ;
}
$fnc->update_is_not_deleted_for_Pearsonvue("tbl_question",$id, "$deleted_date", $deleted_by);
$notes_data = array("notes"=>$date_string);
//changes from
if($db->query_update("tbl_question", $notes_data, "id=$id")){
http_response_code();
echo json_encode('deletion success');
}else{
http_response_code(204);
}
//changes to
?>

display data from database using ajax,mysql,php

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

Ajax reload shoping card after submit data

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

how to update number without reloading

I am working on a voting system in jquery. I have it where a user can vote up or if they change their mind vote down and it deducts from the upvote and puts it in on the down vote. But my problem is I cant get both numbers to refresh when a vote is selected so it just uses the original number instead of the updated number.
Vote Page
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(".vote").click(function() {
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id=' + id;
var parent = $(this);
if (name == 'up') {
$.ajax({
type: "POST",
url: "up_vote.php",
data: dataString,
cache: false,
success: function(html) {
parent.html(html);
}
});
} else {
$.ajax({
type: "POST",
url: "down_vote.php",
data: dataString,
cache: false,
success: function(html) {
parent.html(html);
}
});
}
return false;
});
});
</script>
<?php
$sql=mysql_query("SELECT * FROM uploads LIMIT 9");
while($row=mysql_fetch_array($sql))
{
$msg=$row['title'];
$mes_id=$row['id'];
$up=$row['up'];
$down=$row['down'];
?>
<a href="" class="vote" id="
<?php echo $mes_id; ?>" name="up">
<?php echo $up; ?> up
</a>
<div class='down'>
<a href="" class="vote" id="
<?php echo $mes_id; ?>" name="down">
<?php echo $down; ?>
</a>
</div>
<div class='box2' >
<?php echo $msg; ?>
</div>undefined</div>undefined
<?php } ?>
The up_vote.php page..
(down_vote.php is exactly the same as up_vote except it just changes up to down.)
<?php
include("config.php");
$ip = $_SERVER['REMOTE_ADDR'];
if ($_POST['id']) {
$id = $_POST['id'];
$id = mysql_escape_String($id);
//Verify IP address in Voting_IP table
$ip_sql = mysql_query("select ip from votes where img_id='$id' and ip='$ip'");
$count = mysql_num_rows($ip_sql);
if ($count == 0) {
// Update Vote.
$sql = "UPDATE uploads SET up=up+1 WHERE id='$id'";
mysql_query($sql);
// Insert IP address and Message Id in Voting_IP table.
$sql_in = "insert into votes (id,img_id,ip,type) values ('','$id','$ip','up')";
mysql_query($sql_in);
} else {
//if already voted change it..
$result = mysql_query("SELECT * FROM votes WHERE img_id='$id' AND ip='$ip'");
while ($row = mysql_fetch_array($result)) {
$vote_type = $row['type'];
}
if ($vote_type == 'down') {
$up = mysql_query("UPDATE uploads SET up=up+1 WHERE id='$id'");
$down = mysql_query("UPDATE uploads SET down=down-1 WHERE id='$id'");
$vote = mysql_query("UPDATE votes SET type=up WHERE img_id='$id' AND ip='$ip'");
}
}
$result = mysql_query("select up from uploads where id='$id'");
$row = mysql_fetch_array($result);
$up_value = $row['up'];
echo $up_value;
}
?>
Not an answer but too long for a comment. This script:
while ($row = mysql_fetch_array($result)) {
$vote_type = $row['type'];
}
if ($vote_type == 'down') {
/* ... */
}
I don't think you need it like it is now. You are actually only using the last fetched row, not all of them. If that's your intention (because there's only one), then you don't need the while() at all. You could change it for:
$row = mysql_fetch_row($result);
$vote_type = $row['type'];
if ($vote_type == 'down') {
/* ... */
}
Furthermore, I'd recommend to change your code to PDO. It's more secure and mysql_* is deprecated.

Reload a div only if there is new data

If I create a script like this, then it will reload the div every 2.5 seconds. I want a script that only displays if there is new data, if there is no new data it does not have to reload...
<script type="text/javascript">
function dispMsg() {
$("#displayMessage").load('load.php');
var newscrollHeight = $("#displayMessage").attr("scrollHeight") - 20;
$("#displayMessage").animate({ scrollTop: newscrollHeight }, 'normal');
}
setInterval (dispMsg, 2500);
});
</script>
<div id="displayMessage"></div>
and here is the load.php:
$sql = "SELECT * FROM message ORDER BY id DESC LIMIT 1";
$query = mysql_query($sql);
while ($result = mysql_fetch_array($query)) {
$id = $result['id'];
$from = $result['user_01'];
$to = $result['to_usr'];
$message = $result['message_01'];
$date = $result['date_send'];
echo "<span class='from'> $from </span>"
. "<span class='message'> $message </span> <br/>";
}
use the parameters and call back of $.load()
$.load(url, {param1:value, param2:value}, function(result){
if(result >5){
//do something
}
)
Example:
<?php
if($_REQUEST['action'] == 'check'){
if($_REQUEST['lastId'] < 5 ){
echo $_REQUEST['lastId']+1;
die;
}
}
if($_REQUEST['action'] == 'load'){
echo 'some conntent!';
die;
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var lastId = 0;
function dispMsg() {
$.get('tmp.php', {action:'check', lastId: lastId}, function(responce){
if(responce !== 0){
alert(responce);
$('#displayMessage').load('tmp.php', {action:'load'});
}
});
}
setInterval (dispMsg, 2500);
});
</script>
<div id="displayMessage">1</div>
You can send the last message id with each request. If the last message of your query is greater than the id sent, send the response. Otherwise send nothing.
function load_messages(){
var last = $('#messagewindow p:last').attr('id');
$.ajax({
url: base_url + "load.php",
type: "POST",
data: {
last: last
},
cache: false,
success: function(html){
//insert message
}
});
}
You can send the id as the id attribute in your HTML. Each message in the chat window is sent as a paragraph with some message id such as id="133".
Expanding on #Pé de Leão's solution, here's something more simple:
<?php
$sql = "SELECT * FROM message ORDER BY id DESC LIMIT 1";
$mysqli = new mysqli("host", "user", "pass");
if ($result = $mysqli->query($sql)) {
$msg = $result->fetch_assoc();
if (isset($_REQUEST['last']) && $msg['id'] != $_REQUEST['last']) {
echo "<span id='${msg['id']}' class='from'>${msg['user_01']}</span>";
}
}
And on the client side:
function dispMsg() {
var last = $('#displayMessages span.from').attr('id');
$.get(baseUrl + '/load.php', { last: last }, function(result) {
if (result) {
$('#displayMessages').html(result);
}
});
}
Note that this replaces everything in displayMessages.

Categories