I am having a problem with contenteditable. I am trying to make a ajax post methot using contenteditable. I have two contenteditable div.
If it does not write anything, it must be NULL from the database table but it shows empty post not setting NULL.
AJAX
$("body").on("click", ".post", function() {
var text1 = $("#text1").html();
var text2 = $("#text2").html();
var data = 'text1=' + encodeURIComponent(text1) + '&text2=' + encodeURIComponent(text2);
$.ajax({
type: 'POST',
url: '/requests/post.php',
data: data,
cache: false,
beforeSend: function() {
// Do something
},
success: function(html) {
console.log("post sended");
}
});
});
HTML
<div class="abc" id="text1" contenteditable="true" placeholder="Write something1"></div>
<div class="text2" id="text2" contenteditable="true" placeholder="Write something2"></div>
post.php
<?php
include "../inc/inc.php";
if(isset($_POST['text1'])){
$text1 = mysqli_real_escape_string($db, $_POST['text1']);
$text2 = mysqli_real_escape_string($db, $_POST['text2']);
$data = $POST->POST($uid,$text1, $text2);
}
?>
and POST function
public function POST($uid,$text1, $text2) {
$time=time(); // Current post time
$ip=$_SERVER['REMOTE_ADDR']; // user ip
$query = mysqli_query($this->db,"SELECT post_id,text1,text2 FROM `posts` WHERE uid_fk='$uid' order by post_id desc limit 1") or die(mysqli_error($this->db));
$result = mysqli_fetch_array($query, MYSQLI_ASSOC);
// Add the insert POST
$query = mysqli_query($this->db,"INSERT INTO `posts` (text1,text2, uid_fk,time) VALUES ('$text1','$text2','$uid','$time')") or die(mysqli_error($this->db));
}
All code is working fine.But problem is text2. If doesn't write any text it is showing empty result in database. I want to set id default NULL
Wrong way,
It should looks like this
What i am missing here? Anyone can help me in this regard ?
The problem is you're passing an empty value instead of null itself
Just check if the string is empty and put null if it's empty
if(isset($_POST['text1'])){
$text1 = mysqli_real_escape_string($db, $_POST['text1']);
$text2 = mysqli_real_escape_string($db, $_POST['text2']);
$text1 = !empty($text1) ? $text1 : null;
$text2 = !empty($text2) ? $text2 : null;
$data = $POST->POST($uid,$text1, $text2);
}
And also you're insert statement is adding ' around the string which will make null as string 'null' :
So to process accordingly use pdo:
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname","$dbusername","$dbpassword");
$stmt = $dbh->prepare("INSERT INTO `posts` (text1,text2, uid_fk,time) VALUES (:text1,:text2,:uid,:time)");
$statement->execute(array(':text1'=>$text1,
':text2', $text2,
':uid', $uid,
':time', $time
));
Edit:
For some reasons if you can't or don't want to use PDO. You'd end up hacking in the sql. Something like:
$text2 = !empty($text2) ? "'".$text2."'":null;
$text1 = !empty($text1) ? "'".$text1."'":null;
$query = mysqli_query($this->db,"INSERT INTO `posts` (text1,text2, uid_fk,time) VALUES ($text1,$text2,'$uid','$time')");
Add a precheck to the logic, because you have to give NULL or not useing the field in the insert to get an real NULL in the table.
// Add the insert POST
$text2 = $text2?"'$text2'":'NULL';
$query = mysqli_query($this->db,"INSERT INTO `posts` (text1,text2, uid_fk,time) VALUES ('$text1',$text2,'$uid','$time')") or die(mysqli_error($this->db));
INSERT TEXT vs NON-TEXT
Insert a real NULL
INSERT INTO posts (text1) VALUES (null)
Insert a text with content NULL
INSERT INTO posts (text1) VALUES ('NULL')
Insert table default:
INSERT INTO posts (text1) VALUES (default)
Insert a text with content default
INSERT INTO posts (text1) VALUES ('default')
To understand it more here an example sql:
INSERT INTO test (testfield) VALUES (null), ('null'), (default), ('') ;
Make a table test with one field VARCHAR(50) NULL DEFAULT NULL and execute the SQL and look what you get. You will get 2 entries with real null, one with empty string and one with an string null.
Related
I have a search bar that works for displaying AJAX live search results with MySQL, PHP, and JS.
The problem is I can’t figure out how to get the search results to display “No matches found” or hide the results div completely when a query doesn’t match any “Name” in the MySQL database.
Currently, when a user types something into the search bar that doesn’t match any “Name” in the database, a blank result pops up under the AJAX live search result. I would instead like for the message “No matches found” to take over that blank result.
I have tried a number of else / if / echo codes and combinations in different orders and nothing has worked so far. I am also trying a different method of showing / hiding a div that displays “No matches found” based on the results.
How can I fix this code once and for all so that when the user searches any name that doesn’t match any name in the MySQL database, it will display "No matches found"?
Below are the files and codes I am currently using:
index.php
<form>
<input type="text" id="search" class="search" data-js="form-text"
placeholder="Search Over 100+ Resources..." autocomplete="off">
<button type="submit" class="Button" value="Submit"><i class="fa fa-
search"></i></button>
<div id="display"></div>
<div id="no-results" style="display:none"><ul><li id='hover'>No matches
found</li></ul></div>
</form>
ajax.php
<?php
//Including Database configuration file.
include "db.php";
//Getting value of "search" variable from "script.js".
if (isset($_GET['search'])) {
//Search box value assigning to $Name variable.
$Name = $_GET['search'];
//Search query.
$Query = "SELECT Name FROM search WHERE Name LIKE '$Name%' LIMIT 5";
//Query execution
$ExecQuery = MySQLi_query($con, $Query);
//Creating unordered list to display result.
echo '<ul>';
//Fetching result from database.
while ($Result = MySQLi_fetch_array($ExecQuery)) {
?>
<!-- Creating unordered list items.
Calling javascript function named as "fill" found in "script.js" file.
By passing fetched result as parameter. -->
<li onclick='fill("<?php echo $Result['Name']; ?>")'>
<a>
<!-- Assigning searched result in "Search box" in "index.php" file. -->
<?php
if ($ExecQuery > "0") {
echo $Result['Name'];
}
else {
echo "<li id='hover'>No matches found</li>";
}
?>
</li></a>
<!-- Below php code is just for closing parenthesis. Don't be confused. -->
<?php
}}
?>
</ul>
script.js
//Getting value from "ajax.php".
function fill(Value) {
//Assigning value to "search" div in "index.php" file.
$('#search').val(Value);
//Hiding "display" div in "index.php" file.
$('#display').hide();
}
$(document).ready(function() {
//On pressing a key on "Search box" in "index.php" file. This function will
be called.
$('#no-results').hide();
$("#search").keyup(function() {
//Assigning search box value to javascript variable named as "name".
$('#display').hide();
$('#no-results').css("display", "none");
var name = $('#search').val();
//Validating, if "name" is empty.
if (name == "") {
//Assigning empty value to "display" div in "index.php" file.
$('#no-results').css("display", "none");
}
//If name is not empty.
else {
//AJAX is called.
$.ajax({
//AJAX type is "Post".
type: "GET",
//Data will be sent to "ajax.php".
url: "ajax.php",
//Data, that will be sent to "ajax.php".
data: {
//Assigning value of "name" into "search" variable.
search: name
},
//If result found, this funtion will be called.
success: function(html) {
//Assigning result to "display" div in "index.php" file.
$("#display").html(html).show();
}
});
}
});
});
Updated
you should check your data that is valid and you have any result from your database query or not, if there is no record then you can print not found data message.
you should check the output of $ExecQuery and set if condition according to that.
let me now your output and result I hope this helps you.
Update ajax.php
Last updated section
echo "<li onclick='fill(`".$Result['Name']."`)'>".$Result['Name']."</li>";
Complete ajax.php
<?php
//Including Database configuration file.
include "db.php";
//Getting value of "search" variable from "script.js".
if (isset($_GET['search'])) {
//Search box value assigning to $Name variable.
$Name = $_GET['search'];
//Search query.
$Query = "SELECT Name FROM search WHERE Name LIKE '$Name%' LIMIT 5";
//Query execution
$ExecQuery = MySQLi_query($con, $Query);
//Creating unordered list to display result.
if ($ExecQuery->num_rows > 0) {
echo "<ul>";
while ($Result = MySQLi_fetch_array($ExecQuery)) {
// use the onclick function that defined in js file. you can use the ` sign in js instead of ' if you needed.
echo "<li onclick='fill(`".$Result['Name']."`)'>".$Result['Name']."</li>";
}
echo "</ul>";
}else{
echo "<ul><li>No Result Found!</li></ul>";
}
}
die();
?>
and your ajax code.
function fill(value) {
console.log(value);
$('#search').val(value);
$('#display').hide();
}
$(document).ready(function() {
//On pressing a key on "Search box" in "index.php" file. This function will be called.
$("#search").keyup(function() {
//Assigning search box value to javascript variable named as "name".
$('#display').hide();
$('#no-results').css("display", "none");
var name = $('#search').val();
//Validating, if "name" is empty.
if (name == "") {
//Assigning empty value to "display" div in "index.php" file.
$('#no-results').css("display", "block");
}
//If name is not empty.
else {
//AJAX is called.
$.ajax({
//AJAX type is "Post".
type: "GET",
//Data will be sent to "ajax.php".
url: "ajax.php",
//Data, that will be sent to "ajax.php".
data: {
//Assigning value of "name" into "search" variable.
search: name
},
//If result found, this funtion will be called.
success: function(html) {
if (html == '<ul><li>No Result Found!</li></ul>') {
$('#no-results').css("display", "block");
}else{
//Assigning result to "display" div in "index.php" file.
$("#display").html(html).show();
}
}
});
}
});
});
change other parts as you need.
AJAX is Asynchronous Javascript and XML. Why send back HTML ?
Pointers
If you're doing this via Ajax I would highly dis-advise sending pure HTML. You should send back some JSON data and handle it accordingly client side.
Use PDO instead of MySQLi
Solution PHP
<?php
include "db.php";
if (isset($_POST['search'])) {
$Name = $_POST['search'];
$Query = "SELECT Name FROM search WHERE Name LIKE '$Name%' LIMIT 5";
$ExecQuery = MySQLi_query($con, $Query);
$res = [];
while ($Result = MySQLi_fetch_array($ExecQuery)) {
$res[] = $Result['Name'];
}
echo json_encode($res);
}
Solution Javascript:
$.ajax({
//AJAX type is "Post".
type: "POST",
//Data will be sent to "ajax.php".
url: "ajax.php",
//Data, that will be sent to "ajax.php".
data: {
//Assigning value of "name" into "search" variable.
search: name
},
//If result found, this funtion will be called.
success: function(data) {
//Assigning result to "display" div in "search.php" file.
const list = JSON.parse(data);
const html = list.length > 0 ?
list.map(name=>{
`<li onclick="${name}">
<a>${name}</a>
</li>`
}).join("") :
`<li>No matches found</li>`
$("#display").html(`<ul>${html}</ul>`).show();
}
});
My Alert is showing that updated successfully but data is not updating in database and not able to click ok button of alert. Here is my php code for upresult.php. Hope This will b helpful. Thank you in advance
my jquery
$(document).ready(function(){
$("#form1").submit(function(event){
event.preventDefault();
var formData = new FormData(this);
$.ajax({
url:"upresult.php",
type:"POST",
data:formData,
async:true,
success:function(data) {
alert(data);
},
cache:false,
contentType:false,
processData:false
});
});
});
upresult.php
<?php
include("connection.php");
$no=trim($_POST['upno']);
$name=trim($_POST['upname']);
$mob=trim($_POST['upmob_no']);
$dob=trim($_POST['updob']);
$add=trim($_POST['upadd']);
$photo=trim($_FILES['upphoto']['name']);
$gen=trim($_POST['gender']);
$cn=trim($_POST['upcountry']);
$st=trim($_POST['upstate']);
$ct=trim($_POST['upcity']);
$qry="update stud set stud_name='".$name."',mobile='".$mob."',dob='".$dob."',address='".$add."',gender='".$gen."',country='".$cn."',state='".$st."',city='".$ct."' where stud_no='".$no."'";
$data=mysqli_query($conn,$qry);
if($data)
{
echo '<script language="javascript">';
echo 'alert("Updated Successfully")';
echo '</script>';
}
else {
echo '<script language="javascript">';
echo 'alert("Cannot update record")';
echo '</script>';
}
?>
You want to alert alert. Try with editing your flow control structure like this:
<?php
include("connection.php");
// you need to validate this data before sending it to update query
$no=trim($_POST['upno']);
$name=trim($_POST['upname']);
$mob=trim($_POST['upmob_no']);
$dob=trim($_POST['updob']);
$add=trim($_POST['upadd']);
$photo=trim($_FILES['upphoto']['name']);
$gen=trim($_POST['gender']);
$cn=trim($_POST['upcountry']);
$st=trim($_POST['upstate']);
$ct=trim($_POST['upcity']);
// this parameters should be binded to avoid SQL injection
$query = "
update stud
set
stud_name = '$name',
mobile = '$mob',
dob = '$dob',
address = '$add',
gender = '$gen',
country = '$cn',
state = '$st',
city = '$ct'
where stud_no = '$no';
";
/** This may be query for checking.
* Just execute it after first query and grab response from it.
* Depends of response you will return appropirate text message.
*/
$checkUpdateQuery = "
select if(count(*) = 1, true, false) as response
from stud
where stud_name = '$name',
and mobile = '$mob',
and dob = '$dob',
and address = '$add',
and gender = '$gen',
and country = '$cn',
and state = '$st',
and city = '$ct'
and stud_no = '$no';
";
/** mysqli_query will return false only if some error occurred.
* In other cases you will get true,
* so you need to check if data is updated by another query.
*/
$data = mysqli_query($conn, $query);
echo $data ? 'Updated Successfully' : 'Cannot update record';
Few things you should consider is do you have certain stud_no in database, mysqli_query returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.
If you want we can change this query. Can you use PDO instead of mysqli?
I'm trying to fetch data using jquery but I'm having a problem with htmlentities because it shows " instead of " in jquery.
Here is my code for input text:
<input type="text" name="material_name[]" id="material_name<?=$x?>" autocomplete="off" readonly="true" class="form-control oninput" />
And here's JQUERY Fetching the value
$.ajax({
url: 'fetchSelectedOrder.php',
type: 'post',
data: {productId : productId},
dataType: 'json',
success:function(response) {
// setting the rate value into the rate input field
$("#material_name"+row).val(response.material_name);
} // /success
}); // /ajax function to fetch the product data
}
fetchSelectedOrder.php
<?php
require_once 'checker.php';
$productId = $_POST['productId'];
$sql = "SELECT material_name FROM tbl_materials WHERE m_id = $productId";
$result = $controller->runQuery($sql);
$result->execute();
if($result->rowCount() >= 1) {
$row = $result->fetch(PDO::FETCH_ASSOC);
} // if num_rows
echo json_encode($row);
Data From Database:
I use htmlentities to prevent quote inside database.
How can I fetch " as "?
You can use html_entity_decode() to convert it back to the original text.
However, I recommend that you stop using htmlentities() when storing into the database. You don't need to prevent having quotes in the database. If you're getting syntax errors when you try to store it, you should fix the code to use parametrized statements rather than substituting variables into the string. And if you must substitute variables, you should use a proper escaping function, either mysqli::real_escape_string() or PDO::quote().
If you're trying to prevent XSS, call htmlentities() when you're displaying the output on a web page. If you're using JavaScript to display the results on a web page, use the textContent DOM property or the jQuery .text() method, rather than innerHTML or .html(). If you're assigning to the value property, it never gets executed so you don't need to do any encoding.
You can use the following function to decode html:
function htmlDecode(input){
var e = document.createElement('div');
e.innerHTML = input;
// handle case of empty input
return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
}
Usage:
$("#material_name"+row).val(htmlDecode(response.material_name));
That will display html as real text.
You could decode the HTML entities coming from the DB on server side.
<?php
require_once 'checker.php';
$productId = $_POST['productId'];
$sql = "SELECT material_name FROM tbl_materials WHERE m_id = $productId";
$result = $controller->runQuery($sql);
$result->execute();
if($result->rowCount() >= 1) {
$row = $result->fetch(PDO::FETCH_ASSOC);
} // if num_rows
// Run html_entity_decode on all $row values
foreach ($row as $k => $v) {
$row[$k] = html_entity_decode($v);
}
echo json_encode($row);
That also is a "patch" for a DB having bad values... But unlike the other answer, which relies on the end user's device, here is a server-side solution.
And please read about prepared statements to prevent injection...
This is my javascript code :
$(document).ready(function()
{
$("li").click(function() {
var childid = $(this).attr("id"); /* this works(gets id of clicked li) */
if(childid)
{
var child = childid.split(';;;');
$('#Grid').load('../Grid/FillWithGrid.php',{"name" : child[1], "family" : child[0]}); /* I think problem is here */
}
})
})
<div class="Grid" id="Grid">
This is index.php where it must be pasted
</div>
This is FillWithGrid.php:
<?PHP
header('Content-Type: text/html; charset=utf-8');
require_once("../Grid/conf.php");
$conn = mysql_connect(PHPGRID_DB_HOSTNAME,PHPGRID_DB_USERNAME,PHPGRID_DB_PASSWORD);
$CHName = mysql_real_escape_string($_GET["name"]); /*ERROR : Undefined value*/
$CHFamily = mysql_real_escape_string($_GET["family"]); /*ERROR : Undefined value*/
mysql_close($conn);
if($CHFamily & $CHName)
{
$query = "select * from `view_marks` where `name` = '$CHName' and `family` = '$CHFamily' ";
$dg1 = new C_DataGrid($query);
$dg1->enable_advanced_search(true);
$dg1 -> display();
}
?>
1)I can't get childname and childfamily from javascript. It says 'undefined name' and 'undefined family'. So It doesn't get value from javascript. --- RESOLVED!!!
2)It is showing blank page when I click on li...
Have anyone got any idea. Please help
Thanks!!!
When you provide data for load function, then the request method would be a POST instead of GET. Use $_POST in php to get the value instead of $_GET as shown below.
$CHName = mysql_real_escape_string($_POST["name"]);
$CHFamily = mysql_real_escape_string($_POST["family"]);
For further information on load(), refer this
You have an error in query
$query = "select * from `view_marks` where `name` = '$CHName' and '$CHFamily' ";
it should be
$query = "select * from `view_marks` where `name` = '$CHName' and `family` = '$CHFamily' ";
If I'm wrong i dont know what alse it can be ;-)
~Cheers
Try to use console.log() to check if values are passed, example:
$('#Grid').load('../Grid/FillWithGrid.php',{"name" : child[1], "family" : child[0]}, function(responseText){console.log(responseText)});
inside FillWithGrid.php:
print_r($_GET);
die;
Maybe it can help... if not - check HTTP requests/responses in browsers Developer Tools.
Send me a link (via priv) to problem, maybe I can solve it.
~Cheers
This has been an ongoing issue for me. You all have already helped so much. However, I am stuck again. I cannot get my .ajax() to run. For some reason the .click() won't even work without if(field != text) above my .ajax() call, but I digress.
My question is: Why is my ajax() not functioning properly and if this gets fixed will the table is have displayed update after the query is sent to the database without a page refresh?
Here is my script:
<script type="text/javascript">
$(document).ready(function()
{
$(".edit_td").click(function()
{
$(this).children(".text").hide();
$(this).children(".editbox").show();
}).children('.editbox').change(function()
{
var id=$(this).closest('tr').attr('id');
var field=$(this).data('field');
var text=$(this).val();
var dataString = 'id= '+ id +'&field= '+ field +'&text= '+ text;
alert("made variables");
if(field != text)
{
alert("in if");
$.ajax({
type: "POST",
url: "table_edit_ajax.php",
data: dataString,
cache: false,
success: function(html)
{
$("#first_"+ID).html(first);
$("#last_"+ID).html(last);
}
});
}
else
{
alert('Enter something.');
}
});
// Edit input box click action
$(".editbox").mouseup(function()
{
return false
});
// Outside click action
$(document).mouseup(function()
{
$(".editbox").hide();
$(".text").show();
});
});
</script>
Here is my table_edit_ajax.php
<?php
//connect to DB
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
echo 'in table_edit';
$id = mysqli_escape_String($_POST['id']);
$table = "owners";
$field = mysqli_escape_String($_POST['field']);
$text = mysqli_escape_String($_POST['text']);
$query = "UPDATE ".$table." SET ".$field."='".$text."' WHERE ".$table."_id = '".$id."'";
mysqli_query($query);
//close connection
mysqli_close($con);
?>
The first argument to all mysqli functions is the connection, statement, or result object.
$id = mysqli_escape_String($con, $_POST['id']);
$table = "owners";
$field = $_POST['field'];
$text = mysqli_escape_String($con, $_POST['text']);
$query = "UPDATE ".$table." SET ".$field."='".$text."' WHERE ".$table."_id = '".$id."'";
mysqli_query($con, $query);
$field shouldn't be escaped, since it's not a string value. Therefore, you need to validate it carefully, to prevent SQL injection. Perhaps instead of allowing the client to submit the field name to update, have them submit an integer, which you look up in an array to convert to a field name.
In your AJAX call, you may have a problem due to not encoding your parameters properly. Change the dataString assignment to:
var dataString = { id: id, field: field, text: text };
Then jQuery will encode it for you.
you are sending a data string
var dataString = 'id= '+ id +'&field= '+ field +'&text= '+ text;
and retrieving it through $_POST.
first check what is in $_POST
and use $_GET instead of $_POST
and change post in ajax to get
and what is first and last in success callback??