Save html code to mysql table with php and jquery ajax - php

Im trying to clone a div's content with jquery. After it is cloned i am sending it to a php page to be processed with Jquery Ajax. The php page saves it to a mysql database table. Then i need to retrieve it from the table on a different page and load it in another div. The mysql table cell is a blob that i save this html too. When i retrieve the table it echo's [object Object]. So i not usre if i am sending it to the save_invoice.php correctly or im not saving it to database correctly or last im not retrieving it correctly.
Html div: invoice.php
<div id="invoice_content">
<table>
<tr><td>Html Example</td></tr>
</table>
</div>
Jquery Code:
$(document).on('click', "#clone", function () {
var printContents = $("#invoice_content").clone(true, true);
//var $data = 'invoice=' + escape(printContents);
var $data = $(printContents).serialize();
$.ajax({ url: "functions/insert_html.php",
type: "POST",
dataType:"html",
data:$data,
success:function(obj){
alert(obj);
}
});
});
php: save_invoice.php
if (isset($_POST['invoice'])) {
$html = $_POST['invoice'];
$sql = "INSERT INTO `html table` (html)
VALUES ('" . mysql_real_escape_string($html) . "')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
}
php: view_invoice.php
if(isset($_GET)){
$id = $_GET['id'];
$sql = "SELECT html FROM `html table` WHERE id = '".$id."'";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$html_id = $row["html"];
}
mysqli_close($conn);
}
<div id="invoice_content">
<?php echo $html_id; ?>
</div>

Related

jQuery function doesn't update data when it is updated in the database

I would like to update the data in the frontend when it is changed in the database. The code I'm using is given below:
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<div id="test">
<?php
include('conn.php');
$query = "SELECT name FROM user_details WHERE user_id = 1;";
if(mysqli_fetch_assoc(mysqli_query($conn, $query))["name"] == "MyName")
echo 'Hi <b>MyName!</b>';
else
echo 'You are not <b>MyName</b>.';
?>
</div>
<script>
setInterval(function(){
$.get("/test.php", function(data){
let $data = $(data);
$("#test").append($data.find("#test > *"));
});
}, 1000);
</script>
However, when the data is updated, it does not get updated in the frontend unless refreshed. When I use jQuery's load() function, it works perfectly. Why does this not work?
As I suggested in the comment, if you create a stand alone PHP Script, it might be like:
getUserName.php
<?php
$id = (int)$_GET['id'];
include('conn.php');
$query = "SELECT name FROM user_details WHERE user_id = $id;";
$myName = "";
if ($result = mysqli_query($conn, $query)) {
while ($row = mysqli_fetch_assoc($result)) {
$myName = $row;
}
}
mysqli_free_result($result);
mysqli_close($conn);
header('Content-Type: application/json');
echo json_encode($myName);
?>
This is a very basic example and I would strongly advise you switch to using prepared statements to avoid the risk of SQL Injection.
In your HTML you can now do:
<script>
setInterval(function(){
$.getJSON("/getUserName.php", { id: 1 }, function(data){
$("#test").append(data.name);
});
}, 1000);
</script>
This will ping the script every second and you will have a list of names appearing.

MySQLI how to insert a form into database by language select

Im having an issue with form method.
How can I insert a form value in the database in different table by language select.
I have in my database the tables called article_en / articles_ro ,and when I chose with select english I want the values to be inserted in the article_en
Also when I select the language its not staying selected.
And if I write something in the inputs and chose a language the inputs are being cleared.
PS:Im a newby , I am still learning.
This is the language select code
<?php
define("LANG",$_GET['lang']);
include('../db.php');
function select_langs(){
global $conn;
echo'<h2 class="box-title">Select the language where you want to the article</h2>
<select id="select_language">
<option selected disabled hidden value=""></option>';
$get_languages = mysqli_query($conn, "SELECT lang,title from `languages`") or die(mysqli_error($conn));
while($row = mysqli_fetch_array($get_languages)){
if($row['title'] == $_GET['lang']){
echo'<option value="insert_article.php?lang='.$row['lang'].'" selected>'.$row['title'].'</option>';
}
else{
echo'<option value="insert_article.php?lang='.$row['lang'].'">'.$row['title'].'</option>';
}
}
echo'</select>';
}
?>
And this is the insert code.
<?php
include('./lang.php');
include('../db.php');
define("LANG",$_GET['lang']);
select_langs();
// extract data from form; store in variable
$title = $_GET['title'];
$link = $_GET['link'];
if (!empty($title) and !empty($link ) and !empty($_GET['lang'])) {
// Define the query to inser the song request
$sql = "INSERT INTO `articles_".LANG."`(title , link)VALUES (".$title.", ".$link.")";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$("#select_language").bind("change",function(){var n=$(this).val();return""!=n&&(window.location=n),!1});
</script>
<form action="insert_article.php" method="get">
<label id="first">title:</label><br/>
<input type="text" name="title"><br/>
<label id="first">link:</label><br/>
<input type="text" name="link"><br/>
<input type="submit" value="submit">
</form>
Thank You.
I think you need to use ajax to send the details to the php to insert it in your database. It's just easier.
var select_language= document.getElementById("select_language").value;
var title= document.getElementById("title").value;
var link= document.getElementById("link").value;
var data= {select_language: select_language,title: title,link:link};
$.ajax({
type: "POST",
url: "insert.php",
data: data,
cache: false,
success: function(html)
{
console.log (html);
alert("Success");
},
error: function (html)
{
console.log (html);
alert("Failure");
}
});
insert.php
include '../dbconfig.php';
$select_language= mysqli_real_escape_string($db,$_POST['select_language']);
$title = mysqli_real_escape_string($db,$_POST['title']);
$link= mysqli_real_escape_string($db,$_POST['link']);
$query = "your insert query";
mysqli_query($db, $query) or die(mysqli_error($db));
Hope this helps.

Update Text Value in PHP form display using jQuery & MySQL database

I have a table display and I want to enable users to edit the values of the table in a live way using jQuery. The table is simple, it just has 1 column with a list of names. I have it all built out but at the moment the table doesn't update the value. All the code is below, I am still learning everything so it's probably not written very well/correctly! Thanks in advance.
Form Display:
<?php
echo "<div class=\"table-responsive\"><table class=\"table table-striped\">";
echo "<thead><tr><th>Employee Name</th><th></th></tr></thead><tbody>";
require_once 'connectionsettings.php'; // Gets connection settings
$sql = "SELECT id, employees FROM Employees ORDER BY employees ASC";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
// what it's saying is that if there's rows do something
while($row = $result->fetch_assoc()) {
// now it's saying get the data and put it in rows
echo "<tr><td data-id='{$row['id']}' contenteditable=\"true\">" . $row["employees"] . "</td><td><span data-id='{$row['id']}' name='remove_{$row['id']}' class='employee glyphicon glyphicon-remove' aria-hidden='true'></span></td></tr>";
}
}else{
echo "No Employees! Let's add some.";
}
$mysqli->close();
echo "</tbody></table></div>";
?>
Jquery Info:
$(function(s){
$("td[contenteditable=true]").blur(function(){
var id = $(this).attr("id") ;
var name = $(this).text() ;
var formURL = "updateemployeename.php";
$.ajax({
url : formURL,
type: "POST",
data : {name: name, id: id},
success:function(data, textStatus, jqXHR)
{
$('#successmessage2').slideDown('fast').delay(1500).slideUp('fast');
$('div#employeedisplay').hide();
$('div#updatedemployeedisplay').load('employeedisplay.php').fadeIn(3000);
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
}
});
});
s.preventDefault(); //STOP default action
});
SQL Info:
<?php
require_once 'connectionsettings.php'; // Gets connection settings
$name = htmlspecialchars(trim($_POST['name']));
$id = htmlspecialchars(trim($_POST['id']));
$sql = "UPDATE Employees SET employees='$name' WHERE id='$id'";
if($mysqli->query($sql) === TRUE) {
echo "status updated successfully";
}else{
echo "Error updating status" . $mysqli->error;
}
$mysqli->close();
?>

Using jQuery and php to pull data from database

I have a page that is pulling data through jQuery but it is only pulling the return code. Here is my code:
<script type='text/javascript' language='javascript'>
function showCU() {
$.post('getCU.php', {
cuid: $('#cuContact').val()
},
function (response) {
$('#contact').val(response).show();
$('#email').val(response).show();
$('#phone').val(response).show();
})
}
</script>
$select = "SELECT priContact, priEmail, priPhone FROM user WHERE id = '" . $_POST['id'] . "'";
$query = mysql_query($select) or die ("Could not get info: " . mysql_error());
if (mysql_num_rows($query) > 0) {
while ($get = mysql_fetch_array($query)) {
$priContact = $get['priContact'];
echo $priContact;
echo $get['priEmail'] . " | " . $get['priPhone'];
}
} else {
echo "No users";
}
So the call is pulling from getCU.php whenever the onchange event handler is called. That is why this is in a function. What I want to do is every time a user chooses something from the option list the text values change according to what was selected. I have the php page pulling from a db and echoing out the code correctly. jQuery id pulling the data from the php page correctly, but I cannot get the code to place the single details in each of the text boxes.
So what I want to happen is this:
A user selects a name from a drop-down box. Then the mysql data attached to that name would be displayed on the page in form text fields.
Let me know if more information or code is needed.
I think you'll be better off structuring your data. My general recommendation is JSON.
// QUICK WARNING: Don't take unparse GET/POST responses.
// This is asking for trouble from SQL injection.
$select = "SELECT priContact, priEmail, priPhone FROM user WHERE id = '" . mysql_escape_string($_POST['id']) . "'";
$query = mysql_query($select) or die ("Could not get info: " . mysql_error());
$retVal = array();
if (mysql_num_rows($query) > 0) {
$retVal['data'] = array();
while ($get = mysql_fetch_array($query))
{
$retVal['data'][] = $get;
}
} else {
$retVal['error'] = 'No users';
}
header('Content-type: application/json');
echo json_encode($retVal);
Javascript:
<script type="text/javascript">
function showCU() {
$.post('getCU.php', {
cuid: $('#cuContact').val(),
dataType:'json'
},
function (response) {
if (response.error) {
//handle error
}
else
{
$('#contact').val(response.data.priContact).show();
$('#email').val(response.data.priEmail).show();
$('#phone').val(response.data.priPhone).show();
}
})
}
</script>

Table doesn't respond to second jQuery request

My PHP script generates a table with rows which can optionally be edited or deleted. There is also a possibility to create a new Row. The PHP is activated through jQuery Events.
Now all works well, I can edit delete and create an Item. After each action which makes use of the PHP script the HTML table gets updated.
But when I try after an Event to do an action again the HTML Table doesn't get updated though in the background the PHP script makes an entry into the database.
Does someone of you know why my HTML Table doesn't update itself when I trigger a second event?
Here is the Script:
PHP
<?php
require_once "../../includes/constants.php";
// Connect to the database as necessary
$dbh = mysql_connect(DB_SERVER,DB_USER,DB_PASSWORD)
or die ("Unaable to connnect to MySQL");
$selected = mysql_select_db(DB_NAME,$dbh)
or die("Could not select printerweb");
$action = $_POST['action'];
$name = $_POST['name'];
$id = $_POST['id'];
if($action == "new")
{
mysql_query("INSERT INTO `place` (`id`, `name`) VALUES (NULL, '$name')");
}
elseif($action == "edit")
{
mysql_query("UPDATE `place` SET `name` = '$name' WHERE `id` = '$id'");
}
elseif($action == "delete")
{
mysql_query("DELETE FROM place WHERE id = '$id'");
}
echo "<table><tbody>";
$result = mysql_query("SELECT * FROM place");
while ($row = mysql_fetch_array($result)) {
echo "<tr><td id=".$row["id"]." class=inputfield_td><input class=inputfield_place type=text value=".$row["name"]." /></td><td class=place_name>".$row["name"]."</td><td class=edit>edit</td><td class=cancel>cancel</td><td class=delete>delete</td><td class=save>SAVE</td></tr> \n";
}
echo "</tbody>";
echo "</table>";
echo "<input type=text class=inputfield_visible />";
echo "<button class=new>Neu</button>";
?>
JS
$(function() {
$.ajax({
url: "place/place_list.php",
cache: false,
success: function (html){
$("#place_container").append(html);
}
});
$(".edit").live("click", function() {
$(this).css("display","none").prevAll(".place_name").css("display","none").prevAll(".inputfield_td").css("display","block").nextAll(".cancel").css("display","block").nextAll(".save").css("display","block").prevAll(".inputfield_td").css("display","block");
});
$(".cancel").live("click", function() {
myvariable5 = $(this).prevAll(".place_name").html();
$(this).css("display","none").prevAll(".edit").css("display","block").prevAll(".place_name").css("display","block").prevAll(".inputfield_td").css("display","none").nextAll(".save").css("display","none").siblings().find("input[type=text]").val(myvariable5);
});
$(".save").live("click", function() {
var myvariable1 = $(this).siblings().find("input[type=text]").val();
var myvariable2 = $(this).prevAll("td:last").attr("id");
$(this).css("display","none").prevAll(".cancel").css("display","none").prevAll(".edit").css("display","block").prevAll(".place_name").css("display","block").prevAll(".inputfield_td").css("display","none");
$.post("place/place_list.php", {action: "edit", name: ""+myvariable1+"", id: ""+myvariable2+""}, function (html){$("#place_container").replaceWith(html);});
});
$(".delete").live("click", function() {
var myvariable3 = $(this).prevAll("td:last").attr("id");
$.post("place/place_list.php", {action: "delete", id: ""+myvariable3+""}, function (html){$("#place_container").replaceWith(html);});
});
$(".new").live("click", function() {
var myvariable4 = $(this).prevAll("input[type=text]").val();
$.post("place/place_list.php", {action: "new", name: ""+myvariable4+""}, function (html){$("#place_container").replaceWith(html);});
});
});
I think I know. You do replaceWith instead of append, so your DIV with ID #place_container disappears after the first operation (you are left with only a table in your page), and of course jQuery does not find it and is unable to refresh it with new content from the second operation.
Just use append or, better yet, html methods.
Shouldnt you replace the complete table ?
$("#place_container").html(html);

Categories