add submit to delete comment using ajax , php - ajax

Hi, I use a php code to view the all comments to any post from my sql and I want to add a submit button to every comment in order to delete it without refreshing the page, I mean using AJAX i don't know how to write that codes and connect it with html codes i want add submit like this :
<form>
<input type="submit" id="deletecomment">
</form>
and connected it with AJAX and delete.php page to delete the comment (ajax,delete.php)???????
this is my codes
$result = mysql_query ("select * from post_comments WHERE link ='$getlink' order by link asc");
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$link = $row['link'];
$time = $row['time'];
$content = nl2br($row['content']);
$name = ($row['link'] != '') ? '<h3 style="color:blue">'.$row['name'].'</h3>' : $row['name'];
$imge = $row['imge'];
echo '
<div class="commentuserbackground">
<img src="'.$imge.'" width="30px" height="30px">
<div id="comment-'.$id.'" class="username1">'.$name.'</div>
<div class="username2">'.$content.'</div><div class="commenttime"><h4 style="color:#5a5a5a">'.$time.'</h4>
</div></div>';
}

If you already have the jquery lib included in your html, you could do something like this:
# html page
<button data-id="1" class="delete_comment" /> # no need to wrap in form
# At the bottom of the body tag
$(".delete_comment").click(function(e){
e.preventDefault();
var $button = $(this), $comment = $button.parent(), id = $button.data("id");
$.ajax({
type: 'DELETE',
url: "/path/to/comment/" + id,
success: function(){ $comment.remove(); }
});
});

Related

URL::to('/') echoed as string (Laravel)

I'm working with my project which get new orders and append to DOM with jQuery.
jQuery
setInterval(function() {
$.ajax({
type:'POST',
url:'{{URL::to('/')}}/orders',
success:function(data)
{
let obj = JSON.parse(data)
let ordersDiv = $('#ordersDiv');
let queueCount = $('#queueCount');
queueCount.html(obj.count);
ordersDiv.html(obj.data);
}
});
}, 15000);
Controller
//some code here
$data .= "<a class=\"example-image-link\"
href=\"{{URL::to('/')}}/users/uploads/profiles/{{strlen($biker-
>picture_file_path)>0?$biker>picture_file_path:'avatar.png'}}\">
<img src=\"URL::to('/')/users/uploads/profiles/$biker-
>picture_file_path:.'avatar.png'\" data-toggle=\"tooltip\"
title=\"HiBes Biker\">
</a>";
//more code here
My problem is that I'm getting this result:
<a href=\"{URL::to('\/')}\/order-details\/3159\">Details<\/a>
I expect a result something like this:
<a href=\"http://127.0.0.1:8000/order-details\/3159\">Details<\/a>
The reason your URLs still contain the placeholders is you are building HTML in your controller, not your view.
Ideally, you should switch this logic into the view, where the {{ $var }} syntax will work.
Create a new blade file bikerimage.blade.php
#foreach($bikers as $biker)
<a class="example-image-link"
href="{{URL::to('/')}}/users/uploads/profiles/{{ $biker->picture_file_path ?: 'avatar.png' }}">
<img src="{{ URL::to('/')}}/users/uploads/profiles/{{ $biker->picture_file_path ?: 'avatar.png' }}"
data-toggle="tooltip"
title="HiBes Biker"
>
</a>
#endforeach
Then in your controller, you can do something like
//some code here
$data = view('partials/bikerimage.blade.php', ['bikers' => $bikers])->render();
return [
'html' => $data,
];
This means you can still return the data as part of an ajax call, without having to build HTML in your controller.

Having issues submitting form via AJAX on WordPress with reCAPTCHA

I've spent a good few hours trying to Google my way out of this, and I keep coming up with one issue or another. I'm getting myself wrapped up in knots and I am hoping that someone can help me by giving me a metaphorical slap around the face and showing me how the hell to do this properly.
Ok ... so I have a page on my front end that is inserted by a shortcode. This form is essentially a sort of AMA (Ask Me Anything) form, which I am using to create posts in my Admin area. Visitors enter their question, name and email, and submit the form to me via AJAX. The submissions are saved into the WordPress database under an ama custom post type, and an email is sent to me via wp_mail because I have an SMTP plugin installed that routes all requests for wp_mail through there. I have CMB2 installed on my website, and have keys for reCAPTCHA saved there.
So far, so good.
I had a working form with CMB2 fields, but CMB2 doesn't seem to support reCAPTCHA (otherwise it worked fine). So I decided to start from scratch and write my own form since it was just three fields that I wanted to submit. What could possibly go wrong, right?
Here's my Franken-code.
<?php
function ccdClient_shortcode_amaForm( $atts ) {
// Parse attributes
$atts = ( shortcode_atts( array(
'id' => uniqid('ccdClient_amaForm_'),
), $atts, 'ama_form' ) );
$rcKey = cmb2_get_option( 'ccdtheme_settings_apikeys', '_ccdclient_themesettings_apikeys_captcha_sitekey' );
$form = '
<form id="' . $atts['id'] . '" name="' . $atts['id'] . '" method="post" action="">
<div class="amaError"></div>
<div class="amaForm-field-question amaForm-field">
<p><label for="question">Your Question</label></p>
<p><textarea id="question" name="question" tabindex="1"></textarea></p>
</div>
<div class="amaForm-fieldGroup amaForm-groupTwo">
<div class="amaForm-field-name amaForm-field">
<p><label for="name">Your Name</label></p>
<p><input type="text" id="name" name="name" tabindex="2" /></p>
</div>
<div class="amaForm-field-email amaForm-field">
<p><label for="email">Your Email</label></p>
<p><input type="email" id="email" name="email" tabindex="3" /></p>
</div>
</div>
<div class="amaForm-fieldGroup amaForm-groupTwo">
<div class="amaForm-field-recaptcha amaForm-field amaForm-recaptcha">
<div class="g-recaptcha" data-sitekey="' . $rcKey . '"></div>
</div>
<div class="amaForm-field-submit amaForm-field amaForm-submit">
<input type="submit" value="Publish" id="submit" name="submit" />
</div>
</div>
</form>
<script>
$(document).ready(function() {
// Get form
var amaForm = $("#' . $atts['id'] . '");
// Get messages div
var amaError = $("#' . $atts['id'] . ' .amaError");
// Set data
var amaData = { "action" : "ama_form_process"}
var options = {
url: "'. admin_url( 'admin-ajax.php' ) .'",
type: "post",
dataType: "json",
data: amaData,
success : function(responseText, statusText, xhr, $form) {
$(amaError).html("Your form has been submitted successfully");
},
};
//Set submit function
amaForm.on("submit", function(e) {
//Prevent default form behavior
e.preventDefault();
// Serialise form data
//Post via AJAX
$.ajax(options)
.done(function(response) {
// Make sure that the amaError div has the "success" class.
$(amaError).removeClass("error");
$(amaError).addClass("success");
// Set the message text.
$(amaError).text(response);
})
.fail(function(data) {
// Make sure that the amaError div has the "error" class.
$(amaError).removeClass("success");
$(amaError).addClass("error");
// Set the message text.
if (data.responseText !== "") {
$(amaError).text(data.responseText);
} else {
$(amaError).text("Oops! An error occured, and your message could not be sent.");
}
});
});
});
</script>';
return $form;
}
add_shortcode('ama_form', 'ccdClient_shortcode_amaForm');
function ama_form_process() {
// If the form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Include WordPress files
include_once '../../../../../wp-includes/wp-load.php';
// Set reCaptcha private key
$recaptchaKey = cmb2_get_option( 'ccdtheme_settings_apikeys', '_ccdclient_themesettings_apikeys_captcha_secretkey' );
// If the Google Recaptcha box was clicked
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){
$captcha = $_POST['g-recaptcha-response'];
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=" . $recaptchaKey . "&response=" . $captcha);
$obj = json_decode($response);
// If the Google Recaptcha check was successful
if($obj->success == true) {
$question = strip_tags( trim( $_POST['question'] ) );
$name = strip_tags( trim( $_POST["name"] ) );
$name = str_replace( array("\r","\n"), array(" "," "), $name);
$email = filter_var( trim( $_POST["email"] ), FILTER_SANITIZE_EMAIL );
if ( !$name || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Add the content of the form to $post as an array
$post = array(
'post_title' => $question,
'post_status' => 'pending', // Could be: publish
'post_type' => 'ama', // Could be: `page` or your CPT
'meta_input' => array(
'_ccdclient_ama_name' => $name,
'_ccdclient_ama_email' => $email,
),
);
wp_insert_post($post);
echo 'Saved your post successfully! :)';
$recipient = get_option('admin_email');
$subject = "New question from $name";
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$question\n";
$email_headers = "From: $name <$email>";
wp_mail( $recipient, $subject, $email_content, $email_headers );
}
// If the Google Recaptcha check was not successful
else {
echo "Robot verification failed. Please try again. Success:" . $response;
}
}
// If the Google Recaptcha box was not clicked
else {
echo "Please click the reCAPTCHA box.";
}
}
// If the form was not submitted
// Not a POST request, set a 403 (forbidden) response code.
else {
echo "There was a problem with your submission, please try again.";
}
}
add_action("wp_ajax_ama_form_process", "ama_form_process");
//use this version for if you want the callback to work for users who are not logged in
add_action("wp_ajax_nopriv_ama_form_process", "ama_form_process");
As you can guess, I have looked at about a dozen or so pages and combined the efforts of each of them, thus overwriting parts that would perhaps have worked and confused myself no end, and so am resorting to here to preserve what is left of my sanity.
EDIT: Apologies. Whilst I copied the code, I wasn't specific on what issues I was facing. Goes to show the extent I was frustrated.
I have had a number of issues with this code. Currently, when I submit the form, it keeps the same URL but returns a 404 error page. However, it has previously told me that it cannot recognise functions - and therefore couldn't run - such as cmb2_get_option (which is a modification of get_option that specifically works with CMB2 options pages) and wp_insert_post. The latter error (ie: wp_insert_post) came up when the secret key was hard-coded into the script and not called from the get_option function.

like option in a website using codeigniter

I have a problem like this. I am creating a website using codeigniter. In it, users can ask questions and "like" them. All questions should be shown in the website by descending Order by the amount of like. If the first questions has 20 like and the second one has 18 and then, a person likes the second question ,then it has 19 likes it should stay in same place if it got 21 likes it should come to the top.
How can i do this?
I search internet so many times but i couldn't able to find out something suitable.
This is my question table.
In your view you have something like that i guess:
<input type="button" class="likeAction" data-questid="<?=$question->id?>" value="Like">
In jquery, when a like button is cliked, read the value of the data(questid) and you should start an ajax query to the likeQuestion method.
I don't know your code so I just write as i do it...
In your controller :
public function likeQuestion($quest_id){
$json = (object) []; //init an object, easier to use with json
$json->result = "error";
$res = $this->question_model->like($quest_id);
if($res){
$json->result = "success";
//read the number of like of the question
$json->num_like = $this->question_model->countLikeNumber($quest_id);
}
header("Content-type:application/json");
echo json_encode($json);
}
In your model :
public function like($quest_id){
$this->db->set('likes', 'likes+1', FALSE); //the false is important here
$this->db->where('id', $quest_id);
$this->db->update('question');
}
public function countLikeNumber($quest_id){
$this->db->select('*');
$this->db->from('question');
$this->db->where("id", $quest_id);
$query = $this->db->get();
return $query->num_rows();
}
I'll assume that you want to send your [adding like] request via ajax, and then ordering your list according the number of likes for each question, and I'll cover basically your front-end code reading the comments, so:
Your view should be like this:
<ul class="questions">
<li id="question_item_<?= $id ?>">
...
<span id="likes_<?= $id ?>"><?= $likesNum ?></span>
<button class="likeBtn" data-id="<?= $id ?>" >Like</button>
</li>
<li id="question_item_<?= $id ?>">
...
<span id="likes_<?= $id ?>"><?= $likesNum ?></span>
<button class="likeBtn" data-id="<?= $id ?>" >Like</button>
</li>
...
</ul>
Your Ajax Call:
$('.likeBtn').click(function(){
var $clicked = $(this),
questionID = $clicked.data('id'),
likesNum = $('li#question_item_' + questionID).find('span').text;
$.ajax({
url: 'PATH_TO_YOUR_CONTROLLER_METHOD_addingLike',
data: {'question_id': questionID},
dataType: 'json',
success: function(returnedData){
if(returnedData.status === 'success'){
$('li#question_item_' + questionID).find('span').text(parseInt(likesNum ) + 1);
reorderQuestions(returnedData.ids);
}
},
error: function(error){
console.log(error.resposeText);
}
});
});
/* Reordering your list at the front-end base,
* preventing server resources highly consumptions
*/
function reorderQuestions(ids){
var newUL = $('<ul class="questions">');
$each(ids, function(index, id){
newUL.append($('li#question_item_' + id));
});
$('ul.questions')replaceWith(newUL);
}
Your Controller Should behave like this:
public function addingLike($question_id){
# Increasing the number of like for question holding the specific id,
# Fetching all your questions ids ordered by the number of its likes
# Return a json object ['status': success, 'ids': [array_of_ids_ordered_by_likes]]
}

How to open contact form 7 by using wordpress ajax

I am using contact from 7 plugin and my question is to open contact form 7 in popup via wordpress admin ajax but my code not working. Only popup open but contact form 7 not submitting. It is redirecting in admin ajax url and returns 0.
Here is the code that i am doing in functions.php
<?php
add_action('wp_head', 'my_action_popup_cf7_javascript');
function my_action_popup_cf7_javascript() {
?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
$('.myajaxcarrer').click(function(){
//alert(1);
var mydata = $(this).data();
$(".overlay").fadeIn('slow');
var data = {
action: 'my_action_popup_cf7',
//whatever: 1234,
id: mydata.id
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
//console.log(ajaxurl);
$('.item').removeClass('active');
$('[data-id=' + mydata.id + ']').parent().addClass('active');
$.post('<?php echo esc_url( home_url() ); ?>/wp-admin/admin-ajax.php', data, function(response) {
// alert('Got this from the server: ' + response);
$('#testcarrer').html(response);
var offset = $(window).scrollTop();
$(".career-form").css("top", offset+50 );
$('.closeBtn').click(function(e){
e.preventDefault();
$(".overlay").fadeOut('slow');
$('.career-form').css("top", -1000+"%" )
});
});
});
});
</script>
<?php
}
add_action('wp_ajax_my_action_popup_cf7', 'my_action_popup_cf7_callback');
add_action( 'wp_ajax_nopriv_my_action_popup_cf7', 'my_action_popup_cf7_callback' );
function my_action_popup_cf7_callback() {
global $wpdb; // this is how you get access to the database
//$whatever = 'ID=> '. $_POST['id'];
//echo $whatever;
?>
X
<h3>Apply Now</h3>
<div class="formBox">
<?php echo do_shortcode('[contact-form-7 id="905" title="My New Carrer Form"]'); ?>
</div>
<?php
exit(); // this is required to return a proper result & exit is faster than die();
}
And code in page template file is
<span class="applyBtn"><a class="myajaxcarrer" data-id="903">Apply Now</a></span>
<div class="overlay"></div>
<div class="career-form">Ajax result Load here..</div>
And js code is below.
$('.applyBtn').click(function(e){
e.preventDefault();
var offset = $(window).scrollTop();
$(".overlay").fadeIn('slow');
$(".career-form").css("top", offset+50 )
});
$('.closeBtn, .overlay').click(function(e){
e.preventDefault();
$(".overlay").fadeOut('slow');
$('.career-form').css("top", -1000+"%" )
});
You can open it by echoing do_shortcode('[form name with id]'); it in you php function.

Jquery returning all to much data I only want the table

Hi im attempting to use jquerys ajax to update a form after a GET request, I simply want the table to update but it send through the page headers as well.
First Here is my script, its small so i will include it all,
var wishorder = {
init: function(config){
this.config = config;
this.bindEvents();
},
bindEvents: function(){
this.config.itemSelection.on('click',this.addWish);
},
addWish: function(e){
console.log('working');
var self = wishorder;
$.ajax({
url: $(this).attr('href'),
type: 'GET',
data: {
sku: $(this).data('sku'),
action: $(this).data('action'),
qty: $(this).data('qty')
},
success: function(results){
//here is where is would like to repopulate the div
//but its outputting the whole page
console.log(results);
}
});
e.preventDefault();
}
};
wishorder.init({
itemSelection: $('#carttable a'),
form: $('#cartfrm')
});
I can see that it is returning the results i want but it wraps it in html as in page header.
Here are the php function its calling.
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_GET['action'] == 'move'){
list($sp_type, $pid) = $this->parse_sku($_GET['sku']);
$qty = (filter_var($_GET['qty'], FILTER_VALIDATE_INT, array('min_range' >= 1)))?$_GET['qty']:1;
$q = "CALL add_to_wish_list('$this->uid', '$sp_type', $pid, $qty)";
$this->query($q);
$q = "CALL remove_from_cart('$this->uid', '$sp_type', $pid)";
$this->query($q);
$q = "CALL get_shopping_cart_contents('$this->uid')";
$this->query($q);
$this->read();
$this->outcart();
exit();
}
and the outcart function wich generates the html for the div
function outcart(){
echo "<div id=\"cartcont\" class=\"cartitems\"><form action=\"/cart.php\" method=\"post\"><table id=\"carttable\"><tr class=\"theads\"> <th class=\"titm\" >Item</th> <th >Quantity</th> <th >Price</th> <th>Subtotal</th> <th class=\"topt\" >Options</th>";
$total = 0;
while($row = $this->_result->fetch_object()){
$price = $this->get_just_price($row->price, $row->sale_price);
$subtotal = $price * $row->quantity;
$total += $subtotal;
echo "<tr class=\"tdata\">
<td>".$row->category." :: ".$row->name."</td>
<td><input type=\"text\" name=\"quantity[".$row->sku."]\" value=\"$row->quantity\" size=\"2\">
<td>$".$price."</td>
<td>$".number_format($subtotal, 2)."</td>
<td> Move To Wishlist <br> Remove From Cart </td>";
}
echo "</tr><tr class=\"ttotals\"><td colspan=\"3\" ><strong id=\"carttotal\">TOTAL:</strong></td>
<td colspan=\"2\" > $".number_format($total,2) ." </td>
</tr>";
echo "</table>";
echo "<div id=\"cartmnbtns\"><p><input type=\"submit\" value=\"UPDATE QUANTITIES\" class=\"buttoncart1 green\"><br>Checkout</p> </div></form>";
}
So i just want to repopulate the table really or the cartcont div with the results, where am missing the point?
The page you're calling is url: $(this).attr('href') and that's a web-page you're just on with all headers and stuff... You have to put your functions in a separate .php file that doesn't contain a whole web-page frame and only outputs the text you want.
If that's not possible then create in your success callback function with document.createDocumentFragment(), pass the whole response inside the fragment and pull out your stuff you need with something like myHTML = docFrag.getElementsByTagName('div')[0] and then pass this with append to your form.
You might also want to set something like contentType: "text/plain; charset=utf-8" in your ajax call.
By the way: If you're not using the convenience of parsing variables inside strings you might want to use a different way (the other quotes) of writing your strings, as it's then faster, so:
echo '<tr class="tdata">...'

Resources