I have blog post list and that post have comments. Posts and comments i loop with foreach from database.So i have problem when i want to create new comment via ajax. I have form and one hidden field for holding post id.
When from jquery i try to access to that element post_id is all time the some. I try on submit to debug with alert to see witch post_id will be returned. All time return 270. And when i click to other post comment submit id is not changed.
Posts and comments
<?php foreach($posts as $post): ?>
<h1><?= $post->title; ?></h1>
<p><?= $post->text; ?></p>
<?= if($comments = postComments($post->id): ?>
<?= foraech($comments as $comment): ?>
<form id="post_add">
<input type="text" placeholder="Say somthing..." name="comment">
<input type="hidden" name="pid" class="pid" value="<?= $post->id">
<input type="submit">
</form>
<?= endforeach; ?>
<?= endif; ?>
<?= endforeach; ?>
submiteComment: function() {
var comment_form = $("#comment_add");
var comment_text = $(".comment_text");
var pid = $(".pid"); // post id
$("body").on("submit", comment_form, function(e) {
e.preventDefault();
alert(pid.val()); // debug all time return 270 for all comments
if($.trim(comment_text).length) {
$.ajax({
type: 'post',
url: baseurl + '/comment/create',
data: {item_id: post_id.val(), comment_text: comment_text.val()},
success: function(data) {
alert('success');
},
error: function(t, r, j) {
alert(r.responseText);
}
})
}
});
Because you are giving each of the post id fields in the form the same name and class, when you access it like this:
var pid = $(".pid");
You will receive all three of the pid elements for your comments into the variable pid. When you do pid.val() it will just return the value of the first one, which is why you will always be seeing the same pid no matter which comment you submit.
Related
Sorry for disturbing again with my very basic question. First of all, sorry if my English is a little bit hard to understand. My current situation is I want to do a popup modal in my drag and drop boxes. In my popup modal, I can view and edit the details of the user based on what we click in the button in the box. The problem is, I cannot SELECT the data by id. But, when I SELECT all the data, the data appear in the modal boxes. But, it appears all the data. I just want the selected id. Back to my question for past few days, I've redo again to get more understanding on this popup modal part. I've done ajax and a little bit JavaScript, also, I tried to debug my code just what I've been told but I got an error saying "Parameter is missing" . What is causing by that ? I've done some reading about parameter but I still don't get the actual understanding about it. Can someone give an idea what is actually parameter is missing . And what I suppose to do by it?
Here what I've tried so far.
This is the button
<button data-id="<?php echo $row['userid'];?>" data-target="doubleClick-1" class='jobinfo' type='button' id='btnInfo' ondblclick="document.getElementById('doubleClick-1').style.display='block'">Info</button>
This is the modal popup
<div id="doubleClick-1" class="modal">
<label class="tabHeading">User Info</label>
<div class="contentTechJobInfo">
<div class="tech-details">
<div class="techClose" onclick="document.getElementById('doubleClick-1').style.display='none'" >×</div>
</div>
</div>
</div>
</div>
<script type='text/javascript'>
$(document).ready(function() {
$('.jobinfo').click(function() {
var userid = $(this).data('userid');
// AJAX request
$.ajax({
url: 'ajaxhome.php',
type: 'post',
data: {userid: userid},
success: function(response) {
// Add response in Modal body
$('.tech-details').html(response);
// Display Modal
$('#doubleClick-1').modal('show');
}
});
});
});
</script>
This my ajaxhome.php
<?php
$connection = mysqli_connect("", "", "");
$db = mysqli_select_db($connection, '');
if (!isset($_GET['userid'])) {
die("Parameter is missing!");
}
$userid = intval($_GET['userid']);
$query = "SELECT * FROM user WHERE userid ='$userid'";
$query_run = mysqli_query($connection, $query);
if ($query_run) {
while ($row = mysqli_fetch_array($query_run)) {
?>
<div class="input-box">
<label for="">Name</label>
<input type="text" id="username" name="username" value="<?php echo $row['username']?>">
</div>
<div class="input-box">
<label for="">Number</label>
<input type="text" id="usernumber" name="usernumber" value="<?php echo $row['usernumber']?>">
</div>
<div class="input-box">
<label for="">Class</label>
<input type="text" id="userclass" name="userclass" value="<?php echo $row['userclass']?>">
</div>
<button type="submit" id="submit" name="update" class="btn btn-primary"> Update Data </button>
<?php
if (isset($_POST['update'])) {
$username = $_POST['username'];
$usernumber = $_POST['usernumber'];
$userclass = $_POST['userclass'];
$query = "UPDATE user SET username='$username', usernumber='$usernumber', userclass='$userclass' WHERE userid='$userid'";
$query_run = mysqli_query($connection, $query);
if ($query_run) {
echo '<script> alert("Data Updated"); </script>';
header("location:homepage.php");
} else {
echo '<script> alert("Data Not Updated"); </script>';
}
}
} ?>
<?php
}
?>
In short, I think the problem comes from these lines of code in your modal:
var userid = $(this).data('userid');
you should replace it with
var userid = $(this).data('id'); // you should pass 'id' to .data() function instead of 'userid'
With your current code userid variable in your modal will always be undefined. It means it wont exist in $_GET when you send ajax request to PHP. And it causes your ajaxhome.php moves to die("Parameter is missing!");.
To get data-xxx attribute with jQuery, you should use pass 'xxx' to .data() function.
var xxx = $(this).data('xxx');
In your button, you are storing userid in data-id attribute
<button data-id="<?php echo $row['userid'];?>"
so if you need to get that userid you should pass 'id' into .data() function
Update:
In your ajax, you are using type: 'post', so in your php code you should check $_POST instead of $_GET
I don't think the value of user has been obtained
var userid = $(this).data('userid');
you can try
var userid = $(this).data('id');
I trying to make opening WP posts in popup.
Firts part of code its form in posts loop where I get query of posts what should be opened
<form id="postForm" method="POST">
<input id="postQuery" style="display: none" name="postQuery" value="<?php echo get_the_ID() ?>">
<input id="sendQueryBtn" data-toggle="modal" data-target="#exampleModalLong" type="submit" value="<?php the_title(); ?>">
</form>
Next is my JS, where I do query check by alert
$(document).ready(function () {
$("form").submit(function () {
let xuinya = $(this).serialize();
$.ajax({
type: "POST",
url: '.../footer.php',
data: xuinya,
success: function (data) {
alert(xuinya)
},
error: function (jqXHR, text, error) {
$('#modalBody').html(error);
}
});
return false;
});});
And I final, here is part of HTML with modal, where I try to use POST
<div id="modalBody" class="modal-body">
<?php
echo $_POST["postQuery"];
echo apply_filters( 'the_content', get_post( $_POST["postQuery"] )->post_content );
?>
</div>
My problem is because when I check query in JS - qet alert message with correct value, but in php I always qet simple "1".
I don't get why you posting to footer.php, I think its should be admin-ajax.php
just simply add to youfooter.php
<script>
var ajax_url = "<?php echo admin_url( 'admin-ajax.php' ); ?>";
</script>
Change url value in js to ajax_url, make sure hat with data you posting variable action and then create function in functions.php, something like this(if you sending action value as 'get_pop_posts')
add_action( 'wp_ajax_get_pop_posts', 'get_pop_posts_init' );
add_action( 'wp_ajax_nopriv_get_pop_posts', 'get_pop_posts_init' );
function get_pop_posts_init() {
$data = $_POST;
print_r($data);
die();
}
I created a list of radio groups and attached them to a product category. So what am doing is checking the groups that the category is meant to have then am going to then pick up the radio values in those groups available to the category and display them to the user to fill.
The next thing is I want to pass them to my ajax function which will then inject it into database. The problem is I can't get the unique name of the radio input in my ajax since I am loading it from the database.
<?php $notarray = DataDB::getInstance()->select_from_where('pro_print_group','product_category_id',$cat);
while ($row = mysqli_fetch_assoc($notarray)) {?>
<div class="col-sm-12">
<label for="quantity"><?php echo DataDB::getInstance()->get_name_from_id('group_n','print_type_group','print_type_group_id',$row['print_type_group_id']); ?></label>
<div class="printd-group">
<?php
$not = DataDB::getInstance()->select_from_where('print_type','print_type_group_id',$row['print_type_group_id']);
foreach($not as $ow):?>
<label class="printd">
<input name="prind<?php echo $row['print_type_group_id'] ;?>[]" id="prind<?php echo $row['print_type_group_id'] ;?>[]" value="<?php echo $ow['print_type_id'] ;?>" checked="" type="radio" class="name" data-price="0"> <?php echo $ow['name'] ;?>
</label>
<?php endforeach; ?>
</div>
</div>
<?php } ?>
Ajax Function
when form is submitted i call this function
function testpr() {
document.getElementById("load").style.display = "block";
var track = 'YU6758990';
var printd = $('#printd').val();
$.ajax({
type: 'post',
url: 'frverify.php',
data: "track=" + track + "&printd=" + printd + "&ins=testp",
success: function(data)
{
document.getElementById("load").style.display = "none";
jQuery('#get_prresult').html(data).show();
scroll_to('#messs');
}
});
}
PHP function
The ajax function then passes it to this php function where I am to receive the post request which in return inserts the selected radio values to the database and then returns the response back to my front end
function test(){
$track = $_POST['tack'];
$printd = $_POST['printd'];
echo DataDB::getInstance()->testp($track,$printd);
}
My guess is that there are more then one radiobutton generated, if that's the case you could try something like this.
<input name="printd[<?php echo $row['print_type_group_id'] ;?>]" id="<?php echo $row['print_type_group_id'] ;?>" value="<?php echo $ow['print_type_id'] ;?>" checked="" type="radio" class="name" data-price="0"> <?php echo $ow['name'] ;?>
Then in your Javascript change the way you retrieve the values of your form by using serialize.
data: "track=" + track + "&" + $('form#id.selector').serialize() + "&ins=testp"
Then inside your PHP script iterate trough the values with some sort of foreach loop
function test(){
$track = $_POST['tack'];
foreach($_POST['printd'] as $key => $value){
//$key => print_type_group_id
//$value => print_type_id
}
echo DataDB::getInstance()->testp($track,$printd);
}
Not sure what you want to do with the data and what it is you actually need but this should send you in the right direction.
I'm trying my best to get this to work. But AJAX is pretty new to me. So hang in there...
Ok, I've asked a couple of questions here about getting this issue that I'm having to work. I (We)'ve come a long way. But now the next issue is here.
I'm trying to echo a session in a div using AJAX.
The AJAX code is working, I can echo plain text to the div I want it to go. The only problem I have is it does not display the title of the item.
I have some items (lets say 3 for this example) and I would like to have the custom save the Items in a Session. So when the customer clicks on save. The ajax div displays the title. And if the custom clicks the 3rd item it show the 1st and 3rd item, etc...
My HTML:
<button type="submit" class="btn btn-primary text-right" data-toggle="modal" data-target=".post-<?php the_ID(); ?>" data-attribute="<?php the_title(); ?>" data-whatever="<?php the_title(); ?>">Sla deze boot op <span class="glyphicon glyphicon-heart" aria-hidden="true"></span></button>
My AJAX code:
$(".ajaxform").submit(function(event){
event.preventDefault();
$.ajax({
type: "POST",
url: "example.com/reload.php",
success: function(data) {
$(".txtHint").html(data);
},
error: function() {
alert('Not OKay');
}
});
return false;
});
My PHP reload.php:
<h4>Saved Items</h4>
<p>Blaat...</p>
<?php echo "Product Name = ". $_SESSION['item'];?>
I saw this code on here: I'm not using this code. Only wondering if I can use it for my code, and then how?
Change session.php to this:
<?php
session_start();
// store session data
$_SESSION['productName'] = $_POST['productName'];
//retrieve session data
echo "Product Name = ". $_SESSION['productName'];
?>
And in your HTML code:
function addCart(){
var brandName = $('iframe').contents().find('.section01a h2').text();
$.post("sessions.php", {"name": brandName}, function(results) {
$('#SOME-ELEMENT').html(results);
});
}
How I'm getting my title();:
<?php
// Set session variables
$_SESSION["item"][] = get_the_title();
?>
Is this some thing I can use? And could someone help me with the code?
Thanks in advance!
I'm not too sure on what exactly you're trying to accomplish, but here's a quick and dirty example of making an HTTP request (POST) with a name of a product, storing it in a PHP session, and outputting all product names in the session:
HTML
<p>Product A <button class="add-product" data-product="Product A">Add Product</button></p>
<p>Product B <button class="add-product" data-product="Product B">Add Product</button></p>
<p>Product C <button class="add-product" data-product="Product C">Add Product</button></p>
<div id="response">
</div>
JavaScript
$('.add-product').click(function() {
var productName = $(this).data('product');
$.post('addProduct.php', {productName: productName}, function(data) {
$('#response').html(data);
})
});
PHP (addProduct.php)
<?php
session_start();
if (!array_key_exists('products', $_SESSION) || !is_array($_SESSION['products'])) {
$_SESSION['products'] = [];
}
$productName = array_key_exists('productName', $_POST) ? (string) $_POST['productName'] : '';
if ($productName) {
$_SESSION['products'][] = $productName;
}
?>
<h4>Your added products:</h4>
<ul>
<?php foreach ($_SESSION['products'] as $product): ?>
<li><?php echo htmlspecialchars($product); ?></li>
<?php endforeach;?>
</ul>
I have created an AJAX that can store and delete data from database. The adding of data is working fine also the delete function is working fine when the page is already refresh but the delete is not working when data is newly added or when the page is not refresh.
This how it works. When a new data is added, the data will display, the user has an option to delete the data or not. The data has a "X" to determine that it is a delete button. Right now, The delete only works when the page is refresh.
This my SAVING script, as you can see if saving is success it displays the data automatically, together with the span that has the delete function.
$("#wordlistsave").click(function()
{
var user = $("#getUser").val();
var title = $("#wordbanktitle").val();
var words = $("#wordbanklist").val();
var postID = $("#getPostID").val();
var ctrtest = 2;
var testBoxDiv = $(document.createElement('div'))
.attr("id", words);
var dataString = 'user='+user+'&title='+title+'&words='+words+'&id='+postID;
<?php if (is_user_logged_in()): ?>
$.ajax({
type: "POST",
url: "<?=plugins_url('wordlistsave.php', __FILE__ )?>",
data: dataString,
cache: false,
success: function(postID)
{
testBoxDiv.css({"margin-bottom":"5px"});
testBoxDiv.after().html('<span id="'+words+'" style="cursor:pointer">x '+postID+'</span>  <input type="checkbox" name="words[]" value="'+ words+ '">'+words );
testBoxDiv.appendTo("#test_container");
ctrtest++;
}
});
<?php else: ?>
alert('Fail.');
<?php endif; ?>
});
This is my delete function , when the user click the "X" span, the data will be deleted, but this only works after the page is refresh.
$("span").click(function()
{
var queryword=$(this).attr('id');
var postIDdel = $("#getPostID").val();
var dataString = 'queryword='+queryword+'&postID1='+postIDdel;
<?php if (is_user_logged_in()): ?>
$.ajax({
type: "POST",
url: "<?=plugins_url('worddelete.php', __FILE__ )?>",
data: dataString,
cache: false,
success: function(html)
{
$('div[id="'+queryword+'"]').remove();
}
});
<?php else: ?>
<?php endif; ?>
});
This is my HTML, the one that holds the querying of data and displaying of data.
<?php
global $wpdb;
$query_wordbanklist = $wpdb->get_results("SELECT meta_value, meta_id FROM wp_postmeta WHERE post_id = '$query_id' AND meta_key = '_wordbanklist'");
if($query_wordbanklist != null)
{
echo "<h3> Wordlist </h3>";
foreach($query_wordbanklist as $gw)
{
?> <div id="<?php echo $gw->meta_value ?>">
<span id="<?php echo $gw->meta_value ?>" style="cursor:pointer">x</span>   <input type="checkbox" name="words[]" value="<?php echo $gw->meta_value ?>"><?php echo $gw->meta_value; ?>
</div>
<?php
}
}
?>
All I wanted to achieve is to make the delete function works right after the data is stored. Right now it only works when the page is refresh. Any idea on this?
Perhaps try this...
$(document).on('click', 'span', function() {
// delete stuff in here
}