How to store div content to DB with Ajax - javascript

In my project, I want to store div content to DB. The content is like:
<span>name:</span><input type="text" id="inputid" value="John"><br />
So I chose innerHTML to fetch them successfully. And with Ajax, the content would be stored to DB.
Yesterday, I found that stripslashes() should be called to format the content, and it could be updated successfully.
But today stripslashes() made nothing done. Here is my js code:
var slcId = $('#slcStNum').val();
var tmTgDvHtml=document.getElementById("timeTagDiv").innerHTML;
$.ajax({
dataType:'html',
type:"POST",
url:"get_ajax_csc_div.php",
data:{htmlCnt:tmTgDvHtml,slcId:slcId},
success:function (data)
{
alert("test");
}
});
Here is html code:
<div id="timeTagDiv"><span>name:</span><input type="text" id="inputid" value="John"><br /></div>
Here is get_ajax_csc_div.php code
<?php
if(isset($_POST['htmlCnt']))
{
include("DB.php");
$htcnt=stripslashes(".$_POST['htmlCnt'].");
$sql="update IDC SET stprocess='$htcnt' where id='".$_POST['slcId']."';";
$sel = $conn->exec($sql);
}
?>
I changed dataType:'html' to dataType:'json', but it failed again. Who can help me?

It's because you have your _POST[] superglobal surrounded by quotes, making it a string.
Change this
$htcnt = stripslashes(".$_POST['htmlCnt'].");
With this
$htcnt = stripslashes($_POST['htmlCnt']);

change your get_ajax_csc_div.php to
include("DB.php");
if(isset($_POST['htmlCnt'])) {
$htcnt = stripslashes($_POST['htmlCnt']);
$sql = "update IDC SET stprocess='$htcnt' where id='".$_POST['slcId']."'";
$sel = $conn->exec($sql);
}

Related

PHP : How to get value from DB to already created textbox

Background
I am a complete beginner to web designing and i am using PHP and mySQL.
Code in hand
This is my HTML file named UserRegistration.php
<?php
session_start();
?>
<html>
<body>
<script>
function FillRecord(Id)
{
$.ajax({
type: "POST",
url: "Algorithm/UserRegistration-FillUserRecords.php",
data:'Id='+Id,
success: function(data)
{
document.forms["Frm_User"].elements["txtName"].value = "";
document.forms["Frm_User"].elements["txtFName"].value = "";
document.forms["Frm_User"].elements["txtMName"].value = "";
}
});
}
</script>
<form id="Frm_User" name="Frm_User" method="POST" action="Algorithm/UserRegistration-SaveDetails.php">
<label for="txtName">Name</label>
<input type="text" name="txtName" placeholder="Name" required>
<label for="txtFName">Father Name</label>
<input type="text" name="txtFName" placeholder="Father Name" required>
<label for="txtMName">Mother Name</label>
<input type="text" name="txtMName" placeholder="Mother Name" required>
</form>
<input type="button" onclick="FillRecord(1);">//1 is fixed at the moment
</body>
</html>
This is my PHP class named UserRegistration-FillUserRecords.php
<?php
session_start();
include_once 'Connection.php';
if ($dbcon->connect_error)
{
die("Connection failed: " . $dbcon->connect_error);
header('Location: ../UserRegistration.php');
exit();
}
//Search data from database on all fields except "SNo"
//----------------------------------------------------------------------------
$sql = "Select * from usertable where id=".$_POST["Id"];
$result = $dbcon->query($sql);
$rows = array();
foreach ($result as $RowRecord)
{
$_SESSION['UserRegistration_txtName'] = $RowRecord["Name"];
$_SESSION['UserRegistration_txtFName'] = $RowRecord["FName"];
$_SESSION['UserRegistration_txtMName'] = $RowRecord["MName"];
}
exit();
?>
The Algorithm/UserRegistration-SaveDetails.php is used to save the user details into database which is working perfectly.
Problem
I want to show the data which is being retrieved by UserRegistration-FillUserRecords.php into UserRegistration.php's already created textbox when the function FillRecord is called but i have no clue as to how to assign the session variable value to my input boxes.
I Tried
1) alert(<?php echo $_SESSION['UserRegistration_txtName']; ?>);
but the statement doesn't seem to work even when i have used
2) success: function(data) in AJAX reponse has the value which i need but when i echo it, it shows the value in continuation like:-
abc
----------------
a (Name)
b (Father Name)
c (Mother Name)
and i cant seperate it as the string can be anything, it can be full of comma's, new line characters and any special symbols
Your PHP code doesn't actually output those session variables you've created to the browser. To do that, you need something like this (I'm using JSON as the format in which to send the data, as it's easiest to work with on the receiving end).
foreach ($result as $RowRecord)
{
$_SESSION['UserRegistration_txtName'] = $RowRecord["Name"];
$_SESSION['UserRegistration_txtFName'] = $RowRecord["FName"];
$_SESSION['UserRegistration_txtMName'] = $RowRecord["MName"];
}
// Create an array to send the data
$data = [
'Name' => $_SESSION['UserRegistration_txtName'],
'FName' => $_SESSION['UserRegistration_txtFName'],
'MName' => $_SESSION['UserRegistration_txtMName']
];
// Tell the browser that a JSON data file is coming
header('Content-type: application/json');
print json_encode($data);
exit();
Your jQuery AJAX handler function can then easily populate the form with these values:
function FillRecord(Id)
{
$.ajax({
type: "POST",
url: "Algorithm/UserRegistration-FillUserRecords.php",
data:'Id='+Id,
dataType: "json", //Add this so data comes back as an Object
success: function(data)
{
document.forms["Frm_User"].elements["txtName"].value = data.Name;
document.forms["Frm_User"].elements["txtFName"].value = data.FName;
document.forms["Frm_User"].elements["txtMName"].value = data.MName;
}
});
}
I hope I've correctly understood (and satisfied) what you want to achieve, please feel free to say if not.

Trouble inserting data with PHP and Jquery

I have been at this for few hours now and need some help. I am a little new to jquery - it seems straightforward enough, but I can't get this to work. If I submit the data through a form straight to the php page, it works perfectly, but I can't get the ajax to execute. It is pretty simple with just one variable to send for marking an item for review. Any help is appreciated.
<input type="hidden" id="flag_item" name="flag_item" value="<?php echo $row[0]; ?>" />
<input type="button" class="grn_button2" id="report_btn" name="report_btn" onclick="MM_changeProp('flag1','','display','none','SPAN'), MM_changeProp('flag2','','display','inline','SPAN')" value=" Report Item "/>
the jquery code
<script src="js/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(document).on('click','#report_btn',function(e) {
var data = $("#flag_item").val();
$.ajax({
data: data,
type: "POST",
url: "flag.php",
success: function(data) {
alert("Item has been reported");
}
});
});
});
</script>
and the php
$flag_item = mysqli_real_escape_string($dbgo, $_POST["flag_item"]);
$query = "SELECT flag FROM listings WHERE item_num = '$flag_item'";
$result = mysqli_query($dbconnect, $query);
if(!$result){
die('Invalid query: ' . mysql_error());
}
$row = mysqli_fetch_row($result);
$new_row = $row[0] + 1;
You missed param name here:
var data = $("#flag_item").val();
Try this:
var data = {"flag_item":$("#flag_item").val()};
I got it working now. I ditched the jquery I was using and started over. This jquery code is working.
$('#flag_form').submit(function(){
return false;
});
$('#flag_form').click(function(){
$.post(
$('#flag_form').attr('action'),
$('#flag_form :input').serializeArray(),
function(result){
alert("Item has been reported");
}
);
});
I also added the form tag and the action to input fields. Thank you for trying to help, I appreciate it.

working with ajax, mysql and php

I have to transfer data from one div to another, I am using AJAX to do this.
<script type="text/javascript" src="lib/jquery-1.6.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#aq").click(function(){
var name1 = $("#n1").val();
$.ajax({
type: "POST",
url: "risultato.php"
data: "name1=" + name1 ,
dataType: "html",
success: function(msg)
{
$("#risultato1").html(msg);
},
error: function()
{
alert("Chiamata fallita, si prega di riprovare...");
}
});
});
});
</script>';
<form name="modulo1'.$dationennx['id'].'">
<input type="hidden" name="name1" value="'.$dati['id'].'"
id="n1'.$dationennx['id'].'">
<a href="javascript:rispondithread(\'homeq\');"
id="aq">'.stripslashes($dationennx['oggetto']).'</a><br>
</form>
<script>
function rispondithread(h) {
$("#rispondithreadforum").attr("style", "display:block;");
}
</script>`
I am fetching the data from my table from the 'risultato.php' page, which i want to use to show a textarea on my main page with the fetched data.
<?php
$nome = $_POST['name1'];
$query = "SELECT * FROM login2.podcast
WHERE login2.podcast.id = '$nome'
ORDER BY login2.podcast.data DESC";
$dati = mysql_query($query);
while($ris = mysql_fetch_array($dati) ){
echo'
<textarea class="form-control textareaabc" readonly tabindex="8">'.stripslashes($ris['testo']).'</textarea>';
}
?>
It doesn't work if i try to fetch the data using mysql_query, but it does when i try echoing the post data in the page.
$nome = $_POST['name1'];
echo $nome
This writes the '$nome' variable in my main page.
$nome = $_POST['name1'];
echo'<input type="text" value="'.$nome.'" name="nome">';
i don't understand this. why it doesn't work? what's wrong?
It is highly likely that there is no data for the '$nome' variable in your table
Make sure that you are actually receiving data from the database, does it print out the textarea? If not, you do not have any id in your podcast table table matching the '$nome' variable.
Testing your code
Try checking if you actually get anything back when you print something out in that page, could you possibly be pointing to the wrong page?
other
Overall, i would recommend using PDO or atleast mysqli, MySQL is no longer supported since PHP 7 and deprecated since PHP 5. See: PHP.net documentation about mysql extension
sorry, i forget to include the connection to the database into the file risultato.php :P
thanks to everybody

asynchronous commenting using ajax

I'm trying to create a comment system on my website where the user can comment & see it appear on the page without reloading the page, kind of like how you post a comment on facebook and see it appear right away. I'm having trouble with this however as my implementation shows the comment the user inputs, but then erases the previous comments that were already on the page (as any comments section, I'd want the user to comment and simply add on to the previous comments). Also, when the user comments, the page reloads, and displays the comment in the text box, rather than below the text box where the comments are supposed to be displayed. I've attached the code. Index.php runs the ajax script to perform the asynchronous commenting, and uses the form to get the user input which is dealt with in insert.php. It also prints out the comments stored in a database.
index.php
<script>
$(function() {
$('#submitButton').click(function(event) {
event.preventDefault();
$.ajax({
type: "GET",
url: "insert.php",
data : { field1_name : $('#userInput').val() },
beforeSend: function(){
}
, complete: function(){
}
, success: function(html){
$("#comment_part").html(html);
window.location.reload();
}
});
});
});
</script>
<form id="comment_form" action="insert.php" method="GET">
Comments:
<input type="text" class="text_cmt" name="field1_name" id="userInput"/>
<input type="submit" name="submit" value="submit" id = "submitButton"/>
<input type='hidden' name='parent_id' id='parent_id' value='0'/>
</form>
<div id='comment_part'>
<?php
$link = mysqli_connect('localhost', 'x', '', 'comment_schema');
$query="SELECT COMMENTS FROM csAirComment";
$results = mysqli_query($link,$query);
while ($row = mysqli_fetch_assoc($results)) {
echo '<div class="comment" >';
$output= $row["COMMENTS"];
//protects against cross site scripting
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8');
echo '</div>';
}
?>
</div>
insert.php
$userInput= $_GET["field1_name"];
if(!empty($userInput)) {
$field1_name = mysqli_real_escape_string($link, $userInput);
$field1_name_array = explode(" ",$field1_name);
foreach($field1_name_array as $element){
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0){
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element= $goodWord;
}
$newComment = $newComment." ".$element;
}
//Escape user inputs for security
$sql = "INSERT INTO csAirComment (COMMENTS) VALUES ('$newComment')";
$result = mysqli_query($link, $sql);
//attempt insert query execution
//header("Location:csair.php");
die();
mysqli_close($link);
}
else{
die('comment is not set or not containing valid value');
}
The insert.php takes in the user input and then inserts it into the database (by first filtering and checking for bad words). Just not sure where I'm going wrong, been stuck on it for a while. Any help would be appreciated.
There are 3 main problems in your code:
You are not returning anything from insert.php via ajax.
You don't need to replace the whole comment_part, just add the new comment to it.
Why are you reloading the page? I thought that the whole purpose of using Ajax was to have a dynamic content.
In your ajax:
$.ajax({
type: "GET",
url: "insert.php",
data : { field1_name : $('#userInput').val() },
beforeSend: function(){
}
, complete: function(){
}
, success: function(html){
//this will add the new comment to the `comment_part` div
$("#comment_part").append(html);
}
});
Within insert.php you need to return the new comment html:
$userInput= $_GET["field1_name"];
if(!empty($userInput)) {
$field1_name = mysqli_real_escape_string($link, $userInput);
$field1_name_array = explode(" ",$field1_name);
foreach($field1_name_array as $element){
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0){
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element= $goodWord;
}
$newComment = $newComment." ".$element;
}
//Escape user inputs for security
$sql = "INSERT INTO csAirComment (COMMENTS) VALUES ('$newComment')";
$result = mysqli_query($link, $sql);
//attempt insert query execution
mysqli_close($link);
//here you need to build your new comment html and return it
return "<div class='comment'>...the new comment html...</div>";
}
else{
die('comment is not set or not containing valid value');
}
Please note that you currently don't have any error handling, so when you return die('comment is not set....') it will be displayed as well as a new comment.
You can return a better structured response using json_encode() but that is outside the scope of this question.
You're using jQuery.html() which is replacing everything in your element with your "html" contents. Try using jQuery.append() instead.

Getting a variable from my form to my parser file via ajax

I'm a total AJAX noob, so please forgive me, but this is what I'm trying to do...
I have a php form that submits the information via ajax to a parser file. I need to get a few ids from that form to the parser file so I can use them in my sql update. I'll try to keep my code simple but give enough info so someone can answer.
My form is being generated via a foreach loop that iterates through a list of teams and grabs their various characteristics. For simplicity, let's say the main thing I need to get to the parser file is that team_id.
I'm not sure if I need to add
<input type="hidden" name="team_id" value="<?=$team->id ?>">
or
<tr data-teamid="<?=$team->id; ?>">
or something like that to my form....but either way, it gets passed through this AJAX file...
<script type="text/javascript">
function updateNames() {
jQuery('#form-message, #form-errors').html("");
var post_data = jQuery('form[name="update_names"]').serialize();
$.ajax({
url: 'parsers/update_names.php',
method: 'POST',
data : post_data,
success: function(resp) {
if(resp == 'success'){
jQuery('#form-message').html("Names and Scores have been Updated!");
}else{
jQuery('#form-errors').html(resp);
}
}
});
return false; // <--- important, prevents the link's href (hash in this example) from executing.
}
jQuery(document).ready(function() {
$(".linkToClick").click(updateNames);
});
</script>
And is making it to my parser file, which looks like this...
require_once '../core/init.php';
$db = DB::getInstance();
$errors = [];
// $camp_id = Input::get('camp_id');
$camp_id = 18;
//Find the Teams that Belong to the Camp
$sql = "SELECT * FROM teams WHERE camp_id = $camp_id";
$teamsQ = $db->query($sql);
$all_teams = $teamsQ->results();
//validation and sanitization removed for simplicity.
if(empty($errors)){
$fields = [];
foreach($_POST as $k => $v){
if($k != 'camp_id'){
$fields[$k] = Input::get($k);
}
}
$db->update('teams',$all_teams->id,$fields);
echo 'success';
}else{
echo display_errors($errors);
}
SO. The main question I have is how do I get that camp_id and team_id into the parser file so I can use them to update my database?
A secondary question is this...is the fact that the form is being generated by a foreach loop going to make it difficult for the ajax to know which field to update?
So, how would I get that camp_id to
$sql = "SELECT * FROM teams WHERE camp_id = $camp_id";
And the team_id to
$db->update('teams',$all_teams->id,$fields);
I tried to break this down to the simplest form and it's still not getting to the function. This code...
<form name="update_names" method="post">
<input type="hidden" name="team_id" value="<?=$teams->id ?>">
<button onclick="updateNames();return false;" class="btn btn-large btn-primary pull-right">test</button>
<script type="text/javascript">
function updateNames() {
alert('test');
}
</script>
Gives me... Uncaught ReferenceError: updateNames is not defined
The jQuery .serialize() method uses the name attribute of an element to assign a variable name. It ignores the element's id, any classes and any other attribute. So, this is the correct format if using .serialize():
<input type="hidden" name="team_id" value="<?=$team->id ?>">
Looking at your ajax code, your parser file would be called parsers/update_names.php.
To verify that the desired field is getting to your parser file, add this to the top for a temporary test:
<?php
$tid = $_POST['team_id'];
echo 'Returning: ' .$tid;
die();
and temporarily modify the ajax code block to:
$.ajax({
url: 'parsers/update_names.php',
method: 'POST',
data : post_data,
success: function(resp) {
alert(resp);
{
});
return false;
If the ajax processor file (your "parser") receives the team_id data, then you will get that data returned to you in an alert box.
Thus, you can now determine:
1. That you are receiving the team_id information;
2. That the ajax back-and-forth communications are working
Note that you also can install FirePHP and echo text to the browser's console from the php processor file.

Categories