I have an HTML that gets its values from an array list. I'm submitting the form with Ajax and with a PHP script. The issue I'm facing is when clicking on the other array it only submits the first value array. Below is what my form looks like with the PHP loop of array listing:
index.php
$query_product = "SELECT * FROM products ORDER BY id DESC";
$product_stmt = $conn->prepare($query_product);
if($product_stmt->execute()){
while($row_product = $product_stmt->fetch(PDO::FETCH_ASSOC)){
$id = $row_product["id"];
$title = $row_product["title"];
$description = $row_product["description"];
$price = $row_product["price"];
$img = $row_product["img"];
?>
<form onsubmit="clickButton()">
<input type="hidden" value="<? echo $title ?>" name = "title" id="title" >
<input type="hidden" value="<? echo $id ?>" name = "id" id="id" >
<input type="hidden" value="<? echo $price; ?>" name="price" id="price">
<input type="hidden" value="<? echo $img; ?>" name="img_src" id="img_src">
<button type="submit" id="add_to_cart" name="add_to_cart" class="btn btn-outline-secondary btn-sm" value="Add to cart" onclick="return clickButton();">Add Cart</button>
</form>
<?php
}
}
?>
My Ajax looks like the below:
<script type="text/javascript">
function clickButton(){
var title = $("#title").val();
var price = $("#price").val();
var img_src = $("#img_src").val();
var id = $("#id").val();
alert(title);
$("#add_to_cart").attr("disabled", true);
$.ajax({
type:"post",
url:"my_add_cart.php",
data:
{
'title' :title,
'price' :price,
'img_src' :img_src,
'id' :id
},
cache:false,
beforeSend: function(){
$("#loading").show();
},
complete: function(){
$("#loading").hide();
},
success: function (data)
{
// alert(data['message']);
//enable loading
$("#add_to_cart").attr("disabled", false);
$('#msg').html(data['message']);
$('#count').html(data['count']);
}
});
return false;
}
</script>
When I tried to alert(title); above it return just the first array value even though I click the other arrays.
If you ignore the need for a form as you are using ajax you could streamline your code so that each record displays a single button that has various attributes set which are read by the javascript click handler and used to construct the payload sent via ajax to the php server.
$query_product="SELECT * FROM products ORDER BY id DESC";
$product_stmt = $conn->prepare( $query_product );
if( $product_stmt->execute() ){
while( $rs = $product_stmt->fetch( PDO::FETCH_ASSOC ) ){
printf(
'<input type="button" class="btn btn-outline-secondary btn-sm ajax" value="Add to cart" data-id="%s" data-title="%s" data-price="%s" data-img="%s" />',
$rs["id"],
$rs["title"],
$rs["description"],
$rs["price"],
$rs["img"]
);
}
}
?>
<script>
document.querySelectorAll('input.ajax').forEach( bttn => bttn.addEventListener('click',function(e){
let fd=new FormData();
fd.set( 'id', this.dataset.id );
fd.set( 'title', this.dataset.title );
fd.set( 'price', this.dataset.price );
fd.set( 'img_src', this.dataset.img );
alert( this.dataset.title );
$.ajax({
type:"post",
url:"my_add_cart.php",
data:fd,
cache:false,
beforeSend: function(){
$("#loading").show();
},
success:function( data ){
$("#add_to_cart").attr("disabled", false);
$('#msg').html(data['message']);
$('#count').html(data['count']);
},
complete: function(){
$("#loading").hide();
}
});
}))
</script>
So I was able to solve this myself by adding the ID of each item from the loop to the ID of the input form in the HTML making the ID of each item unique. Below is how I solved it:
<form onsubmit="clickButton(<? echo $id ?>)">
<input type="hidden" value="<? echo $title ?>" name = "<? echo $id.'_title' ?>" id="<? echo $id.'_title' ?>" >
<input type="hidden" value="<? echo $id ?>" name = "<? echo $id.'_id' ?>" id="<? echo $id.'_id' ?>" >
<input type="hidden" value="<? echo number_format($price); ?>" name = "<? echo $id.'_price' ?>" id="<? echo $id.'_price' ?>" >
<input type="hidden" value="<? echo "url".$row_product_img[0]; ?>" name = "<? echo $id.'_img_src' ?>" id="<? echo $id.'_img_src' ?>">
<button type="submit" id="add_to_cart" name="add_to_cart" class="btn btn-outline-secondary btn-sm" value="Add to cart" onclick="return clickButton(<? echo $id ?>);">Add Cart</button>
</form>
And my Javascript is as below:
<script type="text/javascript">
function clickButton(id){
var title=document.getElementById(id+'_title').value;
var price=document.getElementById(id+'_price').value;
var img_src=document.getElementById(id+'_img_src').value;
var id=document.getElementById(id+'_id').value;
$("#add_to_cart").attr("disabled", true);
$.ajax({
type:"post",
url:"my_add_cart.php",
data:
{
'title' :title,
'price' :price,
'img_src' :img_src,
'id' :id
},
cache:false,
beforeSend: function(){
$("#loading").show();
},
complete: function(){
$("#loading").hide();
},
success: function (data)
{
// alert(data['message']);
//enable loading
$("#add_to_cart").attr("disabled", false);
$('#msg').html(data['message']);
$('#count').html(data['count']);
}
});
return false;
}
</script>
Related
I want to create form for edit data from MySQL with javascript. when I click link Edit it will show edit form for edit data.
This is from and php code for show data.
<form id="form-edit" method="post">
<?php
$sql = "SELECT * FROM comment WHERE question_id = $question_id ORDER BY id DESC";
$r1 = mysqli_query($link, $sql);
while($cm = mysqli_fetch_array($r1)) {
$comment_id = $cm['id'];
echo '<section class="section-comment">';
echo '<span class="commentator">' .$cm['user_id'] . '</span>';
echo $cm['detail'];
// This is link Edit
echo 'Edit';
echo $comment_id; //This can show correct comment_id
?>
<div id="form-edit-dialog">
<input type="text" name="user_id" value="<?php echo $user_id ?>" readonly > <br>
//I add this line for check comment_id but it show max comment_id to min when I open and close form
<input type="text" name="id" value="<?php echo $comment_id ?>" readonly > <br>
<textarea name="detail"></textarea><br>
<button type="submit" id="submit-edit">Submit</button>
<input type="hidden" name="comment_id" id="comment-id">
}
</form>
</div>
I write code java script like this.
$(function() {
$('a.edit-comment').click(function(event) { //Click link Edit
$('#form-edit')[0].reset();
event.preventDefault();
var t = "Edit Comment";
$('#form-edit-dialog').dialog({
width: '600px',
title: t,
modal: true,
position: { my: "center", at: "center", of: window}
});
//set value for hidden
$('#comment-id').val($(this).attr('edit-id'));
});
$('#submit-edit').click(function() {
$('form#form-edit').ajaxForm({
url: 'save-edit.php',
type: 'post',
dataType: 'script',
beforeSend: function() {
$.blockUI({message:'<h3>Sending data...</h3>'});
},
complete: function() {
$.unblockUI();
}
});
});
});
PHP can list all comment and show comment_id correctly but when I click at Edit , it show max number of comment_id and when I close form and click Edit again. The comment_id will reduce comment_id number untill no comment_id.
Can I use php and javascript create form edit data or I have to send data to new page?
if the user has the right to comment it means he is logged, so basically you can get the id from session, cookie; doesn't make sens to extract here the user id OR you can make the check if he has the right to comment ( user_id is same with session one).
just make the switch between and like this:
<
<div id="showtext<?php echo $comment_id ?>" >
<span id="comment<?php echo $comment_id ?>"><?php echo $cm['detail'] ?></span>
Edit
<div>
<!-- this is invisible at start -->
<div id="showedit<?php echo $comment_id ?>" style="display:none">
<textarea id="edittext<?php echo $comment_id ?>"><?php echo $cm['detail'] ?></textarea>
Save comment
</div>
and javascript to toggle views:
$('.edit-comment').click(function() {
var id=$(this).attr("id");
$("#showedit"+id).show();
$("#showtext"+id).hide();
});
and to submit
$('.submit-comment').click(function() {
var id=$(this).attr("id");
var comment=$("#edittext"+id).val();
//send the data via ajax with parameters id and comment to alter the row, in php add the user id from session, cookie and on success:
//replace the old text
$("#comment"+id).html(comment);
//and make the switchback
$("#showedit"+id).hide();
$("#showtext"+id).show();
})
I have a comment system that is working fine. But now I wanna make it work into a loop, so it needs is add an id to identify as unique every "comment box", "submit buttom", so on. Due to there are many classes involved I got lost adding the index to the js function ... and actually everything.
This is my code:
<?php
$sql = mysql_query("SELECT * FROM tblopiniones_persopoli WHERE id_post = '$id_post' AND intActivo = '1' LIMIT 0,10") or die(mysql_error());
while($affcom = mysql_fetch_assoc($sql)){
$name = $affcom['intName'];
$email = $affcom['email'];
$comment = $affcom['strComment'];
$date = $affcom['date'];
// Get gravatar Image
// https://fr.gravatar.com/site/implement/images/php/
$default = "mm";
$size = 35;
$grav_url = "http://www.gravatar.com/avatar/".md5(strtolower(trim($email)))."?d=".$default."&s=".$size;
?>
<div class="cmt-cnt">
<img src="<?php echo $grav_url; ?>" />
<div class="thecom">
<h5><?php echo ObtenerNombreFull_Usuario($name); ?></h5><span data-utime="1371248446" class="com-dt"></span>
<br/>
<p>
<?php echo $comment; ?>
</p>
</div>
</div><!-- end "cmt-cnt" -->
<?php } ?>
<div class="new-com-bt" id="<?php echo $m; ?>">
<span id="">Escribe un comentario ...</span>
</div>
<div class="new-com-cnt">
<a name="coment_box" id="coment_box">
<input type="hidden" id="name-com" name="name-com" value="<?php echo $_SESSION['MM_IdUser']; ?>" />
<input type="hidden" id="mail-com" name="mail-com" value="<?php echo 'xxxxxxx#gmail.com'; ?>" />
<input type="hidden" id="pic-com" name="pic-com" value="<?php echo ObtenerNombreFoto_Usuario($_SESSION['MM_IdUser']); ?>" />
<textarea class="the-new-com" placeholder="Ingresa tu comentario"></textarea>
<div class="bt-add-com">Publicar comentario</div>
<div class="bt-cancel-com">Cancelar</div>
</a>
</div>
My Js code:
<script type="text/javascript">
$(function(){
//alert(event.timeStamp);
$('.new-com-bt').click(function(event){
$(this).hide();
$('.new-com-cnt').show();
$('#coment_box').focus();
});
/* when start writing the comment activate the "add" button */
$('.the-new-com').bind('input propertychange', function() {
$(".bt-add-com").css({opacity:0.6});
var checklength = $(this).val().length;
if(checklength){ $(".bt-add-com").css({opacity:1}); }
});
/* on clic on the cancel button */
$('.bt-cancel-com').click(function(){
$('.the-new-com').val('');
$('.new-com-cnt').fadeOut('fast', function(){
$('.new-com-bt').fadeIn('fast');
});
});
// on post comment click
$('.bt-add-com').click(function(){
var theCom = $('.the-new-com');
var theName = $('#name-com');
var theMail = $('#mail-com');
var thePic = $('#pic-com');
if( !theCom.val()){
alert('¡Por favor escribe un comentario!');
}else{
$.ajax({
type: "POST",
url: "add-comment.php",
data: 'act=add-com&id_post='+<?php echo $id_post; ?>+'&name='+theName.val()+'&email='+theMail.val()+'&comment='+theCom.val()+'&pic='+thePic.val(),
success: function(html){
theCom.val('');
/*theMail.val('');
theName.val('');*/
$('.new-com-cnt').hide('fast', function(){
$('.new-com-bt').show('fast');
$('.new-com-bt').before(html);
})
}
});
}
});
});
I'll highly appreciate any help with this lack of knowledge & expertise.
Many thanks in advance.
please guys, have some posts which i outputted from my database and now i want to make a comment form for each post and the form will be submitted through ajax method, but my problem is
the ajax method works for only the first outputted post and the form inserts into the database the mysqli_num_rows($query). ie if mysqli_num_rows($query) is =5, the form inserts into 5 rows in the database.
the remaining outputted forms reloads the page when the submit button is clicked.
This is what I want to achieve:
I want each form to be submitted without reloading.
I want the form to be inserted in only one row for each.
Here is my code:
<?php
$con = mysqli_connect('localhost', 'root', '') or die ('error');
mysqli_select_db($con, 'test') or die ('error');
$query = mysqli_query($con, "SELECT * FROM testing");
while($sql = mysqli_fetch_array($query)){
$id = $sql['id'];
$post = $sql['post'];
echo "<p>".$id.". ".$post."<br>";
$pop_id = $id."pop";
?>
<style>
.plop {
display:none;
height:200px;
border-bottom:1px solid #000;
}
</style>
<a href="javascript:;" style="float:right
;margin:20px 20px;" onclick="document.getElementById('<?php echo $pop_id; ?>').style.display='block'">comment</a></p><br>
<div id="<?php echo $pop_id; ?>" class="plop">
close
<script type="text/javascript" src="jquery.js"></script>
<form id="my-form">
<input type="text" id="comment" name="comment" />
<input type="hidden" id="post" name="post" value="<?php echo $id; ?>" />
<input type="submit" id="submit" value="post" />
</form><div id="tutorial"></div>
<script type="text/javascript">
$(document).ready(function() {
$('#my-form').submit(function(e) {
e.preventDefault();
$.ajax({
method: "GET",
url: "dote.php",
data: $(this).serialize(),
beforeSend: function(){
$('#tutorial').html("<img src='progress-dots.gif' />");
},
success: function(status) {
$('#post').val('');
$('#tutorial').html("");
}
});
});
});
</script>
</div>
<?php
}
?>
Change the input type="submit" to type="button" and make ajax on click of button.
For eg.:
<script type="text/javascript" src="jquery.js"></script>
<form id="my-form">
<input type="text" id="comment" name="comment" />
<input type="hidden" id="post" name="post" value="<?php echo $id; ?>" />
<input type="button" id="submit" value="post" />
</form><div id="tutorial"></div>
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function(e) {
e.preventDefault();
$.ajax({
method: "GET",
url: "dote.php",
data: $("#my-form").serialize(),
beforeSend: function(){
$('#tutorial').html("<img src='progress-dots.gif' />");
},
success: function(status) {
$('#post').val('');
$('#tutorial').html("");
}
});
});
});
</script>
Above code will post the data without refreshing the page.
try this code
<?php
$con = mysqli_connect('localhost', 'root', '') or die ('error');
mysqli_select_db($con, 'test') or die ('error');
$query = mysqli_query($con, "SELECT * FROM testing");
while($sql = mysqli_fetch_array($query)){
$id = $sql['id'];
$post = $sql['post'];
echo "<p>".$id.". ".$post."<br>";
$pop_id = $id."pop";
?>
<style>
.plop {
display:none;
height:200px;
border-bottom:1px solid #000;
}
</style>
<a href="javascript:;" style="float:right
;margin:20px 20px;" onclick="document.getElementById('<?php echo $pop_id; ?>').style.display='block'">comment</a></p><br>
<div id="<?php echo $pop_id; ?>" class="plop">
close
<script type="text/javascript" src="jquery.js"></script>
<form id="my-form-"<?php echo $id; ?>>
<input type="text" id="comment" name="comment" />
<input type="hidden" id="post" name="post" value="<?php echo $id; ?>" />
<input type="submit" id="submit" value="post" />
</form><div id="tutorial"></div>
<script type="text/javascript">
$(document).ready(function() {
$('#my-form-<?php echo $id; ?>').submit(function(e) {
e.preventDefault();
$.ajax({
method: "GET",
url: "dote.php",
data: $(this).serialize(),
beforeSend: function(){
$('#tutorial').html("<img src='progress-dots.gif' />");
},
success: function(status) {
$('#post').val('');
$('#tutorial').html("");
}
});
});
});
</script>
</div>
<?php
}
?>
I'm currently using Ajax & jQuery for my chat, some might say its stupidly complex but so long as I can get it working.
It works on the first friend result, how ever not on the other. What its doing is the chat-load.php (Ajax part) is creating a new query to select the friends details, which are then being put into a result query on the chat.php page.
Therefore it only displays one "Working" chat window for the 1st friend. I tried grabbing the previous friend_id from the chat.php query and using it in the chat-load.php query but it didn't seem to notice any data.
Here is an example of what I'm getting, 1st result full width meaning its working, other results not full width as not working with ajax.
This is my current setup:
chat.php
<?php $users = $db->query("SELECT DISTINCT users.id, users.firstname, users.lastname,
message.date, message.time, message.message, message.recipient, message.sender
FROM users
JOIN friends
ON users.id IN (friends.sender, friends.recipient)
JOIN message
ON (users.id = message.sender)
AND 75 IN (message.sender,message.recipient)
ORDER BY message.date DESC, message.time DESC"); ?>
<!-- Friends query -->
<?php $users = $db->query("SELECT IF(friends.sender = ".$_SESSION["user"]["id"].", friends.recipient, friends.sender) AS user_id
FROM friends
WHERE friends.sender = ".$_SESSION["user"]["id"]."
OR friends.recipient = ".$_SESSION["user"]["id"].""); ?>
<?php while($friend = $users->fetch_object()): ?>
<?php $friends = $db->query("SELECT firstname, lastname, id FROM users WHERE id = $friend->user_id "); ?>
<?php while($FriendName = $friends->fetch_object()): ?>
<div class="chat-box">
<div class="header">
<?= $FriendName->firstname ?> <?= $FriendName->lastname ?> <?= $FriendName->id ?>
</div>
<script>
$(window).load(function() {
$("#chat-box, #messages").animate({ scrollTop: $(document).height() }, 1000);
});
</script>
<script>
function loadlink(){
$('#messages').load('chat-load.php',function () {
$(this).unwrap();
});
}
loadlink(); // This will run on page load
setInterval(function(){
loadlink() // this will run after every 5 seconds
}, 100);
</script>
<div id="messages" class="messages">
</div>
<div class="input-box">
<form id="SendForm" class="SendMsg" role="form" method="post">
<input type="text" id="s_firstname" name="s_firstname" class="MsgInputHidden" value="<?= $_SESSION["user"]["firstname"] ?>" />
<input type="text" id="s_lastname" name="s_lastname" class="MsgInputHidden" value="<?= $_SESSION["user"]["lastname"] ?>" />
<input type="text" id="sender" name="sender" class="MsgInputHidden" value="<?= $_SESSION["user"]["id"] ?>" />
<input type="text" id="r_firstname" name="r_firstname" class="MsgInputHidden"value="<?= $FriendName->firstname ?>" />
<input type="text" id="r_lastname" name="r_lastname" class="MsgInputHidden"value="<?= $FriendName->lastname ?>" />
<input type="text" id="recipient" name="recipient" class="MsgInputHidden" value="<?= $FriendName->id ?>" />
<input type="text" id="ip" name="ip" class="MsgInputHidden" value="<?= $_SERVER["REMOTE_ADDR"] ?>" />
<input type="text" id="date" name="date" class="MsgInputHidden" value="<?= date('Y-m-d') ."\n" ?>" />
<?php
$now = time();
$utc_time = $now - intval(date('Z', $now));
?>
<input type="text" id="time" name="time" class="MsgInputHidden" value="<?= '' . date('H:i:s', $now) . '' ?>" />
<input id="message" type="text" name="message" style="width: 100%; overflow: scroll;">
<input id="submit" class="submit" type="submit" name="submit" value="Submit" />
</form>
</div>
</div>
<script>
$("#submit").click(function(e) {
e.preventDefault();
var message = $("#message").val();
var s_firstname = $("#s_firstname").val();
var s_lastname = $("#s_lastname").val();
var sender = $("#sender").val();
var r_firstname = $("#r_firstname").val();
var r_lastname = $("#r_lastname").val();
var recipient = $("#recipient").val();
var ip = $("#ip").val();
var date = $("#date").val();
var time = $("#time").val();
var dataString = '&message=' + message + '&s_firstname=' + s_firstname + '&s_lastname=' + s_lastname + '&sender=' + sender + '&r_firstname=' + r_firstname + '&r_lastname=' + r_lastname + '&recipient=' + recipient + '&ip=' + ip + '&date=' + date + '&time=' + time;
$.ajax({
type:'POST',
data:dataString,
url:'sendmessagefriend.php',
});
});
</script>
<script>
$("#submit").click(function(e) {
$("#SendForm").get(0).reset();
});
</script>
<script>
$("#submit").click(function(e) {
$("#chat-box, #messages").animate({ scrollTop: $(document).height() }, 1000);
});
</script>
<?php endwhile; ?>
<?php endwhile; ?>
chat-load.php
<!DOCTYPE html>
<html>
<head>
<?php
session_start();
if(!isset($_SESSION["user"]) or !is_array($_SESSION["user"]) or empty($_SESSION["user"])
)
// redirect to index page if not superuser
header('Location: index.php');
?>
</head>
<body>
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','****','****','****');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT message, sender, recipient, date, time, IF(recipient = ".$_SESSION["user"]["id"].", 'received', 'sent') AS direction FROM message WHERE recipient IN (".$_SESSION["user"]["id"].", ".$friend->user_id.") AND sender IN (".$_SESSION["user"]["id"].", ".$friend->user_id.")";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
echo "<ul>";
echo "<li>";
echo "<span class='". $row['direction'] ."'>". $row['message'] ."</span>";
echo "<div class='clear'></div>";
echo "</li>";
echo "</ul>";
}
mysqli_close($con); ?>
</body>
</html>
Try using $.ajax() instead of $.load(). Set cache: false.
Example:
function loadlink(){
$.ajax({
url:'chat-load.php',
cache: false,
success: function(result){
$('#messages').html(result);
}
});
}
I have a button that calls an ajax once you submit but I need to add another input where you have to enter text and if that text is the same as the text found in the DB this button should execute the AJAX. How can this be done?
This is my AJAX code:
<script>
jQuery(function(){
jQuery(".canjear").click(function(e){
if(this.tagName==="A"){
e.preventDefault();
}
jQuery.ajax({
url: "index.php?option=com_cuphoneo&task=miscuponess.canjearCupon",
type: "POST",
data: {id:jQuery(this).data("id")},
success: window.location.href = "index.php?option=com_cuphoneo&view=miscuponess&layout=default"
});
});
});
</script>
This is my PHP/HTML button:
<div class="panel-boton-canjear">
<?php
foreach($campos_extra as $value){
if($value->id == 17){
if(!empty($value->value)){
?>
<input class="canjear btn" type="button" value="<?php echo JText::_('COM_CUPHONEO_BOTON_CANJEAR'); ?>" data-id="<?php echo $valor->item_id; ?>" />
<?php
}
}
}
?>
</div>