ajax comment form not posting data to mysql - javascript

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));

Related

Use get url parameter in sql sent with ajax

I can successfully send post data with ajax and get data into mysql database. However I can't display when I use POST parameter in sql statement. İf I remove POST parameter from sql, data perfectly display where it should be.
What am I missing? Here what I've got.. thanks
**index.php**
<form method="POST" id="ask1">
<div class="form-group">
<input type="text" name="name" />
</div>
<div class="form-group" >
<textarea name="content" ></textarea>
</div>
<div class="form-group" >
<input type="hidden" name="service" value ="<?php echo ''.htmlentities($_GET["service"]).'' ?> ">
<input type="submit" name="submit" value="Submit" />
</div>
</form>
<div><span id="message" ></span></div>
<div id="display_message" ></div>
**ask.php**
$service = $_POST['service'];
$query = "SELECT * FROM ask WHERE comment_id = '0' and
service='".mysqli_real_escape_string($conn,$service)."' ";
$statement = $conn->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = '';
foreach($result as $row)
{
$output .= '
<div class="panel-body" style="font-size:12px;">"'.$row["name"].'"</div>
';
$output .= get_reply_comment($conn, $row["id"]);
}
echo $output;
Ajax
<script>
load_comment();
function load_comment()
{
$.ajax({
url:"ask.php",
method:"POST",
success:function(data)
{
$('#display_message').html(data);
}
})
}
</script>

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();
})

can we send the id to the file itself with submit form

I tried to post id to file itself in php. But it post nothing. This code I tried
//if can it should echo 1 and point 232
<?php
if ($_POST['submit'] == 'winners') {
$a = $_GET['A'];
echo $a;
$point = $_GET['POIN'];
echo $point;
}
?>
<form enctype="multipart/form-data" method="post" style="width:auto;">
<div class="box">
<span class='odometer' id="timespan" name="timespan">232</span>
</div>
<input class="process" name="submit" type="submit" id="submit" value="winners" onclick="location.href='reward-pollingx.php?A=1&POIN='+document.getElementById('timespan').innerHTML'">
</form>
You want to GET value inside span in PHP using JavaScript. Try something like this:
<?php
$a = isset( $_GET['A'] ) ? $_GET['A'] : '';
echo $a;
$point = isset( $_GET['POIN'] ) ? $_GET['POIN'] : '';
echo $point;
?>
<form enctype="multipart/form-data" method="post" style="width:auto;">
<div class="box">
<span class='odometer' id="timespan" name="timespan">232</span>
</div>
<input
class="process"
name="submit"
type="submit"
id="submit"
value="winners"
onclick="window.location='reward-pollingx.php?A=1&POIN='+document.getElementById('timespan').innerHTML;return false;"
>
</form>
If you try to pass parameters like a query string you do not need to use a form.
Because you configure your form to send a post request, you can pass the parameters of the query string to input values of hidden type. Test as follows
<form action="reward-pollingx.php" enctype="multipart/form-data" method="post" style="width:auto;">
<input type="hidden" name="A" value="1">
<input type="hidden" name="POIN" value="">
<input type="hidden" name="submit" value="winners">
<div class="box">
<span class='odometer' id="timespan" name="timespan">232</span>
</div>
<input class="process" name="submit" type="submit" id="submit" value="winners">
</form>
<script>
document.querySelector('input[name=POIN]').value = document.getElementById('timespan').innerHTML;
</script>
Your php code should change to use $_POST instead of $_GET
<?php
if ($_POST['submit'] === 'winners') {
$a = $_POST['A'];
echo $a;
$point = $_POST['POIN'];
echo $point;
}
Or use query string to pass parameters to the PHP script
Submit
And the php
if ($_GET['submit'] === 'winners') {
$a = $_GET['A'];
echo $a;
$point = $_GET['POIN'];
echo $point;
}
To build the query string because you need to get information from the view you probably need to build it dynamically
If you need to submit the form to itself, you can use
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" ....
or you can use:
<form action="<?php echo $_SERVER['REQUEST_URI']; ?>" method="POST" ....

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

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 ?>" />

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 } ?>

Categories

Resources