As you can see I want to create in a while multiple forms and buttons. The problem is when I want to submit one row from my array I want to execute this specific form and not another.
Even I put button tag inside the form I have problem. I think to set a unique id to form tag such as id="form_submit_change_status<?php echo $row['id_user']; ?>". But then the problem is what changes I have to do to the javascript code.
sorry for my English and I hope to understand my problem...
while($row = $result->fetch_array() ){
<form name="form_submit_change_status" id="form_submit_change_status" action="">
<input type="text" class="user_id" id="user_id" name="user_id" value="<?php echo $row['id_user']; ?>" />
<input type="text" name="is_enabled" value="<?php echo $row['is_enabled']; ?>" />
</form>
<button type="submit" id="submit_change_status" class="btn btn-warning btn-xs" value="<?php echo $row['is_enabled']; ?>">Change status</button>
}
$(document).ready(function(){
$('#submit_change_status').click(function(){
var formData = $("#form_submit_change_status").serializeArray();
var userId = $("#user_id").val();
alert(userId);
var URL = $("#form_submit_change_status").attr("action");
var URL = "change_status_user.php";
$.post(URL,
formData,
function(data, textStatus, jqXHR)
{
// alert("Data: " + data + "\nStatus: " + textStatus);
}).fail(function(jqXHR, textStatus, errorThrown)
{
});
var varChangeStatus = $('#is_enabled'+userId).val();
if(varChangeStatus=="true"){
$('#is_enabled'+userId).html('false');
}else{
$('#is_enabled'+userId).html('true');
}
});
});
</script>
// change_status_user.php
$DBConnection = new DBConnection();
if (isset($_POST['is_enabled'])) {
$id = $_POST['user_id'];
$status = $_POST['is_enabled'];
if($status=="true")
$status = "false";
else
$status = "true";
$sql = "UPDATE users SET is_enabled = '$status' WHERE id_user = $id";
$res = $DBConnection->db_connection->query($sql);
echo $sql;
}
As suggested above by others, it's flexible to use classes as opposed to IDs as they need to be unique. Classes also help grouping elements for easier access later.
HTML(PHP):
while($row = $result->fetch_array() ){
<form name="form_submit_change_status" class="form_submit_change_status" action="">
<input type="text" class="user_id" name="user_id" value="<?php echo $row['id_user']; ?>" />
<input type="text" class="is_enabled" name="is_enabled" value="<?php echo $row['is_enabled']; ?>" />
<button type="button" class="btn btn-warning btn-xs" value="<?php echo $row['is_enabled']; ?>">Change status</button>
</form>
}
jQuery:
$(function(){
$('.btn.btn-warning').click(function(e) {
e.preventDefault();
var $form = $(this).closest(".form_submit_change_status");
var formData = $form.serializeArray();
var userId = $form.find(".user_id").val();
alert(userId);
//var URL = $form.attr("action");
var URL = "change_status_user.php";
$.post(URL, formData)
.done(function(data) {
//success
}).
fail(function(jqXHR, textStatus, errorThrown) {
//failure
});
var $isStatus = $form.find(".is_enabled");
var varChangeStatus = $isStatus.val();
$isStatus.val(varChangeStatus=="true" ? "false" : "true");
});
});
You're using a while loop to create HTML elements, but using the same ID attribute each time. IDs need to be unique; classes, however, do not.
Try this instead:
PHP/HTML:
while($row = $result->fetch_array() ){
<form name="form_submit_change_status" class="form_submit_change_status" action="">
<input type="text" class="user_id" name="user_id" value="<?php echo $row['id_user']; ?>" />
<input type="text" class="is_enabled" name="is_enabled" value="<?php echo $row['is_enabled']; ?>" />
<button type="submit" class="btn btn-warning btn-xs" value="<?php echo $row['is_enabled']; ?>">Change status</button>
</form>
}
JS:
$(document).ready(function() {
$('.submit_change_status').click(function(e) {
e.preventDefault();
var $form = $(this).closest(".form_submit_change_status");
var formData = $form.serializeArray();
var userId = $form.find(".user_id").val();
alert(userId);
// var URL = $form.attr("action");
var URL = "change_status_user.php";
$.post(URL,
formData,
function(data, textStatus, jqXHR) {
// alert("Data: " + data + "\nStatus: " + textStatus);
}).fail(function(jqXHR, textStatus, errorThrown) {});
var $isEnabled = $form.find('.is_enabled');
var varChangeStatus = $isEnabled.val();
if (varChangeStatus == "true") {
$isEnabled.html('false');
} else {
$isEnabled.html('true');
}
});
});
Related
I am deleting records with ajax and php. When I click the button it erases the record but when I click to delete another record it does nothing. What am I doing wrong?
HTML
<form id="prop_remove">
<input type="hidden" name="id" id="last_id" value="<?php echo $id; ?>">
<input type="hidden" name="user" id="last_user" value="<?php echo $user; ?>">
<input type="button" name="submit" id="last_prop" class="button fullwidth margin-top-5" value="Delete">
</form>
AJAX
<script>
$(document).ready(function() {
$('#last_prop').click(function() {
var id = $('#last_id').val();
var user = $('#last_user').val();
$.ajax({
url: "delete.php",
method: "POST",
data: {
ilan_id: id,
ilan_user: user
},
success: function(response) {
if (response == 1) {
$('#last_prop').closest('tr').css('background', 'tomato');
$('#last_prop').closest('tr').fadeOut(800, function() {
$(this).remove();
});
} else {
alert('Invalid id');
}
}
});
});
});
</script>
PHP
<?php
require_once 'config.php';
$id = $_POST['ilan_id'];
$user = $_POST['ilan_user'];
$checkRecord = "SELECT * FROM last_tbl WHERE id = '$id' AND user = '$user'";
$check_result = mysqli_query($conn, $checkRecord);
$totalrows = mysqli_num_rows($check_result);
if($totalrows > 0){
$delete_sql = "DELETE FROM last_tbl WHERE id = '$id' AND user = '$user';";
$delete_result = mysqli_query($conn, $delete_sql);
echo 1;
exit;
}
?>
Your problem is that you're overwriting the HTML element IDs. You can remove your forms and use a single button instead, and pass data through the data attribute of the buttons.
Replace your form by a single button
<button class="button fullwidth margin-top-5 last_prop" data-last-id="<?= $id; ?>" data-last-user="<?= $user; ?>">Delete</button>
Then adapt your jQuery to use the class last_prop instead of the ID, and fetch the values from the data attributes we set above.
<script>
$(document).ready(function () {
$('.last_prop').click(function () {
var id = $(this).data('last-id');
var user = $(this).data('last-user');
$.ajax({
url:"delete.php",
method: "POST",
data: {ilan_id: id, ilan_user: user},
success:function(response){
if (response == 1 ){
$('#last_prop').closest('tr').css('background','tomato');
$('#last_prop').closest('tr').fadeOut(800,function(){
$(this).remove();
});
} else {
alert('Invalid id');
}
}
});
});
});
</script>
Also, your query can be reduced to one (you don't need that SELECT), and should be with a prepared statement.
<?php
require_once 'config.php';
$id = $_POST['ilan_id'];
$user = $_POST['ilan_user'];
$sql = "DELETE FROM last_tbl WHERE id = ? AND user = ?;";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $id, $user);
$stmt->execute();
if ($stmt->affected_rows) {
// rows were deleted
echo 1;
}
$stmt->close();
I have a table of recipes created by a particular user, and when the pencil mark on each row of the table is clicked, a modal is displayed, showing the details of this particular recipe and it should allow the user to edit the recipe and save the updated version to the database. However, although the details are correctly being passed to the modal, the recipe id doesn't seem to be passed to the modal, since I have tried to output the recipe id into the console and it says the recipe id is undefined. I have tried to debug this error but to no avail. Can anyone provide any insight into why this might be?
//Recipe.js
$('.editThis').on('click', function() {
var recipe_id = $(this).attr('data-id');
var request = $.ajax({
url: "ajax/displayRecipe.php",
type: "post",
dataType: 'json',
data: {recipe_id : recipe_id}
});
request.done(function (response, textStatus, jqXHR){
console.log("response " + JSON.stringify(response));
$('#name').val(response.name);
$('#date').val(response.date);
});
});
$('#editRecipe').click(function() {
var recipe_id = $(this).attr('data-id');
var name_input = $('#name').val();
var date_input = $('#date').val();
var request = $.ajax({
url: "ajax/updateRecipe.php",
type: "post",
data: {name : name_input, date : date_input, recipe_id : recipe_id},
dataType: 'json'
});
request.done(function (response, textStatus, jqXHR){
console.log(response);
});
});
//Recipe.php
<?php
$recipeObject = new recipeList($database); //Lets pass through our DB connection
$recipe = $recipeObject->getUserRecipes($_SESSION['userData']['user_id']);
foreach ($recipe as $key => $recipes) {
echo '<tr><td>'. $value['name'].'</td><td>'. $value['date'].'</td><td>'.'<a data-id = '.$value['recip_id'].' data-toggle="modal" class="edit editThis" data-target="#editRecipe"><i class="fa fa-pencil"></i></a>'.'</td></tr>';
}
?>
// editRecipe Modal
<div id="recipe" class="modal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header recipe">
<h1 class="modal-title">Edit Recipe</h4>
</div>
<div class="modal-body">
<form method="post" id="updateRecipeForm">
<?php
require_once('classes/recipes.classes.php');
$recipeObject = new recipeList($database);
$recipe = $recipeObject->getRecipeDetails(recipe_id);
if(isset($_POST['submit'])) {
$updateRecipe = $recipeObject ->updateRecipe($_POST['name'], $_POST['date'], $_POST['recipe_id']);
if($updateRecipe) {
echo ("Your recipe has been updated!";
}
}
?>
<div class="form-group">
<input type="text" class="control-form" id="name" value = "<?php echo $recipe['name']; ?>">
</div>
<div class="form-group">
<input type="date" class="control-form" id="date" value = "<?php echo $recipe['date']; ?>">
</div>
</div>
<div class="form-group">
<input type="hidden" class="form-control" data-id=".$recipe['recipe_id']." id="recipe_id" name="recipe_id" value = "<?php echo $recipe['recipe_id']; ?>">
</div>
<button type="submit" class="btn recipe" id="editRecipe" data-dismiss="modal">Save</button>
</form>
</div>
</div>
</div>
</div>
//ajax - updateRecipe.php
<?php
require_once('../includes/database.php');
require_once('../classes/recipes.classes.php');
if($_POST['name'] && $_POST['date'] && $_POST['trans_id']){
$recipeObject = new recipeList($database);
echo $recipeObject->updateRecipe($_POST['name'], $_POST['date'], $_POST['recipe_id']);
}
?>
//recipes.classes.php
...
public function getRecipeDetails($recipeid){
$query = "SELECT * FROM recipe WHERE recipe_id = :recipe_id";
$pdo = $this->db->prepare($query);
$pdo->bindParam(':recipe_id', $recipeid);
$pdo->execute();
return $pdo->fetch(PDO::FETCH_ASSOC);
}
public function updateRecipe($name, $date, $recipe_id){
$query = "UPDATE recipe SET name = :name, date = :date WHERE recipe_id = :recipe_id";
$pdo = $this->db->prepare($query);
$pdo->bindParam(':name', $name);
$pdo->bindParam(':date', $date);
$pdo->bindParam(':recipe_id', $recipe_id);
$pdo->execute();
}
Try the following:
$(document).on('click', '.editThis',function() {...});
$(document).on('click','#editRecipe',function() {...});
Try this onclik function
Some time you cant get the apt value from this So Try this method.
we can use id but in your case you foreach the a tag so we cant repeat id. Hope Its Works
<a data-toggle="modal" class="recipe_<?php echo $value['recipe_id']; ?> edit editThis" onclick="editRecipe('<?php echo $value['recipe_id']; ?>')" ><i class="fa fa-pencil"></i></a>
function editRecipe(txt) {
var recipe_id = $('.recipe_'+txt).val();
var name_input = $('#name').val();
var date_input = $('#date').val();
var request = $.ajax({
url: "ajax/updateRecipe.php",
type: "post",
data: {name : name_input, date : date_input, recipe_id : recipe_id},
dataType: 'json'
});
request.done(function (response, textStatus, jqXHR){
console.log(response);
});
};
I am attempting to create a setInterval function to check for new comments, select and post them. So far, it is 'sort-of' working, but not how I want it to. What it is doing is every three seconds re-posting all of my comments instead of just refreshing them.
What am I doing wrong for this to not just refresh the comments?
HTML
<form action="" method="POST" id="comment-form">
<textarea id="home_comment" name="comment" placeholder="Write a comment..." maxlength="1000" required></textarea><br>
<input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
<input id="comment-button" name="submit" type="submit" value="Post">
</form>
<div id="comment-container">
AJAX
function commentRetrieve(){
$.ajax({
url: "ajax-php/comment-retrieve.php",
type: "get",
success: function (data) {
// console.log(data);
if (data == "Error!") {
alert("Unable to retrieve comment!");
alert(data);
} else {
$('#comment-container').prepend(data);
}
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + " | " + errorThrown);
console.log("error"); //otherwise error if status code is other than 200.
}
});
}
setInterval(commentRetrieve, 300);
PHP
$user = new User();
$select_comments_sql = "
SELECT c. *, p.user_id, p.img
FROM home_comments AS c
INNER JOIN (SELECT max(id) as id, user_id
FROM profile_img
GROUP BY user_id) PI
on PI.user_id = c.user_id
INNER JOIN profile_img p
on PI.user_id = p.user_id
and PI.id = p.id
ORDER BY c.id DESC
";
if ($select_comments_stmt = $con->prepare($select_comments_sql)) {
//$select_comments_stmt->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$select_comments_stmt->execute();
//$select_comments_stmt->bind_result($comment_id, $comment_user_id, $comment_username, $home_comments, $comment_date, $commenter_user_id, $commenter_img);
//$comment_array = array();
$rows = $select_comments_stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
$comment_id = $row['id'];
$comment_user_id = $row['user_id'];
$comment_username = $row['username'];
$home_comments = $row['comment'];
$comment_date = $row['date'];
$commenter_user_id = $row['user_id'];
$commenter_img = $row['img'];
$commenter_img = '<img class="home-comment-profile-pic" src=" '.$commenter_img.'">';
if ($home_comments === NULL) {
echo 'No comments found.';
} else {
echo '<div class="comment-post-box">';
echo $commenter_img;
echo '<div class="comment-post-username">'.$comment_username. '</div>';
echo '<div>'.$comment_date. '</div>';
echo '<div class="comment-post-text">'.$home_comments. '</div>';
echo '</div>';
}
}
}
It's because when you have comments you print new one. What i suggest to do is use JSON to get the comments array, pass an ID to each comment and check if the Id is allready present in the list. that way you only paste new comment, here's an example.:
html
<form action="" method="POST" id="comment-form">
<textarea id="home_comment" name="comment" placeholder="Write a comment..." maxlength="1000" required></textarea><br>
<input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
<input id="comment-button" name="submit" type="submit" value="Post">
</form>
<div id="comment-container">
<div id="comment-1">bla bla bla</div>
</div>
js
function commentRetrieve(){
$.ajax({
url: "ajax-php/comment-retrieve.php",
type: "get",
success: function (data) {
// console.log(data);
if (data == "Error!") {
alert("Unable to retrieve comment!");
alert(data);
} else {
var array = JSON.parse(data);
$(array).each(function($value) {
if($('#comment-container').find('#comment-' + $value.id).length == 0) {
$('#comment-container').prepend($value.html);
}
});
}
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + " | " + errorThrown);
console.log("error"); //otherwise error if status code is other than 200.
}
});
}
setInterval(commentRetrieve, 300);
PHP
$user = new User();
$select_comments_sql = "
SELECT c. *, p.user_id, p.img
FROM home_comments AS c
INNER JOIN (SELECT max(id) as id, user_id
FROM profile_img
GROUP BY user_id) PI
on PI.user_id = c.user_id
INNER JOIN profile_img p
on PI.user_id = p.user_id
and PI.id = p.id
ORDER BY c.id DESC
";
if ($select_comments_stmt = $con->prepare($select_comments_sql)) {
//$select_comments_stmt->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$select_comments_stmt->execute();
//$select_comments_stmt->bind_result($comment_id, $comment_user_id, $comment_username, $home_comments, $comment_date, $commenter_user_id, $commenter_img);
//$comment_array = array();
$rows = $select_comments_stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
$comment_id = $row['id'];
$comment_user_id = $row['user_id'];
$comment_username = $row['username'];
$home_comments = $row['comment'];
$comment_date = $row['date'];
$commenter_user_id = $row['user_id'];
$commenter_img = $row['img'];
$commenter_img = '<img class="home-comment-profile-pic" src=" '.$commenter_img.'">';
if ($home_comments === NULL) {
echo 'No comments found.';
} else {
$html = "";
$html .= '<div class="comment-post-box">';
$html .= $commenter_img;
$html .= '<div class="comment-post-username">'.$comment_username. '</div>';
$html .= '<div>'.$comment_date. '</div>';
$html .= '<div class="comment-post-text">'.$home_comments. '</div>';
$html .= '</div>';
array('id' => $comment_id, 'html' => $html)
}
}
}
For better improvement, i would suggest looking into NodeJs socket for more realtime update. Here's a few link.
Official NodeJs Website
Official SocketIo Website
Chat tutorial with socketIo and Nodejs
Hope it helps!
Nic
I've got following problem with my PHP code:
my form is divided into two divs: first div shows up when the page is opened, second div displays after clicking a button (and this first one, thanks to Ajax, hides). My plan is to check a few statements, if true then create POST, get from it data and then dynamically create table, switching the content using Ajax again. BUT. I cannot use the 'action' thing because of the statements. When I've got 'submit' type - it creates POST, but reloads the page. If I replace it with 'button' type - Ajax works, but POST is empty.
Here's my code:
function formu ($w="1", $sr="on", $comma="",
$space ="", $other =""){?>
<form id="options" action="" method="POST" >
<div id = "first">
<h1 id = "title"> Choose a file </h1>
<input type = "radio" name="radio" id ="radio" value="op1" class ="radio"> ONE
<br>
<input type ="radio" name="radio" id="radio" value ="op2" class = "radio"> TWO
<br>
<input type ="radio" name="radio" id="radio" value="op3" class = "radio"> THREE
<br>
<input type = "button" id="Submit" Value = "Show">
</div>
<div id = "sec">
<h1 id = "title2"> Choose options </h1>
<p id="odwiersza"> Cut: </p>
<input type="text" name="w" value=""> <br>
<p id="Separators"> Separator: </p>
<input type = "checkBox" name="sr"> sr
<input type= "checkBox" name="comma"> comma
<input type = "checkBox" name = "space"> space
<input type = "checkBox" name ="other"> other (which?) <input type="text" name="such">
<br>
<input type="submit" id="choose" value = "Enter">
</div>
</form>
<?php }
formu();
?>
<div id= "here"> </div>
And then my ideas:
if($_SERVER["REQUEST_METHOD"] == "POST"){
$w = $_POST['w'];
$sr = $_POST['sr'];
$comma = $_POST['comma'];
$space = $_POST['space'];
$other = $_POST['other'];
if (empty($w) || !($sr || $comma || $space || $other)){
echo "You have to enter the number and choose at least one separator!";
} else {
**/* here I've tried:
?> <script>
window.location = 'third.php'; //but it doesn't create POST table
</script>
<?php
require_once("third.php"); //but it attaches value with reloading the page, so first div shows up above my table
include "third.php"; //same as above
*/**
}
}
I've also tried Ajax script but it doesn't work as well:
<script>
var SubmitBtn2 = document.getElementById('choose');
SubmitBtn2.onclick = function(){
var formularz = document.getElementById('sec');
formularz.style.display = 'none';
var formularz1 = document.getElementById('first');
formularz1.style.display = 'none';
var title2 = document.getElementById('title2');
$(title2).hide();
var FormData = {plik: "<?php echo $_POST['radio']; ?>",
wiersz: "<?php echo $_POST['w']; ?>",
średnik: "<?php echo $_POST['sr']; ?>",
przecinek: "<?php echo $_POST['comma']; ?>",
spacja: "<?php echo $_POST['space']; ?>",
inne: "<?php echo $_POST['other']; ?>",
jakie: "<?php echo $_POST['such']; ?>"};
$(document.getElementById('back')).hide();
$.ajax({
type: 'POST',
url: "third.php",
data: FormData,
complete: function (reply) {
$.ajax({
type: 'POST',
url: "third.php",
complete: function (reply) {
$('here').append(reply);
}
});
}
});
}
</script>
EDIT:
I've tried to use event.preventDefault(); and now my code looks as below:
$(document.getElementById('choose')).click(function()
{ event.preventDefault();
$.ajax({
url : $(this).attr('action') || window.location.pathname,
type: "POST",
data: $(this).serialize(),
success: function (data) {
$.get("test5new.csv", function(data) {
var build = '<table border="1" cellpadding="2" cellspacing="0" width="100%">\n';
var rows = data.split("\n");
var cut = rows.slice(<?php echo $w; ?>); //ponieważ tablice liczy się od 0
cut.forEach( function getvalues(thisRow) {
build += "<tr>";
var columns = thisRow.split("<?php echo $pattern; ?>");
for(var i=0;i<columns.length;i++){ build += "<td>" + columns[i] + "</td>"; }
build += "</tr>";
})
build += "</table>";
$(document.getElementById('wrap')).append(build);
});
},
error: function (jXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
but, although it does not refresh, it doesn't create POST neither. Please please help.
I have an alert box that keeps prompting "Image uploaded", even though $imagename is empty.
Here's the script:
<script>
function ajax_post1(ca){
var cat = ca;
var name = document.getElementById("name").value;
var desc = document.getElementById("description").value;
var key = document.getElementById("keyword").value;
var image = document.getElementById("image").value;
if ($.isEmptyObject(image)) {
alert('pls upload your image')
} else {
alert(' image uploaded ')
}
var myData = 'content_ca='+ cat + '&content_desc='+desc+ '&content_key='+key+ '&content_name='+name;//build a post data structure
jQuery.ajax({
type: "POST", // HTTP method POST or GET
url: "uploadsignuppackageresponse.php", //Where to make Ajax calls
dataType:"text", // Data type, HTML, json etc.
data:myData, //Form variables
success:function(response){
//$("#imagebox").append(response);
//$("#contentText").val(''); //empty text field on successful
//alert("haha");
}, error:function (xhr, ajaxOptions, thrownError){
alert(thrownError);
}
});
};
</script>
This is the main page:
<?php
$sql1 = mysql_query ("SELECT * FROM dumimage WHERE email = '$user_signup' AND cat='company' ");
$row = mysql_fetch_array($sql1);
$imagename = $row['name'];
?>
Name:
<input id="name" type="text" ></input>
<input id="image" type="hidden" value="<?php echo $imagename ?> "></input>
Description
<textarea id="description" rows="7" cols="42"></textarea>
Keywords:
<input id="keyword" type="text" placeholder="3 Maximum Keywords" ></input>
<input type="submit" value="Upload" class="pre" style="float:left; onClick="ajax_post1('company')">
Try this to see if your objects empty
if (image.length < 1) {
alert('pls upload your image')
} else {
alert(' image uploaded ')
}
Try to replace this line:
if ($.isEmptyObject(image)) {
With this one:
if (image != '') {
You also have to correct your php code because you have closed the bracket in the wrong place and you are missing a semicolon:
<input id="image" type="hidden" value="<?php echo $imagename;?>"></input>