Thanks for the help mighty Johan. but I cant get get my db to update. If you do have time please look over my two files and tell me what the F is wrong
my hire_staff.php
<?php
session_start();
include("header.php");
?>
<?php
$chief_aerodynamicist = $staff['chief_aerodynamicist'];
$chief_designer = $staff['chief_designer'];
$commercial_director = $staff['commercial_director'];
$pit_crew = $staff['pit_crew'];
$technical_director = $staff['technical_director'];
?>
<head>
<script>
function bye(){
alert('bye');
}
$(document).ready(function(){
function hire(){
$.ajax({
url: "update.php",
type: "POST",
data: {uid: 12341234}, //this sends the user-id to php as a post variable, in php it can be accessed as $_POST['uid']
success: function(data){
data = JSON.parse(data);
//update some fields with the updated data
//you can access the data like 'data["driver"]'
}
});
}
});
</script>
</head>
<center><h2>You can hire new staff here</h2></center>
<table cellpadding="3" cellspacing="5">
<tr>
<td>Chief Aerodynamicist:</td>
<td><i><?php echo "Level $chief_aerodynamicist"; ?></i></td>
<td><form><input type="button" value="Hire!" onClick="hire();"</form></td>
</tr>
<tr>
<td>Chief Designer:</td>
<td><i><?php echo "Level $chief_designer"; ?></i></td>
</tr>
<tr>
<td>Commercial Director:</td>
<td><i><?php echo "Level $commercial_director"; ?></i></td>
</tr>
<tr>
<td>Pit Crew:</td>
<td><i><?php echo "Level $pit_crew"; ?></i></td>
</tr>
<tr>
<td>Technical Director:</td>
<td><i><?php echo "Level $technical_director"; ?></i></td>
</tr>
</table>
<?php
include("footer.php");
?>
My test1.php file
<?php
include("functions.php");
connect();
if(isset($_POST['uid'])){
connect();
mysql_query("UPDATE `staff` SET `driver` = '3' WHERE `id`='".$_SESSION['uid']."'") or die(mysql_error());
$query = mysql_query("SELECT FROM `staff` WHERE `id`='".$_POST['uid']."'")or die(mysql_error());
$results = mysql_fetch_assoc($query);
echo json_encode($results);
}
?>
its actually the staff in the 's that I want to update but driver is also in the same table
Use jQuery and Ajax:
$(document).ready(function(){
$("#button").click(function(){
$.ajax({
url: "update.php",
type: "POST",
data: {uid: 12341234}, //this sends the user-id to php as a post variable, in php it can be accessed as $_POST['uid']
success: function(data){
data = JSON.parse(data);
//update some fields with the updated data
//you can access the data like 'data["driver"]'
}
});
});
});
//the button
<input type="button" id="button" value="Hire!"/>
//update.php
if(isset($_POST['uid'])){
//connect to the db etc...
mysql_query("UPDATE `staff` SET `driver` = '3' WHERE `id`='".$_POST['uid']."'") or die(mysql_error());
//this'll send the new statistics to the jquery code
$query = mysql_query("SELECT FROM `staff` WHERE `id`='".$_POST['uid']."'")or die(mysql_error());
$results = mysql_fetch_assoc($query);
echo json_encode($results);
}
with "update some fields" in the success function of the ajax call, I mean that you can update the statistics on the page which you just changed in the database, so that the statistics on the webpage automatically change in both the database and on the page itself
Edit
Put this in the header:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
function bye(){
alert('bye');
}
$(document).ready(function(){
$("#button").click(function(){
$.ajax({
url: "test1.php",
type: "POST",
data: {uid: 12341234}, //this sends the user-id to php as a post variable, in php it can be accessed as $_POST['uid']
success: function(data){
data = JSON.parse(data);
//update some fields with the updated data
//you can access the data like 'data["driver"]'
}
});
});
});
</script>
Then give your button the id 'button' like this:
<form><input type="button" id="button" value="Hire!"/></form>
Make sure that the url parameter of the ajax request (url: "test1.php",) is pointing to the right php page.
I hope this helped!
Edit
This is the code if you want to select a driver:
<form><input type="button" class="button" id="3" value="Hire!"/></form> //the id is different for every guy
The javascript code:
$(document).ready(function(){
$(".button").click(function(e){
$.ajax({
url: "test1.php",
type: "POST",
data: {colID: e.target.id}, //this sends the user-id to php as a post variable, in php it can be accessed as $_POST['uid']
success: function(data){
data = JSON.parse(data);
//update some fields with the updated data
//you can access the data like 'data["driver"]'
}
});
});
});
As you can see, I changed the # into a ., I added the argument e to the callback function and I added the colID to the data object.
This'll be the new PHP code:
if(isset($_POST['colID'])){
//connect to the db etc...
$colID = mysql_real_escape($_POST['colID']); //for security
$userID = mysql_real_escape($_SESSION['uid']);
mysql_query("UPDATE `staff` SET `$colID` = 'newValue' WHERE `id`='$userID'") or die(mysql_error());
//this'll send the new statistics to the jquery code
$query = mysql_query("SELECT FROM `staff` WHERE `id`='$userID'")or die(mysql_error());
$results = mysql_fetch_assoc($query);
echo json_encode($results);
}
I hope this is what you meant :)
Related
Good day,
I experimented with a simple JS math calculation.
this calculation works as expected, but additionally I wanted to store the math calculation in a database where all values (the input fields and the result .textContent) should be stored. Afterwards the calculation should be named and populated by a dropdown menu, but that's a different story.
So, I added some nice ajax code, see this: https://phppot.com/php/php-mysql-inline-editing-using-jquery-ajax/
Everything works as expected, the only issue I have is that I don't get the result of the math automatically updated into the database, so if I change the math input fields or refresh the site, the result is lost.
I put up an live example with mysql backened to show you exactly what I mean:
http://90.153.105.10:8888/djdp42Bjjr39399nfjjj39xleit832991vnJ39921/live/test.php
dbcontroller.php:
<?php
class DBController {
private $host = "ip";
private $user = "root";
private $password = "thepassword";
private $database = "the database";
private $conn;
function __construct() {
$this->conn = $this->connectDB();
}
function connectDB() {
$conn = mysqli_connect($this->host,$this->user,$this->password,$this->database);
return $conn;
}
function runQuery($query) {
$result = mysqli_query($this->conn,$query);
while($row=mysqli_fetch_assoc($result)) {
$resultset[] = $row;
}
if(!empty($resultset))
return $resultset;
}
function numRows($query) {
$result = mysqli_query($this->conn,$query);
$rowcount = mysqli_num_rows($result);
return $rowcount;
}
function executeUpdate($query) {
$result = mysqli_query($this->conn,$query);
return $result;
}
}
?>
saveedit.php
<?php
require_once("dbcontroller.php");
$db_handle = new DBController();
$result = $db_handle->executeUpdate("UPDATE database_table set " . $_POST["column"] . " = '".$_POST["editval"]."' WHERE id=".$_POST["id"]);;
?>
test.php
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
function showEdit(editableObj) {
$(editableObj);
}
function saveToDatabase(editableObj,column,id) {
$(editableObj);
$.ajax({
url: "saveedit.php",
type: "POST",
data:'column='+column+'&editval='+editableObj.innerHTML+'&id='+id,
success: function(data){
$(editableObj);
}
});
}
</script>
</head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<style>}
</style>
<body>
<table class="tbl-qa">
<tr>
<td >DESCRIPTION:</td>
<td contenteditable="true" id="Event" onBlur="saveToDatabase(this,'event','0')" onClick="showEdit(this);">This is a simple stored description for the following math. As you can see, the result and math values are editiable. But the RESULT is not beeing stored nor will it get calculated when refreshing the site :/<br></td>
</table>
<hr>
<table class="tbl-qa">
<tr>
<td>VALUE 1:</td>
<td contenteditable="true" id="Tank" size="2" oninput="output();output2();output3();" onBlur="saveToDatabase(this,'Tank','0')" onClick="showEdit(this);">10</td>
<td>VALUE 2:</td>
<td contenteditable="true" id="Spritverbrauch" size="2" oninput="output();output3();" onBlur="saveToDatabase(this,'Spritverbrauch','0')" onClick="showEdit(this);">2</td>
</tr>
<tr>
<p></p>
<td>RESULT: </td>
<td contenteditable="true" size="2" id="StintlangeRd" oninput="output();output3();" onBlur="saveToDatabase(this,'StintlangeRd','0')" onClick="showEdit(this);"></td>
</tr>
</table>
<script type="text/javascript">
function output(){
var value2 = document.getElementById('Tank').textContent;
var value3 = document.getElementById('Spritverbrauch').textContent;
document.getElementById('StintlangeRd').innerHTML = (parseFloat(value2) / parseFloat(value3)).toFixed(2);
}
</script>
<script type="text/javascript">
setTimeout(function(){
location.reload();
},60000);
</script>
</body>
</html>
After updating try to run a query with 'COMMIT' to confirm the update on mysql database!
You could check if the values arrive at your update script. I think the problem may lie within your AJAX call:
function saveToDatabase(editableObj,column,id) {
$(editableObj);
$.ajax({
url: "saveedit.php",
type: "POST",
data:'column='+column+'&editval='+editableObj.innerHTML+'&id='+id,
success: function(data){
$(editableObj);
}
});
}
Inside this function, you set the data by passing a query string. Instead of a query string, you should use a plain old javascript object.
data: {
column : column,
editval : editableObj.innerHTML,
id : id
},
Change Ajax Post Data you are sending data in GET method and trying to get data by POST Method
function saveToDatabase(editableObj,column,id) {
$.ajax({
url: "saveedit.php",
type: "POST",
data: {
column : column,
editval : editableObj.innerHTML, // just check it or use $(editableObj).html() if necessary
id : id
},
success: function(data){
// you will get your response here which is sent from server
}
});
}
So i have 2 files index.php and changeLikeDislike.php. I think the issue is where javascript is trying to get the type and id but I do not know how I would go about that. My javascript function is being called in the foreach->li->divs. It was working before like this: data: dataString, but I added schoolId into data of ajax as well so it's like this now data: {dataString:dataString, schoolId:schoolId},
index.php
<?php
$last_id = 0;
foreach ($list as $rs) {
$last_id = $rs['id']; // keep the last id for the paging
?>
<li>
<div style="width:100%; color:#000;">
<?php echo '<div class="product_like thumb-div"><img src="like.png" class="rating-image " onclick=changeLikeDislike("like","'.$rs['id'].'")> <br><span id="product_like_'.$rs['id'].'">'.$rs['pLike'].'</span></div>';?>
<?php echo '<div class="product_dislike"><img src="dislike.png" class="rating-image" onclick=changeLikeDislike("dislike","'.$rs['id'].'")><br> <span id="product_dislike_'.$rs['id'].'">'.$rs['pDislike'].'</span></div>';?>
</div>
</li>
<?php
}
?>
<script type="text/javascript">
//begin like and dislike
function changeLikeDislike(type,id){
var dataString = 'id='+ id + '&type=' + type;
$.ajax({
type: "POST",
url: "changeLikeDislike.php",
data: {dataString:dataString, schoolId:schoolId},
cache: false,
success: function(result){
if(result){
console.log('working');
}
}
});//end ajax
}
schoolId works in data but not dataString in ajax How would i go about grabbing those. My php file for reference:
//checks if school page id was brought and stores into variable
if (isset($_POST['schoolId'])) {
$schoolIdFinal = $_POST['schoolId'];
}else {
echo "nope";
}
if (isset($_POST['type'])) {
$type = $_POST['type'];
}else {
echo "nope type";
}
if (isset($_POST['id'])) {
$id = $_POST['id'];
}else {
echo "nope id";
}
my page is echoing out "nope type nope id"
Please change
data: {dataString:dataString, schoolId:schoolId},
to
data: {type:type, id:id, schoolId:schoolId},
to match the params to your PHP script.
data can either be a query string (like your dataString) OR a json struct (like {type:type, id:id, schoolId:schoolId}).
See the documentation of jQuery.ajax():
"The data option can contain either a query string of the form key1=value1&key2=value2, or an object of the form {key1: 'value1', key2: 'value2'}."
see http://api.jquery.com/jquery.ajax/
The issue is in the data bracket. change
data: {dataString:dataString, schoolId:schoolId}
to
data: {dataString:'dataString', schoolId:'schoolId'}
next time do a print_r of $_REQUEST or $_POST to see what fields are being recognized and in this case it looks like its not detecting anything.
Here I want to retrieve data from a page called using ajax call and set it as textbox value.I'm not so perfect with ajax but I've tried like this:
<tr>
<td style="text-align:left"> <label for="pat_id" >Patient ID</label></td>
<td><input type="text" name="patient_id" id="patient_id" readonly></td>
</tr>
Ajax call code:
$(document).ready(function()
{
$.ajax({
type: "GET",
url:"retriveID.php",
data: ({type: 'patient'}),
success:function(html){
$("#patient_id").html(html);
}
});
});
And retriveID.php:
<?php
include("db.php");
$type = $_GET['type'];
if($type=='patient')
{
$retrive_id=mysql_query("select patient_id from patient order by patient_id desc limit 1") or die (mysql_error());
$row=mysql_fetch_array($retrive_id);
$patient_id="PAT".$row['0']+1;
}
?>
I know this is not proper calling or requesting data.
Your have not echo your result.
<?php
include("db.php");
$type = $_GET['type'];
if($type=='patient')
{
$retrive_id=mysql_query("select patient_id from patient order by patient_id desc limit 1") or die (mysql_error());
$row=mysql_fetch_array($retrive_id);
$patient_id="PAT".$row['0']+1;
echo $patient_id;
}
?>
and use
$("#patient_id").val(html);
Replace $("#patient_id").html(html); with $("#patient_id").val(html);
You need to echo fetched value
echo $patient_id;
and then need to use .val(value) instead of .html() as patient_id is an input element.
$("#patient_id").val(html);
I have problem with deleting records from database, using ajax and jquery. If i click to button nothing happens. there is my css:
<button class='delete_p' id_p='<?php echo $post_id; ?>'>x</button>"
<script type="text/javascript" src="jquery-1.11.1.js"></script>
<script src="delete_post.js"></script>
and there is ajax that i'm using:
$(document).ready(function(){
$('.delete_p').click(function(){
var del_id = $(this).attr('id_p');
$.ajax({
type:'POST',
url:'delete_post.php',
data:'delete_id='+del_id,
});
});
});
and there is delete_post.php that i'm using:
<?php
include 'esas/core/database/connect.php';
$id = $_POST['delete_id'];
$query = "DELETE FROM `status` WHERE `id` = '$id'";
?>
data shouldn't be a string but a JavaScript object:
$.ajax({
type: 'POST',
url: 'delete_post.php',
data: {
delete_id: del_id
}
});
I want to try to get some value from page cart.php from and ajax call, but its not working.
Ajax code is below:
function temp_sell(id) {
//var p_id=document.getElementById('temp').value;
alert(p_id);
$.ajax({
type: "POST",
url: "temp_sell.php",
data: "value=" + p_id,
success: function (message) {
alert(message);
$("#your_cart").html(message);
}
});
}
temp_sell.php is below where I want to show some products details
<?php
include("connection.php");
echo $p_id = $_POST['value'];
$qty=1;
$query="SELECT * FROM product WHERE id='$p_id'";
$result=mysql_query($query);
while($data=mysql_fetch_array($result))
{
?>
<form>
<table>
<tr>
<img src="<?php echo "img/".$data['image'];?>"/>
<strong><?php echo $data['pro_name'];?></strong>
<strong><?php echo $data['price'];?></strong>
<input type="text" value="<?php echo $qty;?>"/>
</tr>
</table>
</form>
<?php
}
?>
p_id is undefined, you have commented the p_id value or change temp_sell(p_id).
function temp_sell(p_id)
instead of
function temp_sell(id)
Reference comments : Ajax call with javascript not working
Do this :
function temp_sell(id){
var p_id=document.getElementById('temp').value; // <--- uncomment this line
alert(p_id);
$.ajax({
type: "POST",
url: "temp_sell.php",
data: {value:p_id}, // <--- change this
success: function(message){
alert(message);
$("#your_cart").html(message);
}
});
}