Edit button inside table row only works in consecutive order - javascript

I am using php and javascript in order to display data from mysql in a table where each row must have an update button.
It seems to be working fine but i'm getting a weird behavior: it works when i click the buttons in consecutive order (#1 then #2 then #3..) but when i click them randomly (starting with #2 or #3...) it does nothing, just reloads the page.
Can you help me find what am i doing wrong, here's my code so far...
Thanks!
list.php:
<?php
$q= "SELECT * FROM list WHERE id = $f ORDER BY id";
if ($query = mysqli_query($db_con, $q)) {
$y=1;
echo '<table>'.
'<tr>'.
'<th>#</th>'.
'<th>Name</th>'.
'<th>Edit</th>'.
'</tr>';
while ($reg= mysqli_fetch_row($query)){
echo '<tr>';
echo '<td>'.$y.'</td>';
echo '<td>'.$reg[0].'</td>';
echo '<td>
<form id="frm_data'.$y.'" method="post">
<input type="hidden" id="name" name="name" value="'.$reg[0].'" />
<input type="hidden" id="f" name="f" value="'.$f.'" />
<input type="hidden" id="a" name="a" value="'.$a.'" />
<input id="FormSubmit" type="submit" value="EDIT">
</form>
</td></tr>';
$y = $y +1;
}
echo '</table>';
}
?>
validate.js
$(document).ready(function() {
$("#FormSubmit").click(function (e) {
e.preventDefault();
$("#FormSubmit").hide();
var myData = {
name: $("#name").val(),
a: $("#a").val(),
f: $("#f").val()
};
jQuery.ajax({
type: "POST", // HTTP method POST or GET
url: "update.php", //Where to make Ajax calls
dataType:"json", // Data type, HTML, json etc.
data:myData, //Form variables
success : function(data) {
if(data.status == 'success'){
alert("OK!");
} else if(data.status == 'error') {
alert("ERROR!");
}
},
error : function (xhr, ajaxOptions, thrownError){
alert(thrownError);
}
});
});
});
update.php
<?php
$f = $_POST["f"];
$name = $_POST["name"];
$q = "UPDATE list SET edited = '1' WHERE id = '$f' AND name = '$name' ";
$update_row = mysqli_query($db_con, $q);
if (!$update_row) {
$response_array['status'] = 'error';
} else {
$response_array['status'] = 'success';
}
?>

Related

Form is not displaying errors if ajax is used

I'm checking this form for errors using PHP code which is on the same index.php file:
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST">
<?php if(!empty($formErrors)){ ?>
<div id="errors">
<?php
foreach($formErrors as $error)
{ echo '* ' . $error . '.<br/>';}
?>
</div>
<?php } ?>
<input type="text" name="firstname">
<input type="submit" value="send">
</form>
The PHP code is as follows:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$fname = $_POST['firstname'];
$formErrors = array();
if(strlen($fname) < 2 ){
$formErrors[] = "First name must be longer than 1 character";
}
}
?>
Everything is working fine up to this point, except that I want to prevent the page from scrolling to the top upon form submission. Therefore i used ajax to solve this problem:
$("form").submit(function(e){
e.preventDefault();
$.ajax({
type: $(this).attr("method"),
url: $(this).attr("action"),
data: $(this).serialize()
});
});
Now the form errors won't display anymore, which is not what I want. How can I show the errors again while not discarding ajax? Thanks.
Although this isn't the best way, you can echo the JSON from the file and display those errors in your ajax function like below:
FrontEnd(ajax):
$("form").submit(function(e){
e.preventDefault();
$.ajax({
type: $(this).attr("method"),
url: $(this).attr("action"),
data: $(this).serialize() + '&ajax=1',
dataType:'json',
success: function(res){
if(res.success === false){
$('#errors').html('<ul><li>' + res.errors.join('</li><li>') + '</li></ul>');
}else{
$('#errors').html('');
}
}
});
});
Backend:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$fname = $_POST['firstname'];
$formErrors = array();
if(strlen($fname) < 2 ){
$formErrors[] = "First name must be longer than 1 character";
}
// add this additional check
if(($_POST['ajax'] ?? 'N/A') == '1'){
echo json_encode(['success' => false,'errors' => $formErrors]);
exit; // since we will only send the JSON back to the browser, not the entire form
}
}
?>
Change your form code to this(adding a errors div always by default):
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST">
<div id="errors"></div>
<input type="text" name="firstname">
<input type="submit" value="send">
</form>

Codeigniter + Ajax, can't submit form multiple times without page refresh

I'm trying to do simple task in one page and avoiding page refresh on every form submit using ajax.
The problem is I can only submit update to database one time and the rest is only console log success without updating database.
Controller
function index() {
$data['process'] = $this->Debug_model->getProcess();
$this->load->view('debug', $data);
}
function nextLine() {
$this->form_validation->set_rules('id', 'ID', 'required');
if ($this->form_validation->run() == FALSE)
{
redirect('debug','refresh');
} else {
$data = array(
'currentLine' => $this->input->post('currentLine'),
'nextLine' => $this->input->post('nextLine')
);
$id = $this->input->post('id');
$this->Debug_model->goNext($data, $id);
}
}
Model
function goNext($data, $id)
{
$this->db->where('id', $id);
return $this->db->update('tbl_process', $data);
}
Javascript
$(document).ready(function() {
finish();
});
function finish() {
setTimeout(function() {
update();
finish();
}, 200);
}
function update() {
$.getJSON("apitest", function(data) {
$("#currentLine").empty();
$("#nextLine").empty();
$.each(data.result, function() {
$("#currentLine").append(
"" + this['currentLine'] + "-" + this['deskNo'] + ""
);
$("#nextLine").append(
"" + this['nextLine'] + "-" + this['deskNo'] + ""
);
});
});
}
//btn save
$("#btnSave").click(function(e){
e.preventDefault();
var data = $('#callLine').serialize();
$.ajax({
type: 'POST',
url: "<?php echo base_url('debug/nextLine'); ?>",
data: data,
success: function() {
console.log('success');
}
});
});
View
<h1>Current: <span id="currentLine"></span></h1>
<h2>Next: <span id="nextLine"></span></h2>
<?php foreach ($process->result() as $singleProcess) :
$tobeCurrent = $singleProcess->currentLine + 1;
$tobeNext = $tobeCurrent + 1;
?>
<form action="" method="post" enctype="multipart/form-data" id="callLine">
<input type="hidden" name="id" value="<?php echo $singleProcess->id ?>" />
<input type="hidden" name="currentLine" value="<?php echo $tobeCurrent ?>" />
<input type="hidden" name="nextLine" value="<?php echo $tobeNext ?>" />
<button id="btnSave" class="btn-a" type="btn">NEXT LINE</button>
</form>
<?php endforeach; ?>
The goal is no page refresh when submitting form and can be done multiple times, still without refreshing the page.
Instead of detecting the event on button click,
detect it on the form submit event.
$("#callLine").submit(function(e){
e.preventDefault();
var data = $('#callLine').serialize();
$.ajax({
type: 'POST',
url: "<?php echo base_url('debug/nextLine'); ?>",
data: data,
success: function() {
console.log('success');
}
});
});
also change the button type to submit instead of btn
<button id="btnSave" class="btn-a" type="submit">NEXT LINE</button>

Cannot login using php through jquery

I am currently working on a PHP based web-interface, with a login system.
But for some reason when I hit login, it seems to get to the login.php and return a response back.
But the thing is, the response is not what I need to have, and furthermore logging in is still not happening.
The HTML based login form (Within a modal):
<form class="form" method="post" action="<?php echo Utils::resolveInternalUrl('backend/Login.php') ?>" id="loginForm">
<div class="form-group">
<label for="loginUsername">Username:</label> <input type="text" class="form-control" name="loginUsername" id="loginUsername" />
</div>
<div class="form-group">
<label for="loginPassword">Password:</label> <input type="password" class="form-control" name="loginPassword" id="loginPassword"/>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Login</button>
</div>
</form>
Javascript/jQuery related to login:
var form = $('#loginForm');
form.submit(function (e) {
e.preventDefault();
$.ajax({
'data': form.serialize(),
'type': $(this).attr('method'),
'url': $(this).attr('action'),
'dataType': 'JSON',
success: function (data) {
alert("Success: " + data)
},
error: function (error) {
alert("Error: " + error)
}
})
})
PHP backend, related to login:
if($_SERVER['REQUEST_METHOD'] == "POST") {
$database = Database::getDefaultInstance();
if(isset($_POST['loginUsername']) && isset($_POST['loginPassword'])) {
$connection = $database->getConnection();
$username = $_POST['loginUsername'];
$password = $_POST['loginPassword'];
echo $username . ":" . $password;
$stmt = $connection->query("SELECT * FROM banmanagement.users;");
if($stmt->fetch()) {
session_start();
$_SESSION['username'] = $username;
$_SESSION['sessionId'] = Utils::randomNumber(32);
echo json_encode("Successfully logged in as ${username}.");
exit;
} else {
echo json_encode("No user exists with the name \"${username}\".");
exit;
}
} else {
echo json_encode("Username and/or password is not provided.");
exit;
}
} else {
echo json_encode("Submit method is not POST.");
exit;
}
The result of it:
Click here for screenshot
Edit:
Changed SQL query to: SELECT COUNT(*) FROM banmanagement.users WHERE username=:username;
Edit 2:
Per suggestion, I have used var_dump the output var_dump($_POST) is: array(0) { }.
$stmt = $connection->query("SELECT * FROM banmanagement.users;");
I'm assuming you're using PDO on the backend. If so, you don't need the semicolon in your query. That's why your fetch is failing.
$stmt = $connection->query("SELECT * FROM banmanagement.users");
Ok, so that wasn't it. I was reading the wrong braces. Have you tried var_dump($_POST) to see what, if anything, is being sent?

json increments one id but displays all ids

i am using json for like button. when users clicks it correctly increases the like count and stores in database for corresponding id but it shows increment for all ids in browser which is wrong. i want to display for only id where users has liked but it shows for all.
test url is http://way2enjoy.com/app/check/test/indexp.php
indexp.php file is
<?php
include('/home/xxx/con.php');
$query="Select * from users_jokes order by id desc limit 10";
$result=mysql_query($query);
?>
<html>
<head>
<meta charset="utf-8">
<script src="jquery-3.1.0.min.js"></script>
<script type="text/javascript">
var ajaxSubmit = function(formEl) {
var url = $(formEl).attr('action');
var comment=document.getElementById("jokes_comment").value;
var joke_id=document.getElementById("joke_id_hidden").value;
$.ajax({
url: url,
data:{
'action':'addComment',
'comment':comment,
'joke_id':joke_id
},
dataType: 'json',
type:'POST',
success: function(result) {
console.log(result);
$.ajax({
url: url,
data:{
'action':'getLastComment',
'joke_id':joke_id
},
dataType: 'json',
type:'POST',
success: function(result) {
$('#jokes_comment').val("");
console.log(result[0].description);
$("#header ul").append('<li>'+result[0].description+'</li>');
},
error: function(){
alert('failure');
}
});
},
error: function(){
alert('failure');
}
});
// return false so the form does not actually
// submit to the page
return false;
}
var ajaxLike=function()
{
var joke_id=document.getElementById("joke_id_hidden").value;
// setup the ajax request
$.ajax(
{
url: 'likeskk.php',
data:{
'action':'increment_like',
'joke_id':joke_id
},
dataType: 'json',
type:'POST',
success: function(result)
{
$.ajax(
{
url: 'likeskk.php',
data:{
'action':'display_like',
'joke_id':joke_id
},
dataType: 'json',
type:'POST',
success: function(result)
{
console.log(result);
$("label[for='like_counter']").text(result.likes);
},
error: function(result)
{
alert("error 2");
},
});
},
error: function()
{
alert('failure');
}
});
return false;
}
</script>
<p>commnet list</p>
<div id="header">
<ul id="commentlist" class="justList">
<?php
$query="Select * from comment where joke_id='2'";
$result=mysql_query($query);
while($data = mysql_fetch_array($result)){
$cont = $data['description'];
?>
<li><?php echo $cont;
?></li>
<?php
}
?>
</ul>
</div>
<?php
?>
<form method="post" action="processkk.php" onSubmit="return ajaxSubmit(this);">
<input type=text id="jokes_comment" name="jokes_comment">
</input>
<input type="submit" value="comment">
</form>
</body>
</html>
<?php
while($data = mysql_fetch_array($result)){
$id = $data['id'];
$cont = $data['content'];
$likes = $data['likes'];
?>
<p><?php echo $cont;?></p>
<input type="hidden" value="<?php echo $id ;?>" id="joke_id_hidden">
<p><button onClick="ajaxLike();">Like</button> <label for="like_counter"><?php echo $likes;?></label></p>
<?php }
?>
</body>
</html>
likeskk.php
<?php
include('/home/xxxxxxx/con.php');
$action=$_POST['action'];
if($action=="increment_like")
{
$joke_id=$_POST['joke_id'];
$query="update users_jokes set likes =likes+1 where id='".$joke_id."'";
$result=mysql_query($query);
// setup our response "object"
$retVal=array("Success"=>"true");
print json_encode($retVal);
}
if($action=="display_like")
{
$joke_id=$_POST['joke_id'];
$query = "select likes from users_jokes where id = '$joke_id'";
$qry = mysql_query($query);
while($rows = mysql_fetch_array($qry)){
$likes = $rows['likes'];
}
header('Content-Type: application/json');
// print json_encode(array('foo' => 'bar'));
print json_encode(array('success'=>'true','likes'=>$likes));
}
?>
when i click on one like all like increases. when i post comment on one id it appended and displays in all id
Copy and paste it.
<html>
<head>
<script>
function clickCounter(element)
{
element.value = parseInt(element.value) + 1;
}
</script>
</head>
<body>
<input type="button" value="0" onclick="clickCounter(this)"/>
<input type="button" value="0" onclick="clickCounter(this)"/>
<input type="button" value="0" onclick="clickCounter(this)"/>
<input type="button" value="0" onclick="clickCounter(this)"/>
<input type="button" value="0" onclick="clickCounter(this)"/>
<input type="button" value="0" onclick="clickCounter(this)"/>
<input type="button" value="0" onclick="clickCounter(this)"/>
</body>
</html>
Because you are using the same id. id must be unique
<input type="hidden" value="4638" id="joke_id_hidden">
Rather than using a hidden input for each entry you could use a dataset on the button itself with the corresponding ID. When the button is clicked the javscript function could read that dataset value and use that in the ajax POST request. So, as an example:
<!doctype html>
<html>
<head>
<title>Like the jokes...</title>
</head>
<body>
<form id='bttns'>
<?php
/* pseudo generate some jokes with buttons and labels to emulate your page */
for( $i=1; $i < 20; $i++ ){
$random=rand(1,20);
echo "
<p>Funny joke...[{$i}]</p>
<input type='button' value='Like' data-id='$i' />
<label class='counter'>{$random}</label>";
}
?>
</form>
<script type='text/javascript'>
var col=document.querySelectorAll('#bttns input[type=\"button\"]');
for( var n in col )if(col[n].nodeType==1)col[n].onclick=function(e){
var el=typeof(e.target)!='undefined' ? e.target : e.srcElement;
var label=el.nextSibling.nextSibling;
var id=el.dataset.id;
label.innerHTML=parseInt( label.innerHTML )+1;
alert( 'use ajax to POST this id: '+id );
}
</script>
</body>
</html>
I should add perhaps that the ajax callback function would be the place to update the value of likes for each joke rather than as here - it's just example code showing how you could do away with hidden fields and the problem of duplicate ids.

Submiting for using ajax and php and return response

I am using this php to submit a form and is working now i want to post to it using ajax and return what i have submitted without reloading the page but is not posting to me database and it not showing me errors.
Which other simple way can i archive this or can anyone show me where am doing it wrong
Here is the full program <?php echo $_GET['postid'];?> < this get ID of my main blog post
HTML STRUCTURE
<form id="add-comment" action="javascript:void(0);" style="font-size: 100%;">
<textarea placeholder="" name="comment" cols="68" rows="3" style="min-height:30px;" id="comment"></textarea>
<?php
if(!isset($_SESSION['user_login'])) {
echo "<label>Enter name</label><br>";
echo "<input placeholder='Enter a name' style='width:130px;height: inherit;' required='true' id='anony' type='text' name='name'/>";
}?>
<input tabindex="0" value="Add Comment" class="btnpostq" id="donedbtn" type="submit"/>
<input type="hidden" value="<?php echo $_GET['postid'];?>" name="rid"/>
</form>
Ajax
<script>
$(document).ready(function(){
$('#add-comment').submit(function(){
$('#response').html("<b>Loading response...</b>");
$.ajax({
type: 'POST',
url: 'alter_reply.php',
data:'comment='+comment+'&name='+name+'&rid='+rid,
})
.done(function(data){
$('#response').html(data);
})
.fail(function() {
alert( "Posting failed." );
});
return false;
});
});
</script>
alter_reply.php
<?php
if($_POST) {
$db_host = "localhost";
$db_user = "root";
$db_pass = "";
$db_name = "post";
try {
$db_conn = new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,$db_pass);
$db_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $db_conn->prepare("INSERT INTO replys(rid,mesreplys,rtime,rusername) VALUES(:rid,:mesreplys,:rtime,:rusername)");
$stmt->bindParam(':rid', $rid);
$stmt->bindParam(':mesreplys', $comment);
$stmt->bindParam(':rtime', $timedate);
$stmt->bindParam(':rusername', $user);
$form = $_POST;
$rid= $form['rid'];
$comment = $form['comment'];
$timedate = date("Y-m-d H:i:s");
if(isset($_SESSION['user_login'])){
$user = $_SESSION['user_login'];
}else{
$anony_user = $form['name'];
$user = $anony_user;
}
$stmt->execute();
}
catch(PDOException $e)
{
echo "Error:" . $e->getMessage();
}
$db_conn = null;
}
?>
You have not gathered the variables values. Get them and then pass to $.ajax as below :
var comment = $('#comment').val();
var name = $('#anony').val();
var rid = $('#rid').val();
Make sure you have id in your inputs.
You form should look like :
<form id="add-comment" action="javascript:void(0);" style="font-size: 100%;">
<textarea placeholder="" name="comment" cols="68" rows="3" style="min-height:30px;" id="comment"></textarea>
<?php
if(!isset($_SESSION['user_login'])) {
echo "<label>Enter name</label><br>";
echo "<input placeholder='Enter a name' style='width:130px;height: inherit;' required='true' id='anony' type='text' name='name'/>";
}?>
<input tabindex="0" value="Add Comment" class="btnpostq" id="donedbtn" type="submit"/>
<input type="hidden" value="<?php echo $_GET['postid'];?>" id="rid" name="rid"/>
</form>
And script must be :
<script>
$(document).ready(function(){
$('#add-comment').submit(function()
{
var comment = $('#comment').val();
var name = $('#anony').val();
var rid = $('#rid').val();
$('#response').html("<b>Loading response...</b>");
$.ajax({
type: 'POST',
url: 'alter_reply.php',
data:'comment='+comment+'&name='+name+'&rid='+rid,
})
.done(function(data){
$('#response').html(data);
})
.fail(function() {
alert( "Posting failed." );
});
return false;
});
});
</script>

Categories

Resources