JSon array increment my id value from $_POST['id'] - javascript

In my php script, I have managed to get all the data from a form into a json database, however everytime I submit my form, the id value is always == 1. How would I be able to change this, and add more values to my id value, like value++? How would I be able to do that?
<?php
$message = '';
$error = '';
if(isset($_POST["submit"]))
{
if(empty($_POST["title"]))
{
$error = "<label class='text-danger'>Enter title</label>";
echo $error;
}
else if(empty($_POST["decs"]))
{
$error = "<label class='text-danger'>Enter Gender</label>";
echo $error;
}
else if(empty($_POST["cont"]))
{
$error = "<label class='text-danger'>Enter Designation</label>";
echo $error;
}
else
{
if(file_exists('postbl.json'))
{
$current_data = file_get_contents('postbl.json');
$array_data = json_decode($current_data, true);
$extra = array(
'id' => $_POST['id'],
'title' => $_POST['title'],
'decs' => $_POST["decs"],
'cont' => $_POST["cont"]
);
$array_data[] = $extra;
$final_data = json_encode($array_data);
if(file_put_contents('postbl.json', $final_data))
{
$message = "<label class='text-success'>File Appended Success fully</p>";
echo $message;
}
}
else
{
$error = 'JSON File not exits';
}
}
}
?>
my form is like this
<?php session_start();
if(!isset($_SESSION['loggedin'])) header("Location: session.php");
if($_SESSION['loggedin']===FALSE) header("Location: session.php");
?>
<!DOCTYPE html>
<html><head><title>Secret Area</title></head>
<body>
<form action="/admin/form_process.php" method="POST">
<br />
<input type="hidden" name="id" value="1" />
<label>Title</label>
<input type="text" name="title" class="form-control" /><br />
<label>Description</label>
<input type="text" name="decs" class="form-control" /><br />
<label>Content</label>
<input type="text" name="cont" class="form-control" /><br />
<input type="submit" name="submit" value="Append" class="btn btn-info" /><br />
<?php
if(isset($message))
{
echo $message;
}
?>
</form>
<form action="logout.php" method="POST">
<input type="submit" name="logout" value="Log out">
</form>
<p>© 2017 Blog Message</p>
</body>
</html>

Your problem is here
<input type="hidden" name="id" value="1" />
Notice how the 1 is set as value.
Change the 1 with a variable. Something like
<input type="hidden" name="id" value="<?= $id ?>" />

Related

div #id in foreach loop only selects last variable when trying to show/hide in function

I am navigating through a simple foreach loop to get "blog posts". It shows basic blog information, a reply and delete button. When I select the 'reply' button, a small form beneath the reply button appears to fill out. The problem is, the function I am passing the variable to, only gets the last id for the form. How do I change my function or div element to be unique for each instance?
I have tried setting up PHP #echo variable's on the "id" and function, I have checked all my opening and closing brackets 10-fold. I have tried using different GetElementBy ... methods. I started looking into Jquery but I wanted to get this finished with PHP/Javascript only.
<?php foreach ($mainentries as $entry) :
$subentryID = $entry['SubEntryID'];
if ($subentryID == "0")
{ ?>
<div><tr><td><?php echo ('#'.$entry['EntryID'].' - ')?></td>
<td><?php echo $entry['Body']; ?></td>
<br />
<?php foreach($subentries as $subentry) : ?>
<?php if ($subentry['SubEntryID'] == $entry['EntryID'])
{ ?>
<div id="subposts">
<td><td><td>#<?php echo $subentry['EntryID'];?></td><br>
<td>
<?php echo $subentry['Body']; ?>
</td></td></td>
</div>
<?php } endforeach; ?>
<br />
<td>
<button onclick="cookiechecksub()">Reply</button>
<?php echo $entry['EntryID'];
$subform = $entry['EntryID']; ?>
<div id="<?php echo $subform?>" style="display:none">
<form action="Add_subentry.php" method="post" id="Add_subentry">
<label>Title:</label><br />
<input type = "text" name="Title" class="Title"/> <br />
<label>Body</label><br />
<div class="area">
<input type = "textarea" name="Body" class="Body"/><br />
</div>
<input type="hidden" readonly="true" name="EntryID" value="<?php echo $entry['EntryID']; ?>" />
<input type=submit id="btnReply" value="Submit Reply"/>
</form>
</div></td>
<td>
<form action="Delete_entry.php" method="post" id="Delete_entry">
<input type="hidden" readonly="true" name="EntryID" value="<?php echo $entry['EntryID']; ?>" />
<?php if ($userid == 1)
{ ?>
<input type="submit" id="btnDelete" value="Delete Post"/>
<?php } ?>
<br /><br />
</form>
</td>
</tr>
</div>
<?php
} endforeach; ?>
<Script>
function cookiechecksub() {
if (!userid) {
if (confirm("Please log in first")) {
window.location.replace("http://localhost/alexdes/login-logout.php");
}
}
else {
TryAddSubPost();
}
}
function TryAddSubPost()
{
var x = document.getElementById("<?php echo $subform?>");
if (x.style.display === "none")
{
x.style.display="block";
}
else
{
x.style.display="none";
}
}
</Script>
this is because you used php echo in the js function especially in TryAddSubPost
change it to be like this:
<script>
function cookiechecksub(id) {
if (!userid) {
if (confirm("Please log in first")) {
window.location.replace("http://localhost/alexdes/login-logout.php");
}
}
else {
TryAddSubPost(id);
}
}
function TryAddSubPost(id)
{
var x = document.getElementById(id);
if (x.style.display === "none")
{
x.style.display="block";
}
else
{
x.style.display="none";
}
}
</script>
and use the id from php only when calling the function, like this:
<button onclick="cookiechecksub('<?php echo $entry['EntryID']?>')">Reply</button>
Give cookiechecksub an argument, and pass it to TryAddSubPost
<button onclick="cookiechecksub('<?=$entry['EntryID']?>')">

Form insertion into database not working asynchronously

I'm trying to get a text area's value inserted asynchrnously into my database, however it keeps redirecting to the PHP processing page, and echoing a result there. How would I get it to echo the result of the PHP script on the current HTML page?
JS:
$("#sub").click(function() {
$.post( $("#text").attr("action"), $("#text :input").serializeArray(),
function(info) { $("#result").html(info);});
});
$("#text").submit( function(){
return false;
})
PHP:
$sql = "UPDATE text
SET text_content = ? WHERE (id = 40) AND (number = $Number);";
$stmt = mysqli_stmt_init($connection);
if (!mysqli_stmt_prepare($stmt, $sql))
{
header("Location: ../create_text.php?error&prepare1111");
exit();
}
else
{
$stmt->bind_param("s", $content);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
$connection->close();
echo "successfully saved";
}
HTML:
<form type="text" method="post" onSubmit="return validateText(); toHTML();" action="processing.php" id="text">
<textarea name="content" rows="45" id="auto-expand" class="text-box" type="text"><?php echo stripslashes($content) ?></textarea>
<input type="hidden" name="id" id="id" value="<?php echo $id ?>">
<input type="hidden" name="number" id="number" value="<?php echo $number ?>">
<input type="hidden" name="updated" value="<?php echo $updated ?>">
<button type="submit" id="sub" name="submit">Save</button>
<button type="button" onClick="validateText(); toHTML();">Check</button>
<span id="result"></span>
</form>
Any help would be so great! :)
Try preventDefault:
$("#text").submit( function(e){
e.preventDefault();
})

Using a name selector instead of an id

How can I change the following code to work off of a name selector instead of the id?
<div id="light" class="change_group_popup">
<a class="close" href="javascript:void(0)">Close</a>
JavaScript
$('.change_group').on('click',function(){
$("#light,.white_overlay").fadeIn("slow");
});
$('.close').on('click',function(){
$("#light,.white_overlay").fadeOut("slow");
});
UPDATE:
I added more of my code to show the loop to help explain what I am doing in more detail.
$runUsers2 = mysqli_query($con,"SELECT * FROM users ORDER BY id DESC");
$numrows2 = mysqli_num_rows($run2);
if( $numrows2 ) {
while($row2 = mysqli_fetch_assoc($run2)){
if($row2['status'] == "Approved"){
//var_dump ($row2);
$approved_id = $row2['user_id'];
$approved_firstname = $row2['firstname'];
$approved_lastname = $row2['lastname'];
$approved_username = $row2['username'];
$approved_email = $row2['email'];
if ($approved_firstname == true) {
echo "Name - ". $approved_firstname . " " . $approved_lastname . "</br>" .
"Username - ". $approved_username . "</br></br>"
?>
<div class="change_group_button">
<a class="change_group" href="javascript:void(0)">Change User Permission</a>
</div><br>
<div class="change_group_popup light">
<a class="close" href="javascript:void(0)">Close</a>
<div class="group_success" style="color: red;"></div><br>
<form class="update_group" action="" method="POST">
<div class="field">
<label for="group">Group</label>
<input type="hidden" value="<?php echo $approved_id; ?>" name="approved_id" />
<input type="hidden" value="<?php echo $approved_firstname; ?>" name="approved_firstname" />
<input type="hidden" value="<?php echo $approved_lastname; ?>" name="approved_lastname" />
<input type="hidden" value="<?php echo $approved_username; ?>" name="approved_username" />
<input type="hidden" value="<?php echo $approved_email; ?>" name="approved_email" />
<select name='group_id' required>
You can get any element by name attribute by:
$('[name="someName"]')
Use DOM traversal functions to find the related element.
$(".change_group").click(function() {
var light = $(this).closest(".change_group_button").nextAll(".light").first(); // Find the next .light DIV after the button
light.add($(".white_overlay")).fadeIn("slow");
}):

SESSION variable slow to update textfield in php

I have a form, contained 3 fields, which when the submit button in submitted,
it will changes the session variable values according to the fields, in this case there are 3 variables. then i echo back the variable onto the fields.
For the first time submit, it stores the value beautifully and display in the fields correctly, the problem is that, when i submit the second time, the values are still the same. after i refresh the page, then the values in the fields are changed.
this is partially the codes i'm using now.
<?php
session_start();?>
?>
<form name="form1" id="form1" action="">
<input type="text" name="acc1" value="<?php echo $_SESSION['acc_main']" />
<input type="text" name="acc2" value="<?php echo $_SESSION['acc_id']" />
<input type="text" name="acc3" value="<?php echo $_SESSION['acc_cat']" />
<input type="submit" name="submit">
</form>
<?php
if(isset($_POST['submit']) != '')
{
$_SESSION['acc_main'] = $_POST['acc1'];
$_SESSION['acc_id'] = $_POST['acc2'];
$_SESSION['acc_cat'] = $_POST['acc3'];
}
?>
After i refresh(F5), then the value changed. i want it to be, when i clicked the submit button, it will change to the new value.
PHP Code:
<?php
if(isset($_POST['submit']) != '')
{
$_SESSION['acc_main'] = $_POST['acc1'];
$_SESSION['acc_id'] = $_POST['acc2'];
$_SESSION['acc_cat'] = $_POST['acc3'];
echo '<script type="text/javascript">'
, 'jsfunctionToPrintUpdatedValues();'
, '</script>'
;
}
?>
Javascript Sample Code
function jsfunctionToPrintUpdatedValues()
{
/* retrieve the updated session variables in javascript variables */
var acc_main_js = <?php echo $_SESSION['acc_main']?>
var acc_id_js = <?php echo $_SESSION['acc_id']?>
var acc_cat_js = <?php echo $_SESSION['acc_cat']?>
document.getElementById("main").value=acc_main_js;
document.getElementById("id").value=acc_main_js;
document.getElementById("cat").value=acc_main_js;
}
in the input fields you have to write like this
`
Below
`
<input type="text" name="acc1" value="<?php if(isset($_SESSION['acc_main'])) echo $_SESSION['acc_main']" />
Use if(isset($_POST['submit']) != '') before the form. Change your code to this:
<?php
session_start();
if(isset($_POST['submit']) != '')
{
$_SESSION['acc_main'] = $_POST['acc1'];
$_SESSION['acc_id'] = $_POST['acc2'];
$_SESSION['acc_cat'] = $_POST['acc3'];
?>
<form name="form1" id="form1" action="">
<input type="text" name="acc1" value="<?php echo $_SESSION['acc_main']" />
<input type="text" name="acc2" value="<?php echo $_SESSION['acc_id']" />
<input type="text" name="acc3" value="<?php echo $_SESSION['acc_cat']" />
<input type="submit" name="submit">
</form>
<?php
}else{
?>
<form name="form1" id="form1" action="">
<input type="text" name="acc1" value="<?php echo $_SESSION['acc_main']" />
<input type="text" name="acc2" value="<?php echo $_SESSION['acc_id']" />
<input type="text" name="acc3" value="<?php echo $_SESSION['acc_cat']" />
<input type="submit" name="submit">
<?php } ?>

ajax comment form not posting data to mysql

I am using ajax to post a comment to a mysql table. When I post the comment, the javascript is loading but it doesnt submit the data to the mysql database.
$(document).ready(function(){
$('#commentform').on('submit',function(e) {
$.ajax({
url:'ajax.php',
data:$(this).serialize(),
type:'POST',
success:function(data){
console.log(data);
$("#success").show().fadeOut(5000);
},
error:function(data){
$("#error").show().fadeOut(5000);
}
});
e.preventDefault();
});
});
ajax.php
$id = $_POST['id'];
$comment = $_POST['comment'];
$username = $_POST['username'];
$array = $pdo->prepare("INSERT INTO `comments` (id, comment, user)
VALUES (:id,:comment,:username);");
$array->execute(array(':id' => $id, ':comment' => $comment, ':username' => $username));
html
<form method="post" name="commentform" id="commentform">
<textarea name="comment" name="comment"></textarea><br>
<input type="hidden" value="<?php echo "$id"; ?>" name="id" id="id" />
<input type="hidden" value="<?php echo "$username"; ?>" name="username" id="username" />
<input type="submit" name="submit" id="submit" value="REPLY" />
</form>
You have issue in html form, you have used multiple " around php variables which causes to break the value attribute, use updated html
HTML
<form method="post" name="commentform" id="commentform">
<textarea name="comment" name="comment">test comment</textarea><br>
<input type="hidden" value="<?php echo $id; ?>" name="id" id="id" />
<input type="hidden" value="<?php echo $username; ?>" name="username" id="username" />
<input type="submit" name="submit" id="submit" value="REPLY" />
</form>
Ajax script is fine
here is fiddle which is making ajax request fine
ajax.php looks fine as well
$id = $_POST['id'];
$comment = $_POST['comment'];
$username = $_POST['username'];
$array = $pdo->prepare("INSERT INTO `comments`
(id, comment, user)
VALUES
(:id, :comment, :username)"
);
$array->execute(array(
':id' => $id,
':comment' => $comment,
':username' => $username));

Categories

Resources