ajax value fetched but unable to store - php

When I select something in bill.php, it ajax call and get value from get user.php then it display content on bill.php the page but how could I hold those value in a variable in bill.php page for further use in php
<?php
include('db.php');
?>
<html>
<head>
<style>
table, tr th{
border: green;
}
th {
}
</style>
<script type="text/javascript">
function updatesum()
{
document.form.sum.value = (document.form.sum2.value -0);
document.form.sumone.value = (document.form.sum3.value -0) ;
document.form.sumtotal.value = (document.form.sum.value -0) * (document.form.sumone.value -0);
document.form.sumtotalgiven.value=(document.form.sumtotalmoney.value -0) - (document.form.sumtotal.value -0);
}
</script>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
//document.getElementById("txtHin").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 (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
//document.getElementById("txtHin").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
}
</script>
<script>
function shoUser(str) {
if (str == "") {
document.getElementById("txtHin").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 (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHin").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body bgcolor="#C7CBE1">
<form method="get" name="form">
<table border="0" bordercolor="#D83E41">
<tr>
<td> medicine </td>
<td> price batchno
expire date</td>
<td>
quantity</td>
<td>
Total </td>
</tr>
<tr>
<td>
<?php
$qry="select * from inventory";
$rs=mysql_query($qry);
?>
<select name="user" onchange="showUser(this.value)">
<option value=>selet medicine name</option>
<?php
while($rw=mysql_fetch_array($rs)){
?>
<option value="<?php echo $rw['id']?>"><?php echo $rw['medicine']?></option>
<?php
}
?>
</select>
</td>
<td>
<div id="txtHint">
</div>
</td>
<td>
<input type="text" name="sum2" style="width: 70px" onChange="updatesum()" ></td>
<td>
<input name="sum" readonly " style="width: 70px"></td>
</tr>
<tr>
<td>
<?php
$qry="select * from inventory";
$rs=mysql_query($qry);
?>
<select name="user" onchange="shoUser(this.value)">
<option value=>selet medicine name</option>
<?php
while($rw=mysql_fetch_array($rs)){
?>
<option value="<?php echo $rw['id']?>"><?php echo $rw['medicine']?></option>
<?php
}
?>
</select>
</td>
<td>
<div id="txtHin">
</div>
</td>
<td>
<input type="text" name="sum3" style="width: 70px" onChange="updatesum()" ></td>
<td>
<input name="sumone" readonly " style="width: 70px"></td>
<td>
</td>
<tr></tr>
<tr></tr>
<tr></tr>
<tr></tr>
<tr></tr>
<tr></tr>
<tr></tr>
<tr></tr>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td> total<input name="sumtotal" readonly style="border:0px;"> </td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td> paid<input type="text" name="sumtotalmoney" style="border:0px;" onChange="updatesum()"> </td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td> Return<input name="sumtotalgiven" readonly style="border:0px;" > </td>
</tr>
</table>
</form>
<br>
</body>
</html>
<?php
include("db.php");
?>
<!DOCTYPE html>
<html>
<head>
<style>
table {
border-collapse: collapse;
}
table, td, th {
/* border: 1px solid black;*/
/* padding: 5px;*/
text-align: center;
}
th {text-align: left;}
</style>
<body>
<?php
$q = intval($_GET['q']);
//echo $q;
$qry="SELECT * FROM inventory WHERE id = '".$q."'";
$rs=mysql_query($qry);
?>
<?php
while($rw=mysql_fetch_array($rs)){
?>
<table>
<tr>
<td>
<?php echo "&nbsp". "&nbsp". "&nbsp". "&nbsp". "&nbsp" . "&nbsp". "&nbsp". "&nbsp" ?>
<?php echo $rw['price']?> <?php echo "&nbsp". "&nbsp" . "&nbsp" . "&nbsp" . "&nbsp". "&nbsp". "&nbsp". "&nbsp". "&nbsp". "&nbsp". "&nbsp". "&nbsp"
. "&nbsp". "&nbsp". "&nbsp" ?>
<?php echo $rw['batchno'] ?>
<?php echo "&nbsp". "&nbsp" . "&nbsp" . "&nbsp" . "&nbsp". "&nbsp". "&nbsp". "&nbsp". "&nbsp". "&nbsp". "&nbsp". "&nbsp"
. "&nbsp". "&nbsp". "&nbsp" ?>
<?php echo $rw['expire'] ?>
</td>
</tr>
</table>
<?php
}
?>
</body>
</html>

Read more about sessions in php.
If you need to store some values between php files you can do it like:
<?php
session_start();
$_SESSION['myVariable'] = $_GET['myVariable'];
In another php file you can get the previous defined variable as:
<?php
session_start();
echo $_SESSION['myVariable'];

Related

how to prevent the $result in mysql query from looping the wrong way

I have a problem in my following code. I want all data associated with the selected id of the dropdownlist to be viewed in the textboxes as well as inside the table.
When I ran my code, the result of the query created a repetitive result because of the data inside the database is more than 1 row.
What am I missing here? Did Inmake mistakes in the normalization of the database? Can somebody help me?
below is my code in search.php
<?php
//including the database connection file
include_once("dbconnect.php");
$query1 = "SELECT * FROM kursus";
$result1 = mysqli_query($mysqli, $query1);
$result2 = mysqli_query($mysqli, "SELECT * FROM kursus");
?>
<html>
<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","search2.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
Carian : <select id="id_kursus" name="id_kursus" onchange="showUser(this.value)">
<option>Sila Pilih</option>
<?php while($row1 = mysqli_fetch_array($result1)){
echo "<option value='".$row1['id_kursus']."'>".$row1['nama_kursus']."</option>";
}
?>
</select>
</form>
<br>
<div id="txtHint"><b>Result will be display here.</div>
</body>
</html>
below is my codes in search2.php
<html>
<head>
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','root','admin','tracer');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql = "SELECT
a.*,
b.*,
c.*,
a.id_kursus AS id_kursus
FROM pelatih a
LEFT JOIN kursus b ON b.id_kursus = a.id_kursus
RIGHT JOIN status_pelatih c ON c.id_status_semasa = a.id_status_semasa
WHERE a.id_kursus = '.$q.'";
$result = mysqli_query($con,$sql);
$no = 1;
while($row = mysqli_fetch_array($result)) {
echo "<table class='table1'>
<tr>
<td>Kod Kursus : </td>
<td><input type='text' value= '$row[kod_kursus]'></td>
</tr>
<tr>
<td>Nama Kursus : </td>
<td><input type='text' size='40' value= '$row[nama_kursus]'></td>
</tr>
<tr>
<td>Sesi : </td>
<td><input type='text' value= '$row[sesi_kursus]''></td>
</tr>
<tr>
<td>Batch : </td>
<td><input type='text' value= '$row[batch_kursus]'></td>
</tr>
<tr>
<td>Tempoh Kursus :</td>
<td><input type='date' value= '$row[tarikh_mula_kursus]'> Hingga <input type='date' value= '$row[tarikh_tamat_kursus]'></td>
</tr>
<tr>
<td>Program Tajaan : </td>
<td><input type='text' value= '$row[penaja_program]'></td>
</tr>
<tr>
<td>Peruntukan : </td>
<td><input type='text' value= '$row[peruntukan]'></td>
</tr>
<tr>
<td>Tarikh Kajiselidik : </td>
<td ><input type='date' value= '$row[tarikh_kajiselidik]'></td>
</tr>
<tr>
<td>Cara Kajiselidik : </td>
<td ><input type='text' value= '$row[cara_kajiselidik]'></td>
</tr>
</table>
<br>";
echo "<table class='table2'>
<tr>
<th rowspan='2'>Bil</th>
<th colspan='4'>Nama dan Butiran Pelatih</th>
<th colspan='6'>Maklumat Tracer Study</th>
</tr>
<tr>
<th>Nama Pelatih</th>
<th>No. K/P</th>
<th>No. Telefon</th>
<th>Status Semasa</th>
<th>Nama Syarikat</th>
<th>Alamat Syarikat</th>
<th>No. Telefon</th>
<th>Nama Jawatan</th>
<th>Tangga Gaji</th>
<th>Catatan</th>
</tr>";
echo '<tr>
<td>'.$no.'</td>
<td>'.$row['nama_pelatih'].'</td>
<td>'.$row['ic_pelatih'].'</td>
<td>'.$row['tel_pelatih'].'</td>
<td>'.$row['status_semasa_pelatih'].'</td>
<td>'.$row['nama_syarikat'].'</td>
<td>'.$row['alamat_syarikat'].'</td>
<td>'.$row['tel_syarikat']. '</td>
<td>'.$row['jawatan'].'</td>
<td> RM'.$row['tangga_gaji'].'</td>
<td>'.$row['catatan'].'</td>
</tr>';
$no++;
}
echo "</table>";
mysqli_close($con);
?>
</body>
</html>

Cant Run javascript in AJAX file

I have a php file and am sending variables from php to ajax file and everything is running great , however when i run javascript in the ajax file
nothing appear like am alerting a msg , nothing is appear , is there any conflict between ajax and javascript ?
This is in the ajax file
<script type="text/javascript" src="js/library.js"></script>
<script type="text/javascript" src="js/jquery.js"></script>
<?php
session_start();
include("mysqlconnection.php");
if (!isset($_SESSION['username'])) {
echo "<h2 align='center'>Warning: You are not currently signed in </h2>";
die ("<script type = 'text/javascript' language = 'JavaScript'>window.setTimeout(\"location.href='index.php'\", 1000); </script>");
}
$uid=$_SESSION['uid'];
$code = $_GET['user'];
$qty = $_GET['qty'];
$custid = $_GET['custid'];
$warehouseid = $_GET['warehouseid'];
if ($code==''){
$sql1 = "SELECT * FROM itemscopy WHERE uid='$uid'";
$result1=mysql_query($sql1,$con);
if(!$result1)die("Couldn't execute".mysql_error());
?>
<table border="0" width="100%" align="center">
<thead>
<tr>
<th>Code</th>
<th>Code 2</th>
<th>Description</th>
<th>Discount%</th>
<th>Discount Amount</th>
<th>Quantity</th>
<th>Price</th>
<th>Amount</th>
<th>After Discount</th>
<th>Warehouse</th>
</tr>
</thead>
<?php
for($counter=0;$row1=mysql_fetch_assoc($result1);$counter++){
$wid=$row1['warehouseid'];
$selwarehouse="SELECT * FROM warehouse
WHERE Id='$wid'";
$runwarehouse=mysql_query($selwarehouse,$con);
if(!$runwarehouse)die("Error");
$rowz=mysql_fetch_assoc($runwarehouse);
if($counter%2==0){
echo ("<tr class='light'>");
echo ("<th>".$row1['code']."</th>");
echo ("<th>".$row1['code2']."</th>");
echo ("<th>".$row1['description']."</th>");
echo ("<th>".$row1['discountper']."</th>");
echo ("<th>".$row1['discountamount']."</th>");
echo ("<th>".$row1['quantity']."</th>");
echo ("<th>".$row1['price']."</th>");
echo ("<th>".$row1['amount']."</th>");
echo ("<th>".$row1['totaldiscount']."</th>");
echo ("<th>".$rowz['name']."</th>");
echo ("<th><a href='edit.php?id=".$row1['Id']."'>edit</a></th>");
echo ("</tr>");
}else{
echo ("<tr class='dark'>");
echo ("<th>".$row1['code']."</th>");
echo ("<th>".$row1['code2']."</th>");
echo ("<th>".$row1['description']."</th>");
echo ("<th>".$row1['discountper']."</th>");
echo ("<th>".$row1['discountamount']."</th>");
echo ("<th>".$row1['quantity']."</th>");
echo ("<th>".$row1['price']."</th>");
echo ("<th>".$row1['amount']."</th>");
echo ("<th>".$row1['totaldiscount']."</th>");
echo ("<th>".$rowz['name']."</th>");
echo ("<th><a href='edit.php?id=".$row1['Id']."'>edit</a></th>");
echo ("</tr>");
}
}
echo "</table>";
?>
</div>
</body>
</html>
<?php
die('');
}
?>
<head>
</head>
<?php
if($warehouseid==''){
die("<h2 align='center'>Please Choose warehouse</h2>");
}
$x=(explode('-',$code));
$code1=$x[0];
$codeid=$x[1];
$code2=$x[2];
$selqty="SELECT * FROM inventory
WHERE itemid='$codeid' AND
warehouseid='$warehouseid'";
$runselqty=mysql_query($selqty,$con);
$rowinventory=mysql_fetch_assoc($runselqty);
if(!$runselqty)die("error");
if(mysql_num_rows($runselqty)==0){
die("<h1 align='center'>This Item Is Not In Your Inventory</h1>");
}
else{
if($rowinventory['qty']<0){
?>
<script type='text/javascript'>
function check(){
var r = confirm("Press a button!");
if(r) {
var urlLink = 'http://www.example.com/warehouse/record.php?codeid=<?php echo $codeid;?>&qty=<?php echo $qty;?>&custid=<?php echo $custid;?>&warehouseid=<?php echo $warehouseid;?>';
$.ajax({
type: 'GET',
url: urlLink,
success: function(data) {
if(data == 'success') {
alert('123');
}
},
error: function(data) {
console.log(data);
}
});
} else {
return false;
}
}
check();
alert('123');
</script>
<?php
// die("<h1 align='center'>The quantity of the item is negative Do you want to continue ?</h1>");
}
else if($rowinventory['qty']-$qty>=0){
// die("<h1 align='center'>The quantity is enough in the inventory You can continue</h1>");
}
else if($rowinventory['qty']-$qty<0){
// die("<h1 align='center'>The available quantity in the inventory is less than the quantity you select</h1>");
}
}
$sqlx = "SELECT * FROM items
WHERE Id='$codeid'";
$resultx=mysql_query($sqlx,$con);
if(!$resultx)die("Couldn't execute".mysql_error());
$row = mysql_fetch_assoc($resultx);
$desc=$row['description'];
$price=$row['price'];
if((!isset($qty))||($qty=='')){
$insert="INSERT INTO itemscopy(code,code2,description,quantity,price,amount,custid,uid,discountper,discountamount,totaldiscount,warehouseid,codeid)Values('$code1','$code2','$desc','1','$price','$price','$custid','$uid','0','0','$price','$warehouseid','$codeid')";
$r=mysql_query($insert,$con);
if(!$r)die("error".mysql_error());
}
else{
$insert="INSERT INTO itemscopy(code,code2,description,quantity,price,amount,custid,uid,discountper,discountamount,totaldiscount,warehouseid,codeid)Values('$code1','$code2','$desc','$qty','$price','$price'*'$qty','$custid','$uid','0','0','$price'*'$qty','$warehouseid','$codeid')";
$r=mysql_query($insert,$con);
if(!$r)die("error".mysql_error());
}
$sql1 = "SELECT * FROM itemscopy WHERE uid='$uid'";
$result1=mysql_query($sql1,$con);
if(!$result1)die("Couldn't execute".mysql_error());
?>
<table border="0" width="100%" align="center">
<thead>
<tr>
<th>Code</th>
<th>Code 2</th>
<th>Description</th>
<th>Discount%</th>
<th>Discount Amount</th>
<th>Quantity</th>
<th>Price</th>
<th>Amount</th>
<th>After Discount</th>
<th>Warehouse</th>
</tr>
</thead>
<?php
for($counter=0;$row1=mysql_fetch_assoc($result1);$counter++){
$wid=$row1['warehouseid'];
$selwarehouse="SELECT * FROM warehouse
WHERE Id='$wid'";
$runwarehouse=mysql_query($selwarehouse,$con);
if(!$runwarehouse)die("Error");
$rowz=mysql_fetch_assoc($runwarehouse);
if($counter%2==0){
echo ("<tr class='light'>");
echo ("<th>".$row1['code']."</th>");
echo ("<th>".$row1['code2']."</th>");
echo ("<th>".$row1['description']."</th>");
echo ("<th>".$row1['discountper']."</th>");
echo ("<th>".$row1['discountamount']."</th>");
echo ("<th>".$row1['quantity']."</th>");
echo ("<th>".$row1['price']."</th>");
echo ("<th>".$row1['amount']."</th>");
echo ("<th>".$row1['totaldiscount']."</th>");
echo ("<th>".$rowz['name']."</th>");
echo ("<th><a href='edit.php?id=".$row1['Id']."'>edit</a></th>");
echo ("</tr>");
}else{
echo ("<tr class='dark'>");
echo ("<th>".$row1['code']."</th>");
echo ("<th>".$row1['code2']."</th>");
echo ("<th>".$row1['description']."</th>");
echo ("<th>".$row1['discountper']."</th>");
echo ("<th>".$row1['discountamount']."</th>");
echo ("<th>".$row1['quantity']."</th>");
echo ("<th>".$row1['price']."</th>");
echo ("<th>".$row1['amount']."</th>");
echo ("<th>".$row1['totaldiscount']."</th>");
echo ("<th>".$rowz['name']."</th>");
echo ("<th><a href='edit.php?id=".$row1['Id']."'>edit</a></th>");
echo ("</tr>");
}
}
echo "</table>";
?>
</div>
</body>
</html>
Here is my php code that runs the ajax file where should i put the javascript
<?php
include("header.php");
include("mysqlconnection.php");
if(!isset($_POST['custname'])){
die("<h2 align='center'>YOU ARE NOT ALLOWED TO VISIT THIS PAGE</h2>");
}
?>
<html>
<head>
<script type="text/javascript" src="jquery1.9.1.min.js"></script>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquerysearchabledropdown.min.js"></script>
<script>
function showUser(){
var str=document.form.users.value;
var qty=document.form.qty.value;
var custid=document.form.custid.value;
var warehouseid=document.form.warehouse.value;
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
alert('123');
}
}
xmlhttp.open("GET","getcode.php?user="+str+"&qty="+qty+"&custid="+custid+"&warehouseid="+warehouseid,true);
xmlhttp.send();
document.form.users.value='';
document.form.users.focus();
}
$(document).ready(function(){
$("#users").keypress(function(event) {
if (event.which == 13) {
event.preventDefault();
document.getElementById('goo').click();
}
});
});
$(document).ready(function() {
$("#users2").searchable();
});
function appendSelectOption(str) {
$("#users2").append("<option value=\"" + str + "\">" + str + "</option>");
}
</script>
</head>
<body onload="document.form.users.focus()">
<div id="">
</br></br>
<form name="form" method="post">
<table border="0" align="center">
<tr>
<td align="center"><select id="users2" name="users" width="350" style="width: 230px">
<option value="" selected="selected">Please Select</option>
<?php
$sql1="select code,description,code2,Id from items";
$result1=mysql_query($sql1,$con);
for($counter=0;$row=mysql_fetch_row($result1);$counter++)
print ("<option value = '$row[0]-$row[3]-$row[2]'>$row[0] - $row[1] - $row[2]</option>");
?>
</select>
</td>
<td align="center"><select id="warehouse" name="warehouse" >
<option value="" selected="selected">Please Select</option>
<?php
$sql1="select Id,name from warehouse order by Id Desc";
$result1=mysql_query($sql1,$con);
for($counter=0;$row=mysql_fetch_row($result1);$counter++)
print ("<option value = '$row[0]'>$row[1]</option>");
?>
</select>
</td>
<td>
<input type="text" name="qty" id="qty" size="2"/>
</td>
<td>
<input type="button" name="goo" id="goo" value="GO" onclick="showUser()"/>
</td>
<td>
<input type="hidden" name="custid" id="custid" value="<?php echo $_POST['custname'];?>" size="3"/>
</td>
<td>
<input type="hidden" name="warehouseid" id="warehouseid" value="<?php echo $_POST['warehouse'];?>" size="3"/>
</td>
<td>
<input type="hidden" name="date" id="date" value="<?php echo $_POST['date'];?>"/>
</td>
</tr>
</table>
</form>
</div>
<div id="txtHint"></div>
<script>
$(document).ready(function(){
$('#users').attr("placeholder", "Barcode Search...");
$('#users').focusin(function(){
$(this).attr("placeholder", "");
});
$('#users').focusout(function(){
$(this).attr("placeholder", "Barcode Search...");
});
});
</script>
</body>
</html>
To run a javascript function after your ajax call you should do something like below
$.ajax({
url: "getcode.php?user="+str+"&qty="+qty+"&custid="+custid+"&warehouseid="+warehouseid,
type:"get",
success: function(responseText) {
$("#txtHint").html(responseText);
$("#txtHint").find("script").each(function(i) {
eval($(this).text());
});
}
});
put your javascript function in your success function..
So the function will fire when there is a success ajax call
EDIT
as per your coding you need to do following change in your function
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
alert('something') // put some javascript here
}
Let me know if any other help needed

Uploading files to Google Drive

I am trying to upload files from my PHP-based website to Google Drive. I searched, got google-api-php-client library. In documentation an example is given but that can be run on php shell (Command line). I tried to run that example in browser, I got error of curl extention, and fixed that.
Now I am getting error related to authenticating code to allow access. I do not need authentication at all in my project, but for the time being I can try with it.
I have the following code in www.mydomain.com/drive/index.php file:
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
$client = new Google_Client();
// Get your credentials from the APIs Console
$client->setClientId('MY-CLIENT-ID');
$client->setClientSecret('MY-CLIENT-SECRET');
$client->setRedirectUri('http://www.MY-DOMAIN.com/drive/auth.php');
//AUTH.PHP should have code to authenticate code and return back another code.
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
$service = new Google_DriveService($client);
//**********************authentication process for SHELL
//I want this authentication process to remove at all or convert to web based authentication
$authUrl = $client->createAuthUrl();
//Request authorization
print "Please visit:\n$authUrl\n\n";
print "Please enter the auth code:\n";
$authCode = trim(fgets(STDIN));
// Exchange authorization code for access token
$accessToken = $client->authenticate($authCode);
$client->setAccessToken($accessToken);
//************************************************************
//Insert a file
$file = new Google_DriveFile();
$file->setTitle('My document');
$file->setDescription('A test document');
$file->setMimeType('text/plain');
$data = file_get_contents('document.txt');
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => 'text/plain',
));
print_r($createdFile);
?>
Can I upload file without authentication need for each upload? If yes then how? If no then how to authenticate?
You can't use the exact same example that is meant for console development into web development.
You should do some changes, I'll give you mine as an example :
<?php
require_once 'googleapi/Google_Client.php';
require_once 'googleapi/contrib/Google_DriveService.php';
session_start();
$client = new Google_Client();
// Get your credentials from the APIs Console
$client->setApplicationName('Google+ PHP Starter Application');
$client->setClientId('ID');
$client->setClientSecret('Secret');
$client->setRedirectUri('Redirect');
//Voy a la dirección de la creación del permiso
$authUrl = $client->createAuthUrl();
print "<a href='$authUrl'>Connect Me!</a>";
//Regreso de la dirección con el código con el que puedo autenticarme
if (isset($_GET['code'])) {
$accessToken = $client->authenticate($_GET['code']);
file_put_contents('conf.json', $accessToken);
$client->setAccessToken($accessToken);
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
$client->setAccessToken(file_get_contents('conf.json'));
if ($client->getAccessToken()) {
//Significa que tengo derecho a manipular el servicio como quiera
// Elijo el servicio que quiero usar
$service = new Google_DriveService($client);
$file = new Google_DriveFile();
/*$file->setTitle('My document');
$file->setDescription('A test document');
$file->setMimeType('text/plain');
$data = file_get_contents('document.txt');
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => 'text/plain',
));
print_r($createdFile);
print "test";*/
}
?>
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("trainee_devang",$con);
if(isset($_POST['submit']))
{
$name=$_POST['name'];
$email=$_POST['email'];
$address=$_POST['address'];
$country=$_POST['country'];
$gender=$_POST['gender'];
$hobby = implode(',', $_POST['hobby']);
echo $ins="insert into itech (`name`,`email`,`address`,`country`,`gender`,`hobby`)values('".$name."','".$email."','".$address."','".$country."','".$gender."','".$hobby."')";
mysql_query($ins);
//header('location:view.php');
}
?>
<html>
<head></head>
<body>
<form name="add.php" method="post" onSubmit="return validate()">
<table align="center" border="1">
<tr>
<td>Name</td>
<td><input type="text" name="name" id="name"></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" id="email"></td>
</tr>
<tr>
<td>Address</td>
<td>
<textarea rows="5" cols="20" name="address" wrap="physical"</textarea>
</textarea>
</td>
</tr>
<tr>
<td>
Country:<br/></td>
<td>
<select name="country" id="country">
<option value="">Select Country</option>
<option value="India">India</option>
<option value="U.S.A">U.S.A</option>
<option value="Canada">Canada</option></select>:<br />
</td>
</tr>
<tr>
<td>Gender</td>
<td>
Male:<input type="radio" value="Male" name="gender">:<br />
Female:<input type="radio" value="Female" name="gender">:<br />
</td>
</tr>
<tr>
<td>Hobbies</td>
<td>
<input type="checkbox" name="hobby[]" value="cricket">cricket<br/>
<input type="checkbox" name="hobby[]" value="Music">Music<br/>
<input type="checkbox" name="hobby[]" value="Movie">Movie<br/>
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit" value="submit"></td>
</tr>
</table>
</form>
</body>
</html>
<script language="javascript" type="text/javascript">
function validate()
{
if(document.getElementById("name").value=="")
{
alert("Please Enter Your Name");
document.getElementById("name").focus();
return false;
}
if(document.getElementById("email").value=="")
{
alert("Please Enter Your Email Id");
document.getElementById("email").focus();
return false;
}
if(document.getElementById("address").value=="")
{
alert("Please Enter Your Address ");
document.getElementById("address").focus();
return false;
}
return true;
}
</script>
*****************************************************************************
edit.php
**************************************************
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("trainee_devang",$con);
$id=$_GET['id'];
$qry="select * from itech where id=$id";
$data=mysql_query($qry);
$result=mysql_fetch_assoc($data);
echo $result['hobby'];
//echo $id;
if(isset($_POST['update']))
{
$name=$_POST['name'];
$email=$_POST['email'];
$address=$_POST['address'];
$gender=$_POST['gender'];
$hobby = implode(',', $_POST['hobby']);
echo $upd="update itech SET name='$name',email='$email',address='$address',gender='$gender',hobby='$hobby' where id=$id";exit;
mysql_query($upd);
header('location:view.php');
}
?>
<html>
<head></head>
<body>
<form name="edit.php" method="post">
<table align="center" border="1">
<tr>
<td>Name</td>
<td><input type="text" name="name" id="name" value="<?php echo $result['name'];?>"></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" id="email" value="<?php echo $result['name'];?>"></td>
</tr>
<tr>
<td>Address</td>
<td>
<textarea rows="5" cols="20" name="address" id="address" >
<?php echo $result['address'];?>
</textarea>
</td>
</tr>
<tr>
<td>
Country:<br/></td>
<td>
<select name="country">
<option value="">Select Country</option>
<option value="<?php echo $result["id"]; ?>"
<?//php if($result["id"]==$_REQUEST["cat_id"]) { echo "Selected"; } ?>>
<?//php echo $r["category_name"]; ?></option>
<option value="India" <?php if($result['country']=='India') { echo "Selected"; }?>>India</option>
<option value="U.S.A" <?php if($result['country']=='U.S.A') { echo "Selected"; }?>>U.S.A</option>
<option value="Canada"<?php if($result['country']=='Canada') { echo "Selected"; }?>>Canada</option></select>:<br />
</td>
</tr>
<tr>
<td>Gender</td>
<td>
<?php
if($result['gender']=='Male')
{ ?>
Male:<input type="radio" value="Male" name="gender" CHECKED><br />
Female:<input type="radio" value="Female" name="gender"><br />
<?php }elseif ($result['gender'] == 'Female') {?>
Male:<input type="radio" value="Male" name="gender" ><br />
Female:<input type="radio" value="Female" name="gender" CHECKED><br />
<?php }?>
</td>
</tr>
<tr>
<td>Hobbies</td>
<td>
<input type="checkbox" name="hobby[]" value="cricket" <?php if($result['hobby']=='cricket') { echo "checked=checked"; }?>>cricket<br/>
<input type="checkbox" name="hobby[]" value="Music" <?php if($result['hobby']=='Music') {echo "checked=checked";}?>>Music<br/>
<input type="checkbox" name="hobby[]" value="Movie" <?php if($result['hobby']=='Movie') { echo "checked=checked";}?>>Movie<br/>
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="update" value="update"></td>
</tr>
</table>
</form>
</body>
</html>
<script type="text/javascript">
function validation()
{
if(document.getElementById(name).value="");
{
alert("Plz Enter Your Name");
document.getElementById(name).focus();
return false;
}
if(document.getElementById(email).value="");
{
alert("Plz enter Emailid");
document.getElementById(emailid).focus();
return false;
}
if(document.getElementById(address).value="");
{
alert("Plz Enter Your Address");
document.getElementById(address).focus();
return false;
}
if(document.getElementById(gender).value="");
{
alert("Plz Select your gender");
document.getElementById(gender).focus();
return false;
}
if(document.getElementById(hobby).value="");
{
alert("Plz Select your Hobby");
document.getElementById(hobby).focus();
return false;
}
return true;
}
</script>
**********************************************
view.php
******************************************
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("trainee_devang",$con);
?>
<html>
<head></head>
<body>
<table align="center" border="1">
<tr>
<th>Name</th>
<th>EmailId</th>
<th>Address</th>
<th>Country</th>
<th>Gender</th>
<th>Hobby</th>
<th>Action</th>
</tr>
<?php
$sel="select * from itech";
$data=mysql_query($sel);
while($result=mysql_fetch_assoc($data))
{?>
<tr>
<td><?php echo $result['name'];?></td>
<td><?php echo $result['email'];?></td>
<td><?php echo $result['address'];?></td>
<td><?php echo $result['country'];?></td>
<td><?php echo $result['gender'];?></td>
<td><?php echo $result['hobby'];?></td>
<td>Edit
Delete
</td>
</tr>
<?php
}?>
</table>
</body>
</html>
**********************************************
pagination.php
******************************************
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>View Records</title>
</head>
<body>
<?php
/*
VIEW-PAGINATED.PHP
Displays all data from 'players' table
This is a modified version of view.php that includes pagination
*/
// connect to the database
include('connect-db.php');
// number of results to show per page
$per_page = 3;
// figure out the total pages in the database
$result = mysql_query("SELECT * FROM players");
$total_results = mysql_num_rows($result);
$total_pages = ceil($total_results / $per_page);
// check if the 'page' variable is set in the URL (ex: view-paginated.php?page=1)
if (isset($_GET['page']) && is_numeric($_GET['page']))
{
$show_page = $_GET['page'];
// make sure the $show_page value is valid
if ($show_page > 0 && $show_page <= $total_pages)
{
$start = ($show_page -1) * $per_page;
$end = $start + $per_page;
}
else
{
// error - show first set of results
$start = 0;
$end = $per_page;
}
}
else
{
// if page isn't set, show first set of results
$start = 0;
$end = $per_page;
}
// display pagination
echo "<p><a href='view.php'>View All</a> | <b>View Page:</b> ";
for ($i = 1; $i <= $total_pages; $i++)
{
echo "<a href='view-paginated.php?page=$i'>$i</a> ";
}
echo "</p>";
// display data in table
echo "<table border='1' cellpadding='10'>";
echo "<tr> <th>ID</th> <th>First Name</th> <th>Last Name</th> <th></th> <th></th></tr>";
// loop through results of database query, displaying them in the table
for ($i = $start; $i < $end; $i++)
{
// make sure that PHP doesn't try to show results that don't exist
if ($i == $total_results) { break; }
// echo out the contents of each row into a table
echo "<tr>";
echo '<td>' . mysql_result($result, $i, 'id') . '</td>';
echo '<td>' . mysql_result($result, $i, 'firstname') . '</td>';
echo '<td>' . mysql_result($result, $i, 'lastname') . '</td>';
echo '<td>Edit</td>';
echo '<td>Delete</td>';
echo "</tr>";
}
// close table>
echo "</table>";
// pagination
?>
<p>Add a new record</p>
</body>
</html>
login.php
***************************************
<?php
session_start();
$con=mysql_connect("localhost","root","");
mysql_select_db("trainee_devang",$con);
if(isset($_POST['submit']))
{
$email=$_REQUEST['email'];
$pass=$_REQUEST['password'];
$sel="select * from elite where email='$email' and password='$pass'";
$res= mysql_query($sel);
$co= mysql_num_rows($res);
echo $co;
header("location:view.php");
if($co>0)
{
$row=mysql_fetch_array($res);
$_SESSION['email']=$row['email'];
header("location:view.php");
}
else
{
echo "Please enter correct username or password....";
header("location:login.php");
}
}
?>
<html>
<head>
</head>
<body>
<fieldset style="background-color: lightblue;height: 400px;width: 500px;margin-left: 400px;margin-top: 120px;">
<form action="" method="post">
<h1 align="center" style="color: red;">Login Page</h1>
<table align="center" border="1">
<tr>
<td><b>Email</b></td>
<td><input type="text" name="email"></td>
</tr>
<tr>
<td><b>PassWord</b></td>
<td><input type="password" name="password"></td>
</tr>
</table><br /><br />
<b><input type="submit" name="submit" value="submit" style="margin-left: 220px;color: red;"></b>
</form>
</fieldset>
</body>
</html>
*********************************************************
logout.php
**********************************************************
<?php
session_start();
session_destroy();
header("Location: login.php");
exit;
?>
******************************
add.php
**********************************
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("trainee_devang",$con);
if(isset($_POST['submit']))
{
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$email=$_POST['email'];
$password=$_POST['password'];
move_uploaded_file($_FILES['image']['tmp_name'] ,"upload/".$_FILES['image']['name']);
$img = $_FILES['image']['name'];
$dob=$_POST['dob'];
$address=$_POST['address'];
echo $ins="insert into elite (`firstname`,`lastname`,`email`,`password`,`image`,`dob`,`address`)
values('".$firstname."','".$lastname."','".$email."','".$password."','".$img."','".$dob."','".$address."')";
mysql_query($ins);
header('location:view.php');
}
?>
<html>
<head>
</head>
<body>
<table align="center" border="1">
<form name="add.php" method="post" enctype="multipart/form-data" onsubmit="return validation()">
<tr>
<td>FirstName</td>
<td><input type="text" id="firstname" name="firstname"></td>
</tr>
<tr>
<td>LastName</td>
<td><input type="text" id="lastname" name="lastname"></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" id="email" name="email"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" id="password" name="password"></td>
</tr>
<tr>
<td>Image</td>
<td><input type="file" id="image" name="image"> </td>
</tr>
<tr>
<td>Dob</td>
<td> <input type="text" name='dob' id="datepicker" /></td>
</tr>
<tr>
<td>Address</td>
<td><input type="text" id="address" name="address"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit" id="submit"></td>
</tr>
</form>
</table>
</body>
</html>
<script type="text/javascript">
function validation()
{
if(document.getElementById("firstname").value=="")
{
alert("Please Enter FirstName");
document.getElementById("firstname").focus();
return false;
}
if(document.getElementById("lastname").value=="")
{
alert("Please Enter lastname");
document.getElementById("lastname").focus();
return false;
}
var email = document.getElementById('email');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value))
{
alert('Please provide a valid email address');
email.focus;
return false;
}
if(document.getElementById("password").value=="")
{
alert("Please Enter password");
document.getElementById("password").focus();
return false;
}
if(document.getElementById("image").value=="")
{
alert("Please upload image");
document.getElementById("image").focus();
return false;
}
if(document.getElementById("dob").value=="")
{
alert("Please enter date");
document.getElementById("dob").focus();
return false;
}
if(document.getElementById("address").value=="")
{
alert("Please Enter address");
document.getElementById("address").focus();
return false;
}
return true;
}
</script>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Datepicker - Default functionality</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
$( "#datepicker" ).datepicker();
});
</script>
</head>
<body>
</body>
</html>
***************************************
view.php
************************************
<?php
session_start();
$con=mysql_connect("localhost","root","");
mysql_select_db("trainee_devang",$con);
echo $_SESSION['email'];
if(!isset($_SESSION['email']))
{
header("location:login.php");
}
?>
<html>
<head></head>
<body></body>
<table align="center" border="1">
<tr>
<th>FirstName</th>
<th>LastName</th>
<th>Email</th>
<th>Password</th>
<th>Image</th>
<th>D.O.B</th>
<th>Address</th>
<th>Action</th>
</tr>
<?php
$vs="select * from elite";
$data=mysql_query($vs);
while($result=mysql_fetch_assoc($data))
{?>
<tr>
<td><?php echo $result['firstname'];?></td>
<td><?php echo $result['lastname'];?></td>
<td><?php echo $result['email'];?></td>
<td><?php echo $result['password'];?></td>
<td><img src="<?php echo "upload/".$result['image']; ?>" alt="" width="50px" height="50px"></td>
<td><?php echo $result['dob'];?></td>
<td><?php echo $result['address'];?></td>
<td><a href="edit.php? id=<?php echo $result['id'];?>">Edit</td>
<td><a href="delete.php? id=<?php echo $result['id'];?>">Delete</td>
<td><a href="logout.php?">Logout</td>
</tr>
<?php
}
?>
</table>
</html>
********************************************************
edit.php
*********************************************************
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("trainee_devang",$con);
$id=$_GET['id'];
echo $sel="select * from elite where id=$id";
$data=mysql_query($sel);
$res=mysql_fetch_assoc($data);
if(isset($_POST['update']))
{
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$email=$_POST['email'];
$password=$_POST['password'];
move_uploaded_file($_FILES['image']['tmp_name'] ,"upload/".$_FILES['image']['name']);
$img = $_FILES['image']['name'];
$dob=$_POST['dob'];
$address=$_POST['address'];
$upd="update elite SET firstname='$firstname',lastname='$lastname',email='$email',password='$password',image='$img',dob='$dob',address='$address' where id=$id";
mysql_query($upd);
header('location:view.php');
}
?>
<html>
<head>
</head>
<body>
<table align="center" border="1">
<form name="edit.php" method="post" enctype="multipart/form-data" onsubmit="return validation()">
<tr>
<td>FirstName</td>
<td><input type="text" id="firstname" name="firstname" value="<?php echo $res['firstname'];?>"></td>
</tr>
<tr>
<td>LastName</td>
<td><input type="text" id="lastname" name="lastname"value="<?php echo $res['lastname'];?>"></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" id="email" name="email"value="<?php echo $res['email'];?>"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" id="password" name="password"value="<?php echo $res['password'];?>"></td>
</tr>
<tr>
<td>Image</td>
<td><input type="file" id="image" name="image"value="<?php echo $res['image'];?>"> </td>
</tr>
<tr>
<td>Dob</td>
<td><input type="text" id="datepicker" name="dob"value="<?php echo $res['dob'];?>"></td>
</tr>
<tr>
<td>Address</td>
<td><input type="text" id="address" name="address"value="<?php echo $res['address'];?>"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="update" value="update"></td>
</tr>
</form>
</table>
</body>
</html>
<script type="text/javascript">
function validation()
{
if(document.getElementById("firstname").value=="")
{
alert("Please Enter FirstName");
document.getElementById("firstname").focus();
return false;
}
if(document.getElementById("lastname").value=="")
{
alert("Please Enter lastname");
document.getElementById("lastname").focus();
return false;
}
if(document.getElementById("email").value=="")
{
alert("Please Enter emailid");
document.getElementById("email").focus();
return false;
}
if(document.getElementById("password").value=="")
{
alert("Please Enter password");
document.getElementById("password").focus();
return false;
}
if(document.getElementById("image").value=="")
{
alert("Please upload image");
document.getElementById("image").focus();
return false;
}
if(document.getElementById("dob").value=="")
{
alert("Please enter date");
document.getElementById("dob").focus();
return false;
}
if(document.getElementById("address").value=="")
{
alert("Please Enter address");
document.getElementById("address").focus();
return false;
}
return true;
}
</script>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Datepicker - Default functionality</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
$( "#datepicker" ).datepicker();
});
</script>
</head>
<body>
****************************************************
delete.php
*************************************************
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("trainee_devang",$con);
$id=$_GET['id'];
$del="delete from elite where id=$id";
mysql_query($del);
header('location:view.php');
?>

Get javascript active when posting php ajax result through javascript

I have this html form:
<form method="post">
<input type="radio" name="news" id="new" value="nuova" onchange="newstype(this.id);">Nuova News
<input type="radio" name="news" id="mod" value="modifica" onchange="newstype(this.id);">Modifica News
<select name="news" id="modifica" style="display:none" onchange="shownews(this.value)">
<?php
include "../flock/sql.php";
$connection = new mysqli($host, $user, $pw, $db) or die("Impossibile connettersi");
$querylistanews = "SELECT * FROM NEWS ORDER BY id DESC";
$listanews = $connection->query($querylistanews);
print '<option>Seleziona una news...</option>';
while ($newsdamodificare = $listanews->fetch_object()) {
print '<option value="'.$newsdamodificare->id.'">'.$newsdamodificare->data." - ".$newsdamodificare->title.'</option>';
}
$listanews->close();
$connection->close;
?>
</select>
</form>
this javascript:
function newstype(param) {
if(param == 'new') {
document.getElementById('crea').style.display = 'inline';
document.getElementById('modifica').style.display = 'none';
document.getElementById('newsdamodificare').style.display = 'none';
} else {
if(param == 'mod') {
document.getElementById('crea').style.display = 'none';
document.getElementById('modifica').style.display = 'inline';
document.getElementById('newsdamodificare').style.display = 'inline';
}
}
}
function shownews(str) {
if (str=="") {
document.getElementById("newsdamodificare").innerHTML="";
return;
}
if (window.XMLHttpRequest) { // codice per IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // codice per IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("newsdamodificare").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","modifica.php?news="+str,true);
xmlhttp.send();
}
and this php:
<head>
<script type="text/javascript" src="../editor/ckeditor.js"></script>
<script type="text/javascript" src="/js/charscounter.js"></script>
</head>
<?php
$news=$_GET["news"];
include "../flock/sql.php";
$connection = new mysqli($host, $user, $pw, $db) or
die('Impossibile connettersi al database: ' . mysql_error());
$newsdaldatabase="SELECT * FROM NEWS WHERE id = '".$news."'";
$result = $connection->query($newsdaldatabase);
$count = mysqli_num_rows($result);
if($count==1){
while($dati = mysqli_fetch_array($result)) {
$id = $dati['id'];
$data = $dati['data'];
$title = $dati['title'];
$body = $dati['body'];
}
} else {
die('Errore del sistema. Più di una news selezionate: ' . mysql_error());
}
mysqli_close($connection);
?>
<div class="normal" id="modifica">
<table style="width:100%;height:100%;">
<tr>
<td colspan="3" border="0">
<strong class="confirm">Modifica news</strong>
</td>
</tr>
<tr>
<td width="107" align="right">
<strong>Data</strong>
</td>
<td colspan="2">
<form name="modificanews" method="post" action="italiano.php?modifica=yes">
<input name="idmodificanews" type="text" style="display:none" value="<?php echo $id ?>">
<input name="datanewsmodificata" type="text" maxlength="10" size="8" value="<?php echo $data ?>"> gg.mm.aaaa
</td>
</tr>
<tr>
<td align="right">
<strong>Titolo</strong>
</td>
<td width="360">
<input name="modificatitolo" type="text" maxlength="50" size="50" value="<?php echo $title ?>" onKeyPress="return taLimit(this)" onKeyUp="return taCount(this,'myCounter')">
</td>
<td width="522">
<b><span id=myCounter>50</span></b> caratteri rimanenti per il titolo</font>
</td>
</tr>
<tr>
<td colspan="3">
<textarea name="modificatesto"><?php echo $body ?></textarea>
<script>
CKEDITOR.replace('modificatesto');
</script>
</td>
</tr>
All is working quite well, except one thing:
when I select the news to edit, the content is from the server is correcly posted on the php, but on the HTML the scripts in the php (CKEDITOR and Char Cunter) are not active.
So, on my HTML, were the user will edit the news, i get only a simple textarea instead of the CKEDITOR, etc.
Is there a way to fix that? Can you help me somehow?
Thank you!
EDIT: I solved by myselft the problem. See solution as answer.
For those who have the same question:
I solved my problem in the following way: on javascript add a new row:
document.getElementById("newsdamodificare").action=CKEDITOR.replace('modificatesto');
between this 2 lines:
document.getElementById("newsdamodificare").innerHTML=xmlhttp.responseText;
NEW LINE TO INSERT HERE
}
And remove from the php these rows:
<script>
CKEDITOR.replace('modificatesto');
</script>
Hope this helps!
You're trying to select your textarea by it's name, but CKEDITOR.replace('modificatesto'); is looking for an ID.
Try
<textarea id="modificatesto"><?php echo $body ?></textarea>
<script>
CKEDITOR.replace('modificatesto');
</script>

Getting values depending on the dropdown

I have a dropdown list for items. What I want to do is get the item quantity, remaining quantity and dispatched item values which depends on the value in the drop down.
I have this code :
<form method="post" action="restore_stocks.php">
<table>
<tr>
<td>Item Name:</td>
<td><select name="itemname">
<?php
$item="SELECT item_name FROM stocks";
$itemresult = #mysql_query($item)or die ("Error in query: $query. " . mysql_error());
while($row=#mysql_fetch_array($itemresult)){
echo "<OPTION VALUE=".$row['item_name'].">".$row['item_name']."</option>";
}
?>
</select></td></tr>
<tr>
<td>Item Quantity:</td>
<td><?php
$row = mysql_fetch_object($itemresult);
echo $row->item_quantity; ?></td></tr>
<tr>
<td>Remaining Quantity:</td>
<td><?php echo $row->rem_quantity; ?></td></tr>
<tr>
<td>Stocks Dispatched:</td>
<td><?php echo $row->stocks_dispatched; ?></td></tr>
<tr>
<td>Add Stocks:</td>
<td><input name="addstocks" type="text" size="25" maxlength="25" /></td></tr>
<tr>
<td> </td>
<td><input type="submit" name="Submit" id="Submit" value="Restore" /></td>
</tr>
</table>
</form>
I really don't know how to start the code because i'm new to this approach. If you can help me it's much appreciated. Thanks in advance.
This works: The jist is that the page uses ajax to call a script, which will deliver XML of the values you need, and will then populate those fields accordingly. :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<script>
function updateFields(itemname){
var xmlhttp;
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)
{
var xmlDoc=xmlhttp.responseXML;
var iQdata=xmlDoc.documentElement.getElementsByTagName("ITEMQUANTITY");
var rQdata=xmlDoc.documentElement.getElementsByTagName("REMAININGQUANTITY");
var sDdata=xmlDoc.documentElement.getElementsByTagName("STOCKSDISPATCHED");
var iQ=iQdata[0].firstChild.nodeValue;
var rQ=rQdata[0].firstChild.nodeValue;
var sD=sDdata[0].firstChild.nodeValue;
document.getElementById("itemQuantity").innerHTML=iQ;
document.getElementById("remainingQuantity").innerHTML=rQ;
document.getElementById("stocksDispatched").innerHTML=sD;
}
}
xmlhttp.open("GET","quantity_script.php?itemname="+itemname,true);
xmlhttp.send();
}
</script>
<form method="post" action="restore_stocks.php">
<table>
<tr>
<td>Item Name:</td>
<td><select name="itemname" onchange="updateFields(this.value)">
<?php
$item="SELECT item_name FROM stocks";
$itemresult = #mysql_query($item)or die ("Error in query: $query. " .mysql_error());
while($row=#mysql_fetch_array($itemresult)){
echo "<OPTION VALUE=".$row['item_name'].">".$row['item_name']."</option>";
}
?>
</select></td></tr>
<tr>
<td>Item Quantity:</td>
<td><div id="itemQuantity"></div></td></tr>
<tr>
<td>Remaining Quantity:</td>
<td><div id="remainingQuantity"></div></td></tr>
<tr>
<td>Stocks Dispatched:</td>
<td><div id="stocksDispatched"></div></td></tr>
<tr>
<td>Add Stocks:</td>
<td><input name="addstocks" type="text" size="25" maxlength="25" /></td></tr>
<tr>
<td> </td>
<td><input type="submit" name="Submit" id="Submit" value="Restore" /></td>
</tr>
</table>
</form>
</body>
</html>
And then you'd also make a script on your site "quantity_script.php" that would be something like the following:
<?php
//include your DB connection info
$itemname=mysql_real_escape_string($_POST["itemname"]);
$item="SELECT ".$itemname." FROM stocks";
$itemresult = mysql_query($item);
$row=mysql_fetch_assoc($itemresult);
header('Content-type: text/xml');
echo "<ROOT>";
echo "<ITEMQUANTITY>".$row["item_quantity"]."</ITEMQUANTITY>";
echo "<REMAININGQUANTITY>".$row["rem_quantity"]."</REMAININGQUANTITY>";
echo "<STOCKSDISPATCHED>".$row["stocks_dispatched"]."</STOCKSDISPATCHED>";
echo "</ROOT>";
?>

Categories