Database query not working with xeditable plugin - php

I have created a table with popup unabled editing with xeditable plugin and trying submit my data with ajax call to the database. The following is my table row code:
echo "<td>" . $row['loan_status'] . "</td>";
I have tried debugging and in the Network tab of firefox I could see the data being posted as follows :
Form Data:
name : "loan_amount"
value: "2000"
pk: "1"
but the response from the post.php is this field is required . Here is my post.php code
$pk = $_POST['pk'];
$name = $_POST['name'];
$value = $_POST['value'];
/*
Check submitted value
*/
if(!empty($value)) {
$result = mysql_query('update k_loans set '.mysql_escape_string($name).'="'.mysql_escape_string($value).'" where loan_id ="'.mysql_escape_string($pk).'"');
print_r($_POST);
} else {
echo "This field is required!";
}
My jquery code for th xeditable plugin is as follows:
$(document).ready(function() {
//toggle `popup` / `inline` mode
$.fn.editable.defaults.mode = 'popup';
$('#loan a').editable({
type: 'text',
name: 'loan_amount',
url: '../payments/post.php',
title: 'Enter amount',
ajaxOptions: {
type: 'put'
}
});
});
But i am unable to understand the issue as the query seems perfectly fine to me , still the database is not getting updated .
Anyone who can guide me in the right direction . Thanks

The first issue with the script provided by the xeditable on their github uses mysql which is not safe to use these days . So I have shifted all of them to use mysqli. Here is the working code for anyones reference :
<?php
$server = "localhost";
$username = "user";
$password = "pass";
$database = "db";
$con = new mysqli($server,$username,$password,$database);
if (!$con){
die('Could not connect: ' . mysqli_connect_error($con));
echo "Cudnt cnnect";}
else{
echo "connected";
}
var_dump($_POST);
$pk = $_POST['pk'];
$name = $_POST['name'];
$value = $_POST['value'];
/*
Check submitted value
*/
if(!empty($value)) {
if ($result = mysqli_query($con,'update k_loans set '.mysqli_real_escape_string($con,$name).'="'.mysqli_real_escape_string($con,$value).'" where loan_id ="'.mysqli_real_escape_string($con,$pk).'"'));
{
echo "Update successful";
}
mysqli_close($con);
print_r($_POST);
} else {
echo "This field is required!";
}
?>

Related

update table in database with ajax

i want to insert selected texts in my page in table with clicking on button in my page but my problem is it doenst insert . select text is correct i tested it.
response that i receive is my selected texts
This is my index page and i passed my texts into variable text
<script src="jquery-3.2.1.min.js"></script>
<script>
$(document).ready(function () {
var text = $("span:not([dir=rtl])").text();
$("#btn").click(function () {
$.ajax({
type:'post',
url:'process.php',
data:{'text':text},
success:(function (response) {
alert(response);
})
})
})
})
</script>
this is my process.php that connects to database and perform query but runs else statement
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "sahifeDB";
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = 'update sahife_tbl set english ='. $_POST['text'].' where id=1 ';
$result = $conn->query($conn,$sql);
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
You need to put " in update statement as datatype is text for field
change your query to:
$sql = 'update sahife_tbl set english ="'. $_POST['text'].'" where id=1 ';
Also use Prepared statement to prevent from sql injection
You need to put quotes around your string value in the query otherwise your DB will try to parse the text as part of the syntax and fall over.
$sql = "update sahife_tbl set english ='". $_POST['text']."' where id=1 ";
But again as mentioned in my comment on your question, this is super insecure, you want to use parameterisation instead - https://stackoverflow.com/a/60496/635522

Phonegap Ajax and wampserver/php

I am currently trying to simply get Ajax to 'activate' a php file on wampserver
Better to show the code that explain I think
The following is a function activated by a button, the HTML/JS all works fine
var jsonString = "";
function jsonconversion(){
jsonString = JSON.stringify(myArr);
return jsonString;
console.log(jsonString);
$.ajax({
type: "POST",
url: "http://xx.xx.xx.xx:80/xx/index2.php",
data: jsonString,
complete: function() {
console.log("Success");
},
error: function() {
console.log("Function: forward_to_server() error")
}
});
}
However, I can't seem to access the php file. For ease, I am not even using the jsonString in the php file, instead I am simply trying to post some integers into a database on wamp. The php file loaded by itself works fine
<?php
$servername = "localhost";
$username = "root";
$password = "xx";
$dbname = "xx";
//$myArray = $_REQUEST['jsonString'];
$myArray = array(100,1,19);
$con = mysqli_connect($servername,$username,$password ,$dbname) or die ("could not connect database");
echo $myArray;
$keys = array_keys($myArray); // get the value of keys
$rows = array(); // create a temporary storage for rows
foreach($keys as $key) { // loop through
$value = $myArray[$key]; // get corresponding value
$rows[] = "('" . $key . "', '" . $value . "')";
// add a row to the temporary storage
}
$values = implode(",", $rows); // 'glue' your rows into a query
$sql = "INSERT INTO php_test (temp, sound, light) VALUES (10,20,30)"; //. $values
$rs = mysqli_query($con,$sql) or die(mysqli_error($con));
if ($con->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}
$con->close();
?>
However when I call the function in phonegap, it doesn't seem to work, I have no errors either which is hurting the process :(
Wamp server is 'online' and I can access it from the internet.
Any guidance on this?
Thanks in advance

How to send php variable into angularjs function (different files)

I have a variable in php file reg.php. I want to send that variable into .js file in different place (app.reg.js). I tried a lot of solutions but they didn't work. I have to admit that I'm a new programmist, and this is my first own project in angularjs.
How my app exactly works :
In index.html i use routing to get to register.html (this working well).
register.html has a form app.reg.js sending it into reg.php
App.reg.js :
http://www.chopapp.com/#kpwad4zs (i'm getting ALL THE TIME "your post is not properly formatted as code -.-).
reg.php (it works fine! Just need variable $loginExist from it :
http://www.chopapp.com/#yvqivk5m
I would like to send variable from reg.php to the app.reg.js file. How to do this? I think i tried all of the solutions from here but non of them worked...
php file
session_start();
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$login = $request->login;
$password = $request->password;
require_once "connect.php";
mysqli_report(MYSQLI_REPORT_STRICT);
try {
$connect = new mysqli($host,$db_user,$db_password,$db_name);
if($connect->connect_errno!=0)
{
throw new Exception(mysqli_connect_errno());
} else {
//Does login exist?
$result = $connect->query("SELECT id FROM `users` WHERE login = '" . mysql_real_escape_string($login) . "'");
$login_count = $result->num_rows;
if($login_count>0) {
$loginExist = true;
}
else {
$loginExist = false;
$password = $login . $password;
$password = password_hash($password, PASSWORD_DEFAULT);
//$sql = "INSERT INTO users (login, password) VALUES ('$login','$password')";
$sql = "INSERT INTO users (login, password)VALUES('" . mysql_real_escape_string($login) . "', '" . mysql_real_escape_string($password) . "')";
if($connect->query($sql) === TRUE) {
echo "ok!";
} else {
echo "Error: " . $sql . "<br>" . $connect->error;
}
}
$connect->close();
}
} catch(Exception $e) {
echo 'Server error!';
}
echo json_encode(['res' => $loginExist]);
?>
js file
app.controller('regCtrl', function ($scope, $window, $http) {
$scope.send = function () {
var form = {
password: scopeToPasswordImput,
login: scopteToLoginImput
};
$http({
url:'reg1.php',
method: "POST",
data: form
}).then(function (response) {
if (response) {
//I Want to use php variable in this section
//$window.alert("");
console.log(response.data.res);
} else {
console.log("Network response was not ok.");
window.location.href = '/';
}
})
};
});

Variable is empty

I am trying to show data from the database in my textbox. But when I start the script I am getting no results. I tested the script in different ways and i figured out that the variable: $product1 is empty. Does anybody know how I can fix this?
index.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM forms";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<select class='form-control select2' id='product1' name='product1' onChange='getPrice(this.value)' style='width: 100%;'>";
echo "<option selected disabled hidden value=''></option>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value='" . $row["id"]. "'>" . $row["name"]. "</option>";
}
echo "</select>";
} else {
echo "0 results";
}
$conn->close();
?>
<html>
<body>
<!-- Your text input -->
<input id="product_name" type="text">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function getPrice() {
// getting the selected id in combo
var selectedItem = jQuery('.product1 option:selected').val();
// Do an Ajax request to retrieve the product price
jQuery.ajax({
url: 'get.php',
method: 'POST',
data: 'id=' + selectedItem,
success: function(response){
// and put the price in text field
jQuery('#product_name').val(response);
},
error: function (request, status, error) {
alert(request.responseText);
},
});
}
</script>
</body>
</html>
get.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname) ;
// Check connection
if ($conn->connect_error)
{
die('Connection failed: ' . $conn->connect_error) ;
}
else
{
$product1 = filter_input(INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT) ;
$query = 'SELECT price FROM forms WHERE id=" . $product1 . " ' ;
$res = mysqli_query($conn, $query) ;
if (mysqli_num_rows($res) > 0)
{
$result = mysqli_fetch_assoc($res) ;
echo $result['price'];
}else{
echo 'no results';
}
}
?>
Change
var selectedItem = jQuery('.product1 option:selected').val();
To
var selectedItem = jQuery('#product1 option:selected').val();
You are selecting a class with name product1, but you set only an ID with this name. Id's are specified with # and classes with .
Update on your script, because you used getPrice(this.value);
<script>
function getPrice(selectedItem) {
// Do an Ajax request to retrieve the product price
jQuery.ajax({
url: 'get.php',
method: 'POST',
data: 'id=' + selectedItem,
success: function(response){
// and put the price in text field
jQuery('#product_name').val(response);
},
error: function (request, status, error) {
alert(request.responseText);
},
});
}
</script>
TIP:
Did you know that you can use jQuery.ajax and jQuery('selector') also like this: $.ajax and $('selector') :-)
You have not a form tag in your HTML. The default form Method is GET.
In Your get.php you try to get a POST Variable with filter_input
The function filter_input returns null if the Variable is not set.
Two possible solutions:
1. Add a form to your html with method="post"
2. Change your php code to search for a GET variable

PHP - How to get the selected item from dropdown menu populated from query before POST

I would like to know how do I get the selected name from a dropdown menu, being populated by a query using phpmyadmin, to display a picture according to the selection.
For example, if the users selects "Mountains" from the drop down menu I want to be able to use that value and make another query to get the specific image URL from the database and display it, and every time the user changes selection the image changes accordingly.
And yes, I know, mysql commands are deprecated.
If you need any more details let me know.
<select name='picker'>";
<?php
mysql_connect('localhost','root','');
mysql_select_db('...');
$sql = "...";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['name'] . "'>" . $row['name'] ."</option>";
}
$selectoption = $_REQUEST['picker'];
mysql_connect('localhost','root','');
mysql_select_db('...');
$sql3 = "...";
$image = mysql_query($sql3);
?>
<img src="<?php echo $image; ?>">
Create 2 Files
main.php
fetchimage.php
Note: Both files should be on same location, if root folder they look like this
main.php
fetchimage.php
if inside folder assuming folder name is alpha then
alpha/main.php
alpha/fetchimage.php
Now create main.php file and put following PHP and jQuery code in it.
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
mysql_connect('localhost','root','');
mysql_select_db('...');
?>
<select name="picker" id="picker">
<?php
$sql = "SELECT * FROM table";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
?>
<option value="<?php echo $row['name'];?>"><?php echo $row['name'];?></option>
<?php } ?>
</select>
//Here Show the Images
<div id="imged"></div>
jQuery
//JQuery library always comes first.
<script>
$(document).ready(function() {
$("#picker").change(function(){
var name=$(this).val();
alert(name); //This will show an alert when value selected, remove this **alert** in production mode, use it only in development mode.
var dataString = 'name='+ name;
$.ajax({
type: "POST",
url: "fetchimage.php",
data: dataString,
cache: false,
success: function(data){
$("#imged").html(data);
}
});
});
});
</script>
More information about jQuery change function and Ajax Method
Bind #picker change function with <select>
Bind Ajax success function with id="imged" to display the image
Now create second file name fetchimage.php and put following code in it nothing else.
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
mysql_connect('localhost','root',''); //Put Database Connection Here
mysql_select_db('...'); //Put Database Name Here
if(isset($_POST['name'])){
$selectoption = mysql_real_escape_string($_POST['name']);
$sql = "SELECT Image FROM table WHERE name = '$selectoption'";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
//This will show the image inside <div id="imged"></div>
echo '<img src="'. $row["Image"] .'" alt="" />';
}
?>
Side Note: keep in mind, mysql is deprecated, should start using mysqli now.
MySQLi (Procedural Example)
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
//Conntection Credentials
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "databasename";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//Run Query
$sql = "SELECT imagename FROM table";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo $row["imagename"];
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
OP requested an example code and provided other detail e.g (database) via email.
You can use ajax on select onchange event then change the content of the image.

Categories