Pass PHP variable from HTML form to Javascript - javascript

could you help me pass a variable that was taken from a html form into javascript.
The form asks for the tablename
<br>
New tablename:<br>
<input type="text" name="table">
It is passed through PHP:
if (isset($_POST['submit'])) {
$user = $_POST['user'];
$password = $_POST['password'];
$table = $_POST['table'];
$geometry = $_POST['geom'];
}
A first action is underway, and created successfully: the Geoserver postgis table is created through PHP curl (entire code below)
then the javascript tries to get $table with a PHP insert; this will help it load the newly created postgis Geoserver table from the PHP, into the WFST javascript ;
<?php
echo "var thedata = " .$table. ";\n";
?>
...
var wfstPoly = new L.WFST({
url: 'https://mappingforyou.eu/geoserver/ows',
typeNS: 'opendata',
typeName: thedata,
But this code doesn't work:
<?php
echo "var thedata = " .$table. ";\n";
?>
--
The code works fine except for the thedata javascript variable.
The entire form:
<!DOCTYPE html>
<html>
<body>
<h2>PG GS input test</h2>
<form method="POST" action="test1.php">
User:<br>
<input type="text" name="user">
<br>
Password:<br>
<input type="password" name="password">
<br>
New tablename:<br>
<input type="text" name="table">
<input type="radio" name="geom" id="Point" value="Point" />
<label for="Point">Point</label>
<input type="radio" name="geom" id="MultiLineString" value="MultiLineString" />
<label for="MultiLine">Line</label>
<input type="radio" name="geom" id="MultiPolygon" value="MultiPolygon" />
<label for="MultiPolygon">Area</label>
<br><br>
<input type="submit" name="submit">
</form>
</body>
</html>
Into this javascript test1.php page:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.2.0/leaflet.css"/>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css"/>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet.toolbar.js/0.3.0/leaflet.toolbar.css" />
<style>
html, body, #map {
margin: 0;
height: 100%;
width: 100%;
}
</style>
<title>Leaflet-WFST polygon demo</title>
</head>
<body>
<div id="map"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.2.0/leaflet.js"></script>
<link rel="stylesheet" href="https://mappingforyou.eu/javascript/leaflet.draw.css" />
<script src="https://mappingforyou.eu/javascript/leaflet.draw-src.js"></script>
<link type="text/css" rel="stylesheet" href="https://mappingforyou.eu/javascript/leaflet-easybutton.css" />
<script type="text/javascript" src="https://mappingforyou.eu/javascript/leaflet-easybutton.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.4.4/proj4.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/proj4leaflet/1.0.2/proj4leaflet.js"></script>
<script src="https://mappingforyou.eu/javascript/leaflet-wfst.src.js"></script>
<script>
function jsFunction(){
<?php
echo "var thedata = " .$table. ";\n";
?>
var map = L.map('map', {editable: true}).setView([48.5, 2], 10);
// add an OpenStreetMap tile layer
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
var wfstPoly = new L.WFST({
url: 'http://localhost:8080/geoserver/ows',
typeNS: 'workspace',
typeName: thedata,
crs: L.CRS.EPSG4326,
geometryField: 'geom',
style: {
color: 'blue',
weight: 2
}
}).addTo(map)
.once('load', function () {
map.fitBounds(wfstPoly);
});
////// draw and edit
var drawControl = new L.Control.Draw({
draw:{circle:false, circlemarker:false, rectangle:false,
},
edit:{featureGroup: wfstPoly } });
map.addControl(drawControl);
map.on('draw:created', function (e) {
var layer = e.layer;
wfstPoly.addLayer(layer)});
map.on('draw:edited', function (e) {
var layers = e.layers;
layers.eachLayer( function (layer) {
wfstPoly.editLayer(layer);
})
});
// Save button
L.easyButton('fa-save', function () {
wfstPoly.save();
}, 'Save changes').addTo(map);
}
</script>
<?php
// Open log file
$logfh = fopen("GeoserverPHP.log", 'w') or die("can't open log file");
// Initiate cURL session
$service = "http://localhost:8080/geoserver/rest"; // replace with your URL
$ws = "workspace";
$ds = "database";
$request = "/workspaces/" . $ws . "/datastores/" . $ds . "/featuretypes";
$url = $service . $request;
$ch = curl_init($url);
if (isset($_POST['submit'])) {
$user = $_POST['user'];
$password = $_POST['password'];
$table = $_POST['table'];
$geometry = $_POST['geom'];
}
define("GEOSERVER_REST_HOST", "http://localhost:8080/geoserver/rest");
define("GEOSERVER_USER", "admin:password");
// Optional settings for debugging
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //option to return string
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_STDERR, $logfh); // logs curl messages
//Required POST request settings
curl_setopt($ch, CURLOPT_POST, True);
//$passwordStr = "admin:geoserver"; // replace with your username:password
curl_setopt($ch, CURLOPT_USERPWD, GEOSERVER_USER);
//POST data
curl_setopt($ch, CURLOPT_HTTPHEADER,
array("Content-type: text/xml"));
$xmlStr = "<featureType>";
$xmlStr .= "<name>".$table."</name>";
$xmlStr .= "<nativeName>".$table."</nativeName>";
$xmlStr .= "<title>".$table."</title>";
$xmlStr .= "<srs>EPSG:4326</srs>";
$xmlStr .= "<attributes>";
$xmlStr .= "<attribute>";
$xmlStr .= "<name>geom</name>";
$xmlStr .= "<binding>com.vividsolutions.jts.geom.".$geometry."</binding>";
$xmlStr .= "</attribute>";
$xmlStr .= "<attribute>";
$xmlStr .= "<name>description</name>";
$xmlStr .= "<binding>java.lang.String</binding>";
$xmlStr .= "</attribute>";
$xmlStr .= "<attribute>";
$xmlStr .= "<name>timestamp</name>";
$xmlStr .= "<binding>java.util.Date</binding>";
$xmlStr .= "</attribute>";
$xmlStr .= "</attributes>";
$xmlStr .= "</featureType>";
curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlStr);
//POST return code
$successCode = 201;
$buffer = curl_exec($ch); // Execute the curl request
// Check for errors and process results
$info = curl_getinfo($ch);
if ($info['http_code'] != $successCode) {
$msgStr = "# Unsuccessful cURL request to ";
$msgStr .= $url." [". $info['http_code']. "]\n";
fwrite($logfh, $msgStr);
} else {
$msgStr = "# Successful cURL request to ".$url."\n";
fwrite($logfh, $msgStr);
}
fwrite($logfh, $buffer."\n");
curl_close($ch); // free resources if curl handle will not be reused
fclose($logfh); // close logfile
echo '<script type="text/javascript">jsFunction();</script>';
return $success;
?>
</body>
</html>

In the code you provided, this:
if (isset($_POST['submit'])) {
$user = $_POST['user'];
$password = $_POST['password'];
$table = $_POST['table'];
$geometry = $_POST['geom'];
}
...comes after this:
echo "var thedata = " .$table. ";\n";
The initial assignment of PHP variable $table needs to come before it is used.
And if the table name, provided by the form text input, is a string, $table needs to be quoted for when it gets assigned to the Javascript variable thedata:
For example:
function jsFunction(){
<?php
if (isset($_POST['submit'])) {
$user = $_POST['user'];
$password = $_POST['password'];
$table = $_POST['table'];
$geometry = $_POST['geom'];
}
// ...
echo "var thedata = \"" .$table. "\";\n";
?>
<!-- ... -->
Keep in mind, PHP executes on the server, and the resulting text, containing HTML, Javascript, CSS, is sent to the browser through HTTP. The browser never gets PHP code. The browser only gets HTML, Javascript, and CSS. Once the browser gets these from the server it evaluates the Javascript and renders the HTML and CSS.
This, on the server:
function jsFunction(){
<?php
if (isset($_POST['submit'])) {
$user = $_POST['user'];
$password = $_POST['password'];
$table = $_POST['table'];
$geometry = $_POST['geom'];
}
// ...
echo "var thedata = \"" .$table. "\";\n";
?>
<!-- ... -->
...is executed resulting in this:
function jsFunction(){
var thedata = "user provided table name";
<!-- ... -->
...which is then sent as text to the browser.
I elaborate further on the distinct PHP and Javascript execution contexts here: https://stackoverflow.com/a/72023066/2743458

Try below
var thedata = <?php echo $table; ?>+"\n";

Related

Validating Bulk phone Number with Numverify web API in PHP

This is what I have done so far base on what I saw on their documentation page
The phone list is paste separated by comma(,) in a line break inside the textarea
e.g
2144667308,
6823259843,
2173196699,
6163091855,
6163093109
with the below code it only saved all the above listed number inside Invalid_Phones_numbers.txt, please any help will be more appreciated
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<center>
<form action="test2.php" method="post">
<textarea name="input" rows="8" cols="20" required></textarea>
<button class="btn btn-primary" type="submit" name="submit"> Submit </button>
</form>
</center>
</body>
</html>
<?php
if (isset($_POST['submit'])) {
//$leads_gatewayapi=array($_POST['leads_gatewayapi']);
$input = array($_POST['input']);
foreach ($input as $msisdn) {
$json['input'][] = ['msisdn' => $msisdn];
//$msg_gatewayapi=$_POST['msg_gatewayapi'];
$api_multiple = "c375c6c106b14d830b7*********";
$country_code_m = "US";
echo $msisdn; // this is to know maybe array value passes( 2144667308, 6823259843, 2173196699, 6163091855, 6163093109 as the output)
$ch = curl_init('http://apilayer.net/api/validate?access_key=' . $api_multiple . '&number=' . $msisdn . '&country_code=' . $country_code_m);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Store the data:
$json = curl_exec($ch);
curl_close($ch);
// Decode JSON response:
$validationResult = json_decode($json, true);
//$obj = json_decode($resu);
if (empty($validationResult['carrier'])) {
$myfile = fopen("Phone_Check_Result/Invalid_Phones_numbers.txt", "w");
$txt = $msisdn . "\n";
fwrite($myfile, $txt);
fclose($myfile);
} elseif (!empty($validationResult['carrier']) && ($validationResult['line_type'] == "mobile")) {
$myfile = fopen("Phone_Check_Result/Valid_Mobile_numbers.txt", "w");
$txt = $msisdn . "\n";
fwrite($myfile, $txt);
fclose($myfile);
} elseif (!empty($validationResult['carrier']) && ($validationResult['line_type'] == "landline")) {
$myfile = fopen("Phone_Check_Result/Valid_Landline_numbers.txt", "w");
$txt = $msisdn . "\n";
fwrite($myfile, $txt);
fclose($myfile);
}
}
if ($validationResult) {
echo "Its Working!!!";
}
$validationResult['valid'];
$validationResult['number'];
$validationResult['local_format'];
$validationResult['international_format'];
$validationResult['country_prefix'];
$validationResult['country_code'];
$validationResult['country_name'];
$validationResult['location'];
$validationResult['carrier'];
$validationResult['line_type'];
}
?>
#Sami, The api code you see is for illustrations purposes, not a working one...

Get statement not adding to database

i'm trying to use a get statement in a variable to add data to a data base, when i try to do this nothing is added under folder however if i add plain text it is added. (i'm trying to add to the folder section)
My entire html document is provided below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="newfile.css">
<title>Folder</title>
</head>
<body>
<?php
include_once 'dbh.php';
echo $_GET["data"];
if(isset($_GET["data"])) {
$location = $_GET["data"];
$sql = "SELECT * FROM posts WHERE folder LIKE '%$location%'";
$result = mysqli_query($conn, $sql);
$queryResult = mysqli_num_rows($result);
if($queryResult > 0) {
while ($row = mysqli_fetch_assoc($result))
{
echo $row['content'];
}
} else {
echo "There are no results matching your search!";
}
}
?>
<?php
$uploadpath = 'postimages/'; // directory to store the uploaded files
$max_size = 3116718; // maximum file size, in KiloBytes
$alwidth = 100000; // maximum allowed width, in pixeli
$alheight = 100000; // maximum allowed height, in pixeli
$allowtype = array('bmp', 'gif', 'jpeg', 'jpg', 'jpe', 'png', 'docx', 'psd', 'pdf', 'pptx', 'html', 'php', 'css', 'js', 'mp4', 'mp3'); // allowed extensions
if(isset($_FILES['fileup'])) {
$uploadpath = $uploadpath . basename( $_FILES['fileup']['name']);
$name = basename( $_FILES['fileup']['name']);
$type = end(explode('.', strtolower($_FILES['fileup']['name'])));
list($width, $height) = getimagesize($_FILES['fileup']['tmp_name']); // gets image width and height
$err = '';
// Checks if the file has allowed type, size, width and height (for images)
if(!in_array($type, $allowtype)) $err .= 'The file <b>'. $_FILES['fileup']['name']. '</b> not has the allowed extension type.';
if($_FILES['fileup']['size'] > $max_size*900000) $err .= '<br/>Maximum file size must be: '. $max_size. ' KB';
if(isset($width) && isset($height) && ($width >= $alwidth || $height >= $alheight)) $err .= '<br/>The maximum Width x Height must be: '. $alwidth. ' x
'. $alheight;
// If no errors, upload the image, else, output the errors
if($err == '') {
if(move_uploaded_file($_FILES['fileup']['tmp_name'], $uploadpath)) {
$content = $name;
$realfiledest = $uploadpath;
$username = 'user';
$folder = $_GET['data'];
$sql = "INSERT INTO posts (content, img, folder, date) VALUES ('$content', '$realfiledest', '$folder', NOW());";
$result = mysqli_query($conn, $sql);
if($result !== false) {
header("Location: fold.php?data=Math");
}else{
echo "fail";
}
}
else echo '<b>Unable to upload the file.</b>';
}
else echo $err;
}
?>
<div class="upform">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" enctype="multipart/form-data">
<div class="image-upload">
<label for="file-input">
<img src="add-file.png" />
</label>
<input id="file-input" type="file" name="fileup"/>
</div>
<input class="noshow" type="text" id="wow" placeholder="<?php echo $_GET['data']; ?>" name='name'>
<input type="submit" id="submit" name='submit' value="U P L O A D" />
</form>
</div>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(
function(){
$('input:file').change(
function(){
if ($(this).val()) {
$("#submit").show();
// or, as has been pointed out elsewhere:
// $('input:submit').removeAttr('disabled');
}
}
)
});
</script>
</body>
</html>
url= http://localhost/smart%20assist/fold.php?data=Math
Any help would be awesome, Thanks
So, if you doing file uploading you are using post method in your form with multi-part, right.
now, if you want to send something with your url as query params, then you have to use $_REQUEST. In your case,
if(move_uploaded_file($_FILES['fileup']['tmp_name'], $uploadpath)) {
$content = $name;
$realfiledest = $uploadpath;
$username = 'user';
$folder = $_REQUEST['data'];
$sql = "INSERT INTO posts (content, img, folder, date) VALUES ('$content', '$realfiledest', '$folder', NOW());";
$result = mysqli_query($conn, $sql);
If you facing the same problem, I need to check your HTML form, to help you in a better way.
I think you made below mistakes.
You are not posting "data" field value in your HTML.
You must put the name field for get data.
You are posting the form for using post method. So you should be used $_POST[] or $_REQUEST[].
please verify your HTML.

Error Fetching Data From a PHP Server Running MySQL with Angular JS

I am getting a [$http:baddata] error when my Angular app calls my php file.
I'm not sure where the error is triggering exactly, but I believe it's a problem constructing the json object! I've attached all relevant code. Any help would be amazing. Thanks in advance :)
Angular documentation shows this
This is the PHP file which connects to my database and attempts to return a JSON formatting string back to the calling file
<?php
echo '<script>console.log("Inside php file!")</script>';
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
require_once('mysqli_connect.php');
$query = "SELECT rideid, destination, price, capacity, userid, origin, departDate, vehicle FROM rides";
$result = #mysqli_query($dbc, $query);
$outp = "";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "") {$outp .= ",";}
$outp .= '{"Origin":"' . $rs["origin"] . '",';
$outp .= '"Destination":"' . $rs["destination"] . '",';
$outp .= '"Price":"'. $rs["price"] . '"}';
$outp .= '"Capacity":"'. $rs["capacity"] . '"}';
}
$outp ='{"records":['.$outp.']}';
//echo '<script>console.log(JSON.stringify('.$outp.'))</script>';
$conn->close();
echo($outp);
This is the Angular app making the request to the PHP file
<html>
<head>
<!-- Include Angular -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>
</head>
<body>
<!-- Ride Table -->
<div ng-app = "rideAppTest" ng-controller= "rideCtrlTest">
<table>
<tr ng-repeat = "x in names">
<td>{{x.Origin}}</td>
<td>{{x.Destination}}</td>
<td>{{x.Price}}</td>
<td>{{x.Capacity}}</td>
</tr>
</table>
</div>
<!-- End Ride Table -->
<!--Ride Table Script-->
<script>
var app = angular.module('rideAppTest', []);
app.controller('rideCtrlTest', function($scope, $http) {
$http.get("angularFilter.php")
.then(
function (response) {
$scope.names = response.data.records;
},
function(data){
console.log("Error!" + data);
}
);
});
</script>
</body>
</html>
Don't construct the JSON the way you are doing, first collect everything inside an array or an object then do echo json_encode($result);
Something like this:
$outp = [];
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
$outp[] = $rs;
}
echo json_encode(["records" => $outp]);
Thank to #Madhav for the help. This is what ended up working for me :)
while($rs = mysqli_fetch_array($result)) {
$myArray[] = array(
'Origin' => $rs["origin"],
'Destination' => $rs["origin"],
'Price' => $rs["price"],
'Capacity' => $rs["capacity"]
);
}
echo json_encode(["records" => $myArray]);

Replicate the same data request query, but using a JavaScript Ajax post

Replicate the same data request query, but use a JavaScript Ajax post so that it doesn’t refresh the page on button press, just requests another page and display in a section on the page.
i need some help changing this to a ajax post
my code
*<?php
if(isset($_POST['submit']))
{
$success = $_POST['success'];
$dates = $_POST['dates'];
$datee = $_POST['datee'];
/*** mysql hostname ***/
$hostname = 'localhost';
$dbname = '*******';
/*** mysql username ***/
$username = 'root';
/*** mysql password ***/
$password = '*******';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
$tablename = 'login_attempts';
$sql = 'SHOW COLUMNS FROM `'.$tablename.'`';
$fields = array();
$csv = array();
$stmt = $dbh->query($sql);
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
array_push($fields, $row['Field']);
}
array_push($csv, $fields);
$success = mysql_real_escape_string($success);
$sql = "SELECT * FROM $tablename WHERE success = '".$success."' AND attempted >='".$dates."' AND attempted <='".$datee."'";
$stmt = $dbh->query($sql);
$stmt->execute();
$csv = array();
while($row = $stmt->fetch(PDO::FETCH_NUM))
{
array_push($csv, $row);
}
$fp = fopen('file.csv', 'w');
foreach ($csv as $row) {
fputcsv($fp, $row);
}
fclose($fp);
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=export.csv");
header("Pragma: no-cache");
header("Expires: 0");
readfile('file.csv');
$dbh = null;
} catch(PDOException $e) {
echo $e->getMessage();
}
exit();}
?>
<html>
<head>
<title>csv with criteria</title>
</head>
<body>
<form action="csv2.php" method="post" enctype="multipart/form-data">
Select data range
<br>
<input type="date" name="dates" id="dates"> Starting date
<br>
<input type="date" name="datee" id="datee"> Ending date
<br>
Select what data you'd like
<br>
<input type="radio" name="success" value="1" checked> Yes<br>
<input type="radio" name="success" value="0"> No<br>
<input type="submit" value="show" name="submit">
<br>
</form>
</body>
</html>*
If you want to use AJAX request on form submit you should:
Import the jQuery library: e.g. <script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
Create a new JavaScrpit file where you will catch the form submit event, send jQuery request and analize the response, e.g.:
$(document).ready(function(){
$("#myForm").submit(function(e){
e.preventDefault(); //stop sending the form
//here you should validate your form
//submit it via AJAX:
$.ajax({
url: "csv2.php",
data: { dates: $("#dates").val(), datee: $("#datee").val(), $('input[name='success']:checked', '#myForm').val() }
})
})
});
You can use another functions of AJAX object such as success or error callback functions: jQuery.ajax(). Don't forget to add ID to your form.
You can see this post where it's explained how to make a good ajax call to POST parameters. But you will need to separate this portion of code :
<?php
if(isset($_POST['submit']))
{
$success = $_POST['success'];
$dates = $_POST['dates'];
$datee = $_POST['datee'];
/*** mysql hostname ***/
$hostname = 'localhost';
$dbname = '*******';
/*** mysql username ***/
$username = 'root';
/*** mysql password ***/
$password = '*******';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
$tablename = 'login_attempts';
$sql = 'SHOW COLUMNS FROM `'.$tablename.'`';
$fields = array();
$csv = array();
$stmt = $dbh->query($sql);
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
array_push($fields, $row['Field']);
}
array_push($csv, $fields);
$success = mysql_real_escape_string($success);
$sql = "SELECT * FROM $tablename WHERE success = '".$success."' AND attempted >='".$dates."' AND attempted <='".$datee."'";
$stmt = $dbh->query($sql);
$stmt->execute();
$csv = array();
while($row = $stmt->fetch(PDO::FETCH_NUM))
{
array_push($csv, $row);
}
$fp = fopen('file.csv', 'w');
foreach ($csv as $row) {
fputcsv($fp, $row);
}
fclose($fp);
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=export.csv");
header("Pragma: no-cache");
header("Expires: 0");
readfile('file.csv');
$dbh = null;
} catch(PDOException $e) {
echo $e->getMessage();
}
exit();}
?>
into one another php file.

Updating Edited Value Using Jquery/PHP/Mysql

can some one help me out in updating edited value in mysql db using jquery/php.
I have three buttons edit/save/cancel
when i click on edit button span data pushed into input text and edit button replaced with save button!!
when i click on edit button i'll get span data in my text box with save and cancel button but when i try to update using save button its not updating in my db and in UI
Code
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function showdata()
{
$.ajax({
url:"pages/feeds.php",
type:'post',
async:false,
data:{
showtable:1
},
success:function(re){
$('#showdata').html(re);
}
});
}
$('#orders').delegate('.editOrder','click',function(e){
e.preventDefault(e);
var $li = $(this).closest('li'); $li.find('input.name').val($li.find('span.name').html());
$li.addClass('edit');
});
$('#orders').delegate('.cancelEdit','click',function(e){
e.preventDefault(e);
$(this).closest('li').removeClass('edit');
});
//Edit Code
$('body').delegate('.edit','click',function(){
var IdEdit = $(this).attr('ide');
$.ajax({
url:"pages/feeds.php",
type:"post",
data:{
editvalue:1,
id:IdEdit
},
success:function(show)
{
$('#id').val(show.id);
$('#url1').val(show.url);
}
});
});
//Ends
//Update Starts
$('.update').click(function(){
var id = $('#id').val()-0;
var urls = $('#url1').val();
$.ajax({
url:"pages/feeds.php",
type:"post",
async:false,
data:{
update:1,
id:id,
upurls:urls
},
success:function(up)
{
$('input[type=text]').val('');
showdata();
},
error:function(){
alert('error in updating');
}
});
});
//UPdate Ends
</script>
<style type="text/css">
ul li .edit{
display:none;
}
ul li.edit .edit{
display:initial;
}
ul li.edit .noedit{
display:none;
}
</style>
</head>
<body>
<ul id="orders">
<?php
$sql = "select * from demo";
$result = mysql_query($sql);
while($row = mysql_fetch_object($result))
{
?>
<li>
<span class="noedit name" value='<?php echo $row->id;?>'><?php echo $row->url;?></span>
<input id="url1" class="form-control edit name" value="<?php echo $row->id;?>"/>
<a ide='<?php echo $row->id;?>' id="edit" class='editOrder' href="#" style="display:block-inline;">EDIT</a>
<a idu='<?php echo $row->id;?>' id="update" class='update saveEdit' href='#' style='display:none;'>SAVE</a>
<a idd='<?php echo $row->id;?>' id="delete" class='delete' href="#" style="display:block-inline;">DELETE</a>
<a idc='<?php echo $row->id;?>' id="cancel" class='cancelEdit edit' href='#' style='display:none;'>CANCEL</a>
</li>
<?php } ?>
</ul>
</body>
</html>
<?php
//Edit Starts
if(isset($_POST['editvalue']))
{
$sql = "select * from deccan where id='{$_POST['id']}'";
$row = mysql_query($sql);
$rows = mysql_fetch_object($row);
header("Content-type:text/x-json");
echo json_encode($rows);
exit();
}
//Ends
//UPdate Starts
if(isset($_POST['update']))
{
$sql = "
update deccan
set
url='{$_POST['upurls']}'
where id='{$_POST['id']}'
";
$result = mysql_query($sql);
if($result)
{
//alert('success');
echo 'updated successfully';
}
else
{
//alert('failed');
echo 'failed to update';
}
}
?>
Alright. I was still missing the following code from you, so you'll have to add these yourself:
The HTML element with parameter id="id" needed for $('#id').val(text.id);
The HTML element with parameter id="url1" needed for $('#url1').val(text.url);
The PHP response code for JS function showdata(); inside feeds.php
Since I don't have your database here, I was unable to test the code. It should work fine, but if anything is wrong, just let me know:
PHP file: index.php
<?php
// Include PDO class
include_once("pdo.class.php");
// Database connection settings
define("DB_HOST", "localhost");
define("DB_USER", "username");
define("DB_PASS", "password");
define("DB_NAME", "database");
?>
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<!-- CSS resources -->
<link rel="stylesheet" type="text/css" href="style.css">
<!-- Javascript resources -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="main.js"></script>
<title>Update Script</title>
</head>
<body>
<ul id="orders">
<?php
// Instantiate database
$db = new Database;
// Try getting data from database
Try {
// Query
$db->query("SELECT * FROM demo");
// Get results
$data = $db->resultset();
// Echo reults
foreach($data as $row){ ?>
<li>
<span class="noedit name" value="<?php echo $row['id']; ?>"><?php echo $row['url']; ?></span>
<input id="url1" class="form-control edit name" value="<?php echo $row['id']; ?>" />
<a data-ide="<?php echo $row['id']; ?>" class='editOrder' href="#" style="display:block-inline;">EDIT</a>
<a data-idu="<?php echo $row['id']; ?>" class='update saveEdit' href='#' style='display:none;'>SAVE</a>
<a data-idd="<?php echo $row['id']; ?>" class='delete' href="#" style="display:block-inline;">DELETE</a>
<a data-idc="<?php echo $row['id']; ?>" class='cancelEdit edit' href='#' style='display:none;'>CANCEL</a>
</li>
<?php }
//Catch any database errors
} Catch(PDOException $e){
echo "Database error:". $e->getMessage();
}
?>
</ul>
</body>
</html>
Javascript file: main.js
$('#orders').delegate('.editOrder','click',function(e){
e.preventDefault();
var $li = $(this).closest('li');
$li.find('input.name').val($li.find('span.name').html());
$li.addClass('edit');
});
$('#orders').delegate('.cancelEdit','click',function(e){
e.preventDefault();
$(this).closest('li').removeClass('edit');
});
//Edit Code
$('body').delegate('.edit','click',function(){
var IdEdit = $(this).attr('data-ide');
$.ajax({
url: "pages/feeds.php",
type: "POST",
data: 'editvalue=1&id='+IdEdit,
success: function(text){
$('#id').val(text.id);
$('#url1').val(text.url);
}
});
});
//Update Code
$('.update').click(function(){
var id = $('#id').val()-0;
var urls = $('#url1').val();
$.ajax({
url: "pages/feeds.php",
type: "POST",
async: false,
data: 'update=1&id='+id+'&upurls='+urls,
success: function(text){
$('input[type=text]').val('');
showdata();
},
error:function(){
alert('Error in updating');
}
});
});
function showdata(){
$.ajax({
url: "pages/feeds.php",
type: "POST",
async: false,
data: 'showtable=1',
success:function(text){
$('#showdata').html(text);
}
});
}
CSS file: style.css
ul li .edit{
display:none;
}
ul li.edit .edit{
display:initial;
}
ul li.edit .noedit{
display:none;
}
PHP file: feeds.php
<?php
// Include PDO class
include_once("pdo.class.php");
// Database connection settings
define("DB_HOST", "localhost");
define("DB_USER", "username");
define("DB_PASS", "password");
define("DB_NAME", "database");
// Instantiate database
$db = new Database;
// Edit
if(isset($_POST['editvalue']) && $_POST['editvalue'] == 1){
// Try getting data from database
Try {
// Query
$db->query("SELECT * FROM deccan WHERE id = :id");
// Prepare POST data (to prevent SQL injection)
$db->bind(":id", $_POST['id']);
// Get result
$data = $db->single();
// Set header JSON
header("Content-type:text/x-json");
// Return result
echo json_encode($rows);
} Catch(PDOException $e){
echo "Database error:". $e->getMessage();
}
} else if(isset($_POST['update']) && $_POST['update'] == 1){
// Try updating data in database
Try {
// Query
$db->query("UPDATE deccan SET url = :url WHERE id = :id");
// Prepare POST data (to prevent SQL injection)
$db->bind(":url", $_POST['upurls']);
$db->bind(":id", $_POST['id']);
// Execute Query
$db->execute();
// Return succes
echo 'updated successfully';
} Catch(PDOException $e){
echo "Database error:". $e->getMessage();
}
} else if(isset($_POST['showtable']) && $_POST['showtable'] == 1){
/*
This part was not included in your code, so write it
yourself using above data as examples
*/
}
?>
PHP file: pdo.class.php
<?php
Class Database {
private $host = DB_HOST;
private $user = DB_USER;
private $pass = DB_PASS;
private $dbname = DB_NAME;
private $dbh;
private $error;
private $stmt;
public function __construct(){
// Set DSN
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
// Set options
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
// Create a new PDO instanace
try{
$this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
}
// Catch any errors
catch(PDOException $e){
$this->error = $e->getMessage();
return $this->error;
}
}
public function query($query){
$this->stmt = $this->dbh->prepare($query);
}
public function bind($param, $value, $type = null){
if (is_null($type)) {
switch (true) {
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
}
}
$this->stmt->bindValue($param, $value, $type);
}
public function execute(){
return $this->stmt->execute();
}
public function column(){
$this->execute();
return $this->stmt->fetchAll(PDO::FETCH_COLUMN);
}
public function resultset(){
$this->execute();
return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}
public function single(){
$this->execute();
return $this->stmt->fetch(PDO::FETCH_ASSOC);
}
public function rowCount(){
return $this->stmt->rowCount();
}
public function lastInsertId(){
return $this->dbh->lastInsertId();
}
public function beginTransaction(){
return $this->dbh->beginTransaction();
}
public function endTransaction(){
return $this->dbh->commit();
}
public function cancelTransaction(){
return $this->dbh->rollBack();
}
public function debugDumpParams(){
return $this->stmt->debugDumpParams();
}
}
?>
I would normally have two scripts (.php) files.
One to display the form and one to catch the submission (possibly via ajax)
You can have both in the same .php file but then you'd want to check before outputting any text whether you have any POST data to process.
If you go with two files
view file:
<html>
<body>
<form method="POST" action="path/to/formname_submit.php">
your form fields go here
<input name="somefield"/>
...
</form>
<script>
//your jquery code
....
</script>
<body>
</html>
submit file
<?php
if (empty($_POST['id'])){
die("no ID");
};
if (empty($_POST['editvalue'])){
die("no editvalue");
}
//get a database connection
$db = mysqli(DBHOST,DBUSER,DBPASS,DBNAME);
$db->set_charset("utf8");
// read in the POST data
//should do some more validation / anti SQL injection
$editvalue = $db->escape_string($_POST['editvalue']);
$id = intval($_POST['id']);
$sql = "UPDATE sometable SET `field` = '$editvalue' WHERE id=$id";
if ($db->query($sql)){
echo 'Success';
}
else {
echo 'UPDATE ERROR:'.$db->errno.': '.$db->error;
}
your jquery can now send the data to the second script and see if the data coming back from the call is 'Success' and display an error if it's not.

Categories