So im making a "delete" button to my commentsystem..
I want to make it smart, so it should run a ajax call to remove the comment.
Now I have tried out myself, this and have gotten this far:
<?php
echo "<a href='#' onclick='javascript:DoCommentWallRemove()' title='ta bort inlägg'> <span class='removeWallComment'></span> </a>";
?>
<script type="text/javascript">
function DoCommentWallRemove(){
var wrapperId = '#profileWall';
$.ajax({
type: "POST",
url: "misc/removeWallComment.php",
data: {
value: 'y',
commentwallid : "<?php echo $displayWall['id']; ?>",
BuID : "<?php echo $v['id']; ?>",
uID : "<?php echo $showU['id']; ?>"
},
success: function(msg){
alert(msg);
}
});
}
</script>
Now as my comments shows in a while(), I have placed the JS function is right under the link, so it should grab the actual comment id, but instead it gives the same ID to every comment.
But when i do a normal php <?php echo $displayWall['id']; ?> it shows different comment ids like it should do in the javascript.
I would suggest a similar solution to GuidoH, but with a few minor changes.
PHP Code for the Comment Thread:
<form method="post" action="misc/removeWallComment.php">
<input type="hidden" name="value" value="y" />
<input type="hidden" name="BuID" value="<?php echo $v['id']; ?>" />
<input type="hidden" name="uID" value="<?php echo $showU['id']; ?>" />
<div id="commentList">
<?php
foreach( $comments as $c ){
echo '<div id="comment'.$c['id'].'">';
echo $c['commentBody'];
echo '<input class="delButton" type="submit" name="'.$c['id'].'" value="Delete Comment" />';
echo '</div>';
}
?>
</div>
</form>
This will render as:
<form method="post" action="misc/removeWallComment.php">
<input type="hidden" name="value" value="y" />
<input type="hidden" name="BuID" value="ThisIsThe_BuID" />
<input type="hidden" name="uID" value="ThisIsThe_uID" />
<div id="commentList">
<div id="comment001">
This is Comment Number One
<input class="delButton" type="submit" name="001" value="Delete Comment" />
</div>
<div id="comment002">
And, This is Comment Number Two
<input class="delButton" type="submit" name="002" value="Delete Comment" />
</div>
</div>
</form>
In the Javascript for the page holding the Comment thread:
<script>
$(document).ready(function(){
/* Add a Handler for the Delete Button */
$('div#commentList input.delButton').click(function(e){
/* Stop the Link working */
e.preventDefault();
/* Alias the main jQuery Objects */
$this = $(this);
$comment = $this.closest('div');
$form = $comment.closest('form');
/* Grab the Comment Number from the Button's NAME attribute */
commentID = $this.attr('name');
/* Perform the AJAX Action */
$.ajax({
url : $form.attr('action') ,
type : 'POST' ,
data : {
'value' : $form.find( 'input[name="value"]' ).val() ,
'commentwallid' : commentID ,
'BuID' : $form.find( 'input[name="BuID"]' ).val() ,
'uID' : $form.find( 'input[name="uID"]' ).val() ,
'mode' : 'ajax'
} ,
dataType : 'text' ,
complete: function( XHR , status ){
if( $.trim(status).toLowerCase()=='success'
&& $.trim(XHR.responseText).toLowerCase()=='comment deleted' ){
/* Success - Hide, then Remove the Comment */
$comment.hide().remove();
}else{
/* Something Went Wrong */
alert('Deleting Comment #'+commentID+' Failed');
}
}
});
});
});
</script>
In the misc/removeWallComment.php file:
if( $_POST['mode']=='ajax' ){
/* Perform the Action. Return 'Comment Deleted' is Successful */
}else{
/* This is to Extract the Comment ID from the "Delete Comment" button */
$_POST_REV = array_flip( $_POST );
$_POST['commentwallid'] = $_POST_REV['Delete Comment'];
/* Perform the Action.
Return the Full Page, or Redirect, you want Non-Javascript Users to See. */
}
NOTE:
This advice is based on the assumption he BuID and uID variables are the same for any delete action performed by the user from the same page.
Edited:
Updated to provide Graceful Degradation in the event that the user does not allow Javascript to run, and to extract a number of variables from the HTML FORM, (rather than have to code them in twice).
Eww, that's just gross! You probably want something like this:
function removeComment(id, obj) {
$.post('misc/removeWallComment.php', {id: id}, function(msg) {
alert(msg); // or do some useful stuff,
// like remove the comment from the page
// with 'obj' you'll know which comment to remove :)
});
}
And then just something like this for each comment:
delete comment
Related
I have working code for posting data to DB using PHP and Jquery without refreshing the page.
But however, I could only use 1 form with the given code, if I'm to add another form with different variables both the forms getting submitted.
My code goes as:
index:
Query starts
$countlikes = 1;
$countdislikes = 1;
<form data-id='<?= $countlikes?>' action="likeinsert" method="post" id="myform<?= $countlikes?>">
<input type="hidden" id="fid<?= $countlikes?>" name="fid" value="<?php echo $f_id; ?>" />
<input type="hidden" id="uid<?= $countlikes?>" name="uid" value="<?php echo $u_id; ?>" />
<button style="border:none; background:transparent;" data-toggle="tooltip" data-placement="right" title="Like" class="up"><i class="fa fa-thumbs-o-up"></i><?= $f_likes; ?></button>
</form>
<form data-id='<?= $countdislikes?>' action="dislikeinsert" method="post" id="myform<?= $countdislikes?>">
<input type="hidden" id="fid<?= $countdislikes?>" name="fid" value="<?php echo $f_id; ?>" />
<input type="hidden" id="uid<?= $countdislikes?>" name="uid" value="<?php echo $u_id; ?>" />
<button style="border:none; background:transparent;" data-placement="right" data-html="true" title="DisLike" class="down"><i class="fa fa-thumbs-o-down"></i><?= $f_dislikes; ?></button>
</form>
$countlikes ++;
$countdislikes ++;
Query Ends
<script src='https://code.jquery.com/jquery-2.1.3.min.js'></script>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script>
$(document).on('submit','form',function(e){
e.preventDefault();
let id = $(this).data('id');
$.post(
'likeinsert.php',
{
fid: $("#fid"+id).val(),
uid: $("#uid"+id).val()
},
function(result){
if(result == "success"){
$("#result").val("Values Inserted");
} else {
$("#result").val("Error");
}
}
);
});
</script>
<script>
$(document).on('submit','form',function(e){
e.preventDefault();
let id = $(this).data('id');
$.post(
'dislikeinsert.php',
{
fiid: $("#fid"+id).val(),
uiid: $("#uid"+id).val()
},
function(result){
if(result == "success"){
$("#result").val("Values Inserted");
} else {
$("#result").val("Error");
}
}
);
});
</script>
When I to click on any form button, both forms are getting submitted.
It is happening, because you are adding two submit event listeners on both forms, so when you submit one form, both jquery scripts are getting executed.
To prevent this, add form's unique ids to your event listeners (in your case they are myform1 and myform1, but you should make them unique), somewhat like this:
$(document).on('submit','form#dislikesForm',function(e){
request to dislikeinsert.php ...
$(document).on('submit','form#likesForm',function(e){
request to likeinsert.php...
I would like to "add to card" products using URL like "https://www.example.com/?add-to-cart=ProductID" but the problem is I will pass an array of ProductID that was in my javascript code. I would like to ask if we can pass an array of productID in "add-to-cart" parameter?
I tried this solution below:
<script>
$(document).on('click', '.order-btn', function (e) {
e.preventDefault();
var selected_items = $('.selected_items').val();
items = selected_items.split(',');
for (x of items) {
$.ajax({
url: '<?php echo site_url() . '/?add-to-cart=' ?>' + x,
method: 'get',
async: true,
success: function (res) {
window.location.href = "<?php echo site_url('food-and-catering-cart'); ?>";
}
})
}
})
</script>
<input class="selected_items" type="text" name="items" value="1,2,3,4)">
<div class="order">
<p class="hope_btn1">
<a class="order-btn" href="<?php echo site_url('food-and-catering-cart'); ?>">ORDER NOW</a>
</p>
</div>
When I checked the cart it only displayed two items and sometimes 1 item only.
change input value like this
<input class="selected_items" type="text" name="items" value="1,2,3,4">
then using explode() function breaks the input string into an array in php.
how to use explode function
You should create a form with a Submit Button and it will pass the form inputs through url:
<form id="add-to-cart-form" method="get" action="youraction" >
<input type="hidden" name="products[]" value="1" />
<input type="hidden" name="products[]" value="2" />
<button type="submit">Add To Cart</button>
</form>
And then you can get that in $_GET super global like an array
$GET['products'] = Array(1,2)
I have a page with a POST form, when I submit the form the details are updated in a database.
And I have another page where I use AJAX TAB, which means I load the first page with AJAX, when I do this and use the Form, the details are not updated in the database.
I would appreciate help.
<?php
if( isset($_POST['newcst']) )
{
/*client add*/
//getting post from user add form
$c_name = $_POST['c_name'];
$c_adress = $_POST['c_adress'];
$c_idnum = $_POST['c_idnum'];
$c_phone = $_POST['c_phone'];
$c_mail = $_POST['c_mail'];
echo $c_num;
//insert client into SQL
$wpdb->insert('se_clients',array(
'c_name' => $c_name,
'c_adress' => $c_adress,
'user_id'=>$cur_id,
'c_num'=>$c_idnum,
'c_phone'=>$c_phone,
'c_mail'=>$c_mail,
));
}
?>
<html>
</head>
<body>
<div id="newcst">
<form action="" method="post">
<label>Full name:</label>
<input type='text' name='c_name' /><br><br>
<label>ID: </label>
<input type='text' name='c_idnum' /><br><br>
<label>PHONE:</label>
<input type='text' name='c_phone' /><br><br>
<label>ADRESS: </label>
<input type='text' name='c_adress' /><br><br>
<label>EMAIL: </label>
<input type='text' name='c_mail' /><br><br>
<input name="newcst" type="submit" value="create">
</form>
</div>
</body>
</html>
Ajax tab:
$(document).ready(function() {
$("#nav li a").click(function() {
$("#ajax-content").empty().append("<div id='loading'><img src='http://wigot.net/project/wp-content/themes/projthem/vendor/images/loader.gif' alt='Loading' /></div>");
$("#nav li a").removeClass('current');
$(this).addClass('current');
$.ajax({ url: this.href, success: function(html) {
$("#ajax-content").empty().append(html);
}
});
return false;
});
$("#ajax-content").empty().append("<div id='loading'><img src='http://wigot.net/project/wp-content/themes/projthem/vendor/images/loader.gif' alt='Loading' /></div>");
$.ajax({ url: 'invoice', success: function(html) {
$("#ajax-content").empty().append(html);
}
});
});
hover(), click(), bind(), on() and others works only after reloading page.
So you can use live()
or
$(document).on('click', 'element', function () {
...
});
I found the solution, you need to add the PHP code that is responsible for entering data to the database on the main page that contains the AJAX and not the page with the form itself.
I have a bunch of records from a database that I am displaying on a page. Each record has their own form with an update and delete button. I'm using JQuery ajax to send the data to a PHP page to process the form.
The script works fine the first time I push any one of the buttons on any of the forms, but when I push another button on any of the forms (or even the same button on the same form) the ajax request doesn't send any of the data to the PHP page.
Code I'm using to output data on page:
<?php
foreach($records as $data) {
?>
<form>
<input type="number" name="et" step="0.01" value="<?php echo $data->et; ?>" />
<input type="hidden" name="token" value="<?php echo $token; ?>" />
<input type="hidden" name="id" value="<?php echo $data->et_id; ?>"/>
<input type="submit" name="update" value="Update" />
<input type="submit" name="delete" value="Delete" />
</form>
<?php
}
Javascript:
$(document).ready(function() {
var buttonName;
$('input[type=submit]').click('click', function() {
buttonName = $(this).attr('name');
});
$('form').on('submit', function(e) {
e.preventDefault();
var values = $(this).serializeArray();
console.log(values);
if(buttonName == 'delete') {
var message = confirm('Are you sure you want to delete this record?\n\n You can\'t get it back once you do.');
} else {
message = true;
}
if(message) {
$.post('submit/raw_et.php', {et: values[0].value, token: values[1].value, id: values[2].value, button: buttonName}, function(r) {
console.log(r);
});
}
});
});
PHP Snippet:
echo $_POST['button'];
echo $_POST['et'];
echo $_POST['id'];
The "values" variable in the javascript always has the correct data, but the ajax fails to send any data after the first time a button is pushed and the results return blank.
I don't understand why it won't send the data. Am I missing something really easy, or is it something more complicated?
Edit:
I've taken out the tables in the html, but still get the same results.
you are developing in a completely wrong pattern, instead of defining form inside tr, use record id and register event for clicking buttons:
<?php
foreach($records as $data) {
?>
<tr>
<td><input type="number" name="et" step="0.01" value="<?php echo $data->et; ?>" /></td>
<input type="hidden" name="token" value="<?php echo $token; ?>" />
<input type="hidden" name="id" value="<?php echo $data->et_id; ?>"/>
<td><a class='edit' meta-id="<?php echo $record; ?>">edit</a></td>
<td><a class='delete' meta-id="<?php echo $record; ?>">delete</a></td>
</tr>
<?php
}
?>
And now, try to register all buttons onclick for delete and edit.
$(".edit").click(function() {
var record = $(this).attr("meta-id");
$.post("edit uri" , {record : record , otherparam: valueofit} , function(result) {
alert(result);
});
});
$(".delete").click(function() {
var record = $(this).attr("meta-id");
$.post("delte uri" , {record : record} , function(result) {
alert(result);
});
});
You can expand the concept as you want, for less adding class to buttons or so on.
I need to perform another AJAX Form Post from within the first forms success function.
Example, this does 2 AJAX requests.
Search Movie => Pick Movie Wanted => View Specific Movie Details
I am able to load the results into a div <div id="results"></div> just fine but once I select a movie title it isnt performing another AJAX Request, the request goes to the main window.
Here is the initial search page that handles the results.
<script type="text/javascript">
$(document).ready(function(){
$("#searchtitle").submit(function() {
var id = $(this).children('input[name="thetitle"]').attr('value');
$.ajax({
type: "POST",
url: "s.php",
data: $('#searchtitle').serialize(),
cache: false,
success: function(data){
$('#status').html(data);
}
});
return false;
});
});
</script>
<form id="searchtitle">
<input type="text" name="thetitle" />
<input type="submit" name="submit" class="button expand postfix" value="Search" />
</form>
<div id="status"></div>
s.php which returns results within #results
<?php
if(empty($_POST['thetitle'])) {
?>
<div class="alert-box error">
<div class="alert-error"></div>
Error: Nothing Found
</div>
<?php
}
if(!empty($_POST['thetitle'])) {
$myid = strtoupper($_POST['thetitle']);
$searchReults = $tmdb_V3->searchMovie($myid,'en');
?>
<?php
foreach($searchReults['results'] as $result) {
?>
<form class="sform">
<input type="hidden" name="mid" value="<?php echo $result['id']); ?>" />
<h5><?php echo $result['title']; ?></h5>
<span class="mreleased">Year: <?php echo $result['year']; ?></span>
<input type="submit" class="button" value="Select">
</form>
<?php
}
}
?>
This is the code that will post the results from s.php
<script type="text/javascript">
$(".sform").submit(function () {
$.ajax({
type: 'POST',
url: 'sx.php',
data: $(this).closest("form").serialize();
success: function (response) {
$('#status').load(response);
$('#status').find('script').each(function (i) {
eval($(this).text());
});
}
});
return false;
}
</script>
I have tried putting this within s.php, within the bottom of the initial search page, in the head of the initial page and no luck, it submits fine just not the sx.php where it should.
In s.php the statement:
<input type="hidden" name="mid" value="<?php echo $result['id']); ?>" />
Should be:
<input type="hidden" name="mid" value="<?php echo $result['id']; ?>" /> //remove extra bracket
In your javascript code in s.php there are some typos:
data: $(this).closest("form").serialize(); // here should be comma not semicolon
After return false you should close the script properly } should be });.
And since you are trying to submit the dynamic content $(".sform").submit(function () will not work. You should use on for dynamic contents. So the correct script would be:
<script type="text/javascript">
$(document).on('submit', '.sform', function () {
$.ajax({
type: 'POST',
url: 'sx.php',
data: $(this).closest("form").serialize(),
success: function (response) {
$('#status').load(response);
$('#status').find('script').each(function (i) {
eval($(this).text());
});
}
});
return false;
});
</script>
I have checked and verified in my localhost (with a simple setup). It is making both ajax request. Hope this helps!