Target and update dynamically created content using AJAX - php

I am trying to create a question/answer system where a user can reply to existing questions. The question system is correctly posting and displaying to the database, but I am having difficulties replying to dynamically created questions.
To save space here is the code that is failing
$(document).ready(function() {
//make sure it was the postReply button
$("#postReply").on("click", function(){
//get the questionID the user just clicked on
var questionID=$(this).val();
//hide the reply button
$("#postReply").hide();
//show the reply framework
$('.reply').append('<div class="replycontent"><p><textarea name="answer" id="answer" placeholder="Enter your answer"></textarea></p><p><button id="postAnswer" type="submit">Post Answer</button></p></div>');
});
});
Called from this line within a loop:
echo '<p><button type="submit" id="postReply" value='.$questionID.'>Reply</button></p> ';
echo '<div class="reply" id="reply'.$questionID.'">';
The issue that I hit is that I am updating and adding the div to every single question because of the .reply is incorrectly targeting. I can't seem to get it to target the questionID that was clicked. I have tried testing it with alerts but only the most recent question button is parsing to the script.
I can only hide the button from the most recent comment added.
This is the output of the HTML source that is being created from the SQL query
<p>Question ID: 34 Title: z Description: zz Date Posted:2017-08-04 05:31:28</p>
<p><button type="submit" id="postReply" value=34>Reply</button></p>
<div class="reply" id="reply34"></div>
When clicking the Reply button to the above question the code should look something like:
<p>Question ID: 34 Title: z Description: zz Date Posted:2017-08-04 05:31:28</p>
<div class="reply" id="reply34">
<div class="replycontent">
<p><textarea name="answer" id="answer" placeholder="Enter your answer"></textarea></p>
<p><button id="postAnswer" type="submit">Post Answer</button></p>
</div>
</div>

I am not sure to really understand the problem, but try replace this:
$('.reply').append('<div class="replycontent"><p><textarea name="answer" id="answer" placeholder="Enter your answer"></textarea></p><p><button id="postAnswer" type="submit">Post Answer</button></p></div>');
by this:
$('#reply' + questionID).append('<div class="replycontent"><p><textarea name="answer" id="answer" placeholder="Enter your answer"></textarea></p><p><button id="postAnswer" type="submit">Post Answer</button></p></div>');
Your fields have all a different ID attribute, so you can use it.
And to hide your button, since they have all the same ID, your selector can look like $('#postRelpy[value="' + questionID + '"]').

Related

PHP & jQuery form submission issue

I'm creating website project where you can edit a post after it has been published. I've a made the site with PHP, SQL and jQuery, and all posts that are published to the site gets outputted to the websites "feed" via a while-loop (not included in this questions content). All posts have a unique ID added to them when they are published (in the database).
The issue I now have is that the second form (post__edit) doesn't prompt at all.
I've figured out that I need to pass the id of a post inside an <input type="hidden" value="$postID"> field. This form below just prompts the actual post_edit form that is used to submit a post change.
echo '
<form method="post">
<button type="button" class="post__editBtn">Edit post</button>
<input type="hidden" name="post__editHidden" value="'.$postID.'">
</form>';
When the button class: post__editBtn gets clicked a jQuery click eventlistener is triggered that fades in the form (post_edit) that let's you make the changes to a post and submit them.
$('.post__editBtn').click(function() {
$('.post__edit').fadeIn();
});
Then what I have is a PHP if-statement that checks if the hidden value has been set. If it has then I echo out the previously hidden form, and assigns a SESSION variable to be used later on when doing the UPDATE query.
if(isset($_POST['post__editHidden'])) {
$_SESSION['post__editHidden'] = $_POST['post__editHidden'];
echo'
<form method="post" action="../../php/includes/updatePost.php" class="post__edit">
<input type="text" name="postTitle" placeholder="Edit title" required>
<textarea name="postMsg" maxlength="255" placeholder="Edit message" required></textarea>
<button type="submit">Edit Post</button>
<button class="post__edit-close">Close</button>
</form>';
}
To sumarize
The first form triggers the jQuery fadeIn effect for the correct post (with $postID)
The jQuery just fades in the second form (post__edit)
The second form (post__edit) takes the post__editHidden value (the correct ID for the correct post) and assigns it to a SESSION variable that can later be used to make the SQL UPDATE query, that runs when the second form is finally submitted (to updatePost.php).
I believe that because I have the first forms button set to type="button" it doesn't submit the form so isset($_POST['post__editHidden'] doesn't run. But if I change the button to a normal submit type then the first form is just summited and reloads the page which it's on. I could maybe just e.preventDefault in my jQuery fadeIn, but I don't know if that works.
I'm quite new to PHP and SQL so I might have it all wrong. Thanks anyways!
It's more of a suggested alternative than an answer.
The session variable usage would be more useful in other cases where we could obfuscate the ID value for example or reuse it in an orphan (disconnected) navigation level...
But in this case, I'd better use an only one form and fill it's input values using Ajax.
This Demo updates values only for postId' 32... It should work when it's used alongside a functional dynamic ajax handler that gets an Id and returns it's jSon object.
$('.post__editBtn').click(function() {
var myform = $('.post__edit');
var postId=$(this).attr('data-id');
myform.find("input[name='post__editHidden']" ).val(postId);
$.ajax({
type: "GET",
dataType: "json",
url: "https://api.myjson.com/bins/kx5xs", // replace with php later
data: {id: postId},
success: function(data) {
myform.find("input[name='postTitle']" ).val(data[0].title);
myform.find("textarea[name='postMsg']" ).val(data[0].content);
},
error : function(){
alert('Some error...!');
}
});
$('.post__edit').fadeIn();
//for demo puropose to show the new value in the update form:
console.log($(".post__edit input[name='post__editHidden']").val());
});
.post__edit{
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class"post">
Post 30<button type="button" data-id="30" class="post__editBtn">Edit post</button>
</div>
<div class"post">
Post 32<button type="button" data-id="32" class="post__editBtn">Edit post</button>
</div>
<div class"post">
Post 37 <button type="button" data-id="37" class="post__editBtn">Edit post</button>
</div>
<!--all data-id values would be replaced with '.$postID.' in the php loop-->
<form method="post" action="../../php/includes/updatePost.php" class="post__edit">
<input type="text" name="postTitle" placeholder="Edit title" required>
<textarea name="postMsg" maxlength="255" placeholder="Edit message" required></textarea>
<button type="submit">Save Post</button>
<button class="post__edit-close">Close</button>
<input type="hidden" name="post__editHidden" value="">
</form>
And we add a file ex:ajax.php that we call with ajax where we get an ID, we do get that record from the database to return our json. Something like this :
<?php
$id=$_GET['id'];
$stmt = $conn->query("SELECT title,content * FROM posts WHERE postId=$id LIMIT 1");
$result=...
echo json_encode($result);
To get a jSon like this :
{"id": "32","title": "POst 32","content": "POst 32 talks about HiTECH"}

Form auto calculate answer to php

I have an autocalc running on a form and the total is shown through a div ID. I need to be able to somehow render the div ID answer into a php form mailer.
I’ve tried adding a hidden input field with the div ID.
<div id="totalPriceTM">
<input name="Score" id="totalPriceTM" value="" type="hidden" />
</div>
No error messages but result not showing in email.
You should create different div name on your form.
for example :
<script>
function autocalc(x,y)
{
a = x*y;
document.getElementById(totalPriceTM).innerHTML = a;
document.getElementById(totalPriceTM2).value = a;
}
</script>
<div id="totalPriceTM">
<input name="Score" id="totalPriceTM2" value="" type="hidden" />
</div>
result will be show on div totalPriceTM and will be set the value of div totalPriceTM2

Create automatic indivisual link for MYSQL Data

I creating a webpage on mobile price. On the front page i gave the visuals & model of the phone and a "details" button. which submits the id for the phone on a details.php page. It shows the data good without any problem. the link looks like this "www.eeeee.com/details.php".
But i want to show the link as "www.eeee.com/details.php?brand=nokia&id=1111". How can i do this?
Please help me...
If you are using simple form for doing this you can use simple get method instead of post. But if you wanna make your url manually, you need to use form like this.
<form method="get" name="MobileDetails">
<input name="brand" id="brand" value="<?php echo $brand;?>" type="hidden">
<input name="brid" id="brid" value="<?php echo $brandid;?>" type="hidden">
<button type="button" name="submitButton" value="get Details" onclick="getDetails()">
</form>
and javascript for your code will be like
<script type="text/javascript">
function getDetails(){
var brand = document.getElementById('brand').value;
var brandid = document.getElementById('brid').value;
document.MobileDetails.action = 'details.php?brand='+brand+'&id='+brandid;
document.MobileDetails.submit();
}
</script>
you can also do this by using ajax it's totally your choice.

Passing checkbox checked from jQuery to PHP in CodeIgniter

I'm working on a PHP self-evaluation form that has 5 question categories with 10 questions each. In the beginning of the application, I have 5 checkboxes to represent these categories, and they are automatically checked. The idea is that whenever user unchecks a category, the questions of that category instantly disappear from the form, and when they check it again, they come back. Something that should be achievable with the help of jQuery and AJAX.
I made the checkboxes with CodeIgniter's form_helper:
for($i = 1; $i<=5; $i++) {
$this->formapp_model->printCatName($i);
$data = array('name'=>'category$i', 'id'=>'category$i', 'value'=>'$i', 'checked'=>TRUE);
echo form_checkbox($data);
}
And I have a function to printing all 10 questions of the category from database after their category id, which works fine when I just post them as they are:
$this->formapp_model->printCategory(1);
$this->formapp_model->printCategory(2);
$this->formapp_model->printCategory(3);
$this->formapp_model->printCategory(4);
$this->formapp_model->printCategory(5);
Using the help of this:
Passing whether a checkbox is checked, via jQuery, to PHP
I was able to gather that for the jQuery, I need something like
var category1 = $('#category1:checked').val();
in order to check if the checkbox has been selected. I also tried
var category1 = $('#category1:checked').post();
as it seemed logical to use post in order to PHP to recognize it.
And for the print selection something like
if (isset($_POST['category 1'])) { $this->formapp_model->printCategory(1); } else { echo "This category is not selected."; }
I tried this, but PHP doesn't recognize the message that jQuery is giving it, meaning the category's questions disappeared permanently, whether the checkbox was checked or not. I checked with echo var_export($_POST); and noticed that all the jQuery is printing out is: array ( ). The question mentioned above was very informative, but missed some info that I would have needed to get it to work. The asker was also using an array instead of separate variables so I don't know how to edit it properly.
I'm a complete newbie with jQuery and AJAX so I have a hard time grasping what I need in order to get jQuery and PHP communicate dynamically the way I described. I have run around stackoverflow to find similar cases, but none of them have quite had what I need. However, I deeply apologize in case this is a repeativive question. Thank you to anyone who helps!
PHP is server side, you need the questions to appear/disappear client side meaning you want to make that happen using jQuery itself (or regular js but since you're already loading jQuery it's quicker just to use the library itself).
To be honest I'm not really following how your view is working so I'll just give some basic code to give you the idea. You create the checkboxes and the questions giving each a unique ID. Then in the on click method for the check boxes you determine which questions to show.
HTML:
<div id="checkboxes">
<input type="checkbox" id="box1" class="check" checked="checked"/>
<input type="checkbox" id="box2" class="check" checked="checked" />
<input type="checkbox" id="box3" class="check" checked="checked" />
<input type="checkbox" id="box4" class="check" checked="checked" />
<input type="checkbox" id="box5" class="check" checked="checked" />
</div>
<div id="question1" class="question">
<p>Question 1</p>
</div>
<div id="question2" class="question">
<p>Question 2</p>
</div>
<div id="question3" class="question">
<p>Question 3</p>
</div>
<div id="question4" class="question">
<p>Question 4</p>
</div>
<div id="question5" class="question">
<p>Question 5</p>
</div>
jQuery:
$(".check").on("click",function(){
var id = $(this).attr("id");
var id2 = id.substr(id.length -1);
var question = "question"+id2;
if($(this).is(":checked"))
{
$("#"+question).css("display","block");
} else {
$("#"+question).css("display","none");
}
});
Demo: http://jsfiddle.net/calder12/taSPX/1

Showing poll results in place of the poll area

I am trying to show the results from a poll in the same area and page as the poll question without reloading the entire page. I am able to get the results and show them in a new page but I do not know how to replace the html in where I have the question and replace it with the html with the results.
HTML (with the poll question)
<div id="poll-area">
<!-- Voting poll -->
<fieldset>
<form action="javascript:void(0);" id="pollid" name="myform" method="POST">
<label><input type="radio" name="answer" value="left" id="option_left" />Yes</label>
<label><input type="radio" name="answer" value="right" id="option_right" />No</label>
<input type="submit" name="submit" id="submit" value="Vote" />
<input type="hidden" name="id" value="pollid" />
</form>
</fieldset>
<!-- End voting poll -->
</div>
AJAX call to handle the poll:
var $j = jQuery.noConflict();
jQuery(document).ready(function($j) {
$j("form").submit(function(){
var str = $j(this).serialize();
$j.ajax({
url: "poll_vote.php",
type: "POST",
data: str,
cache: false,
success: function(result) {
window.location.replace("poll_results.php");
}
});
return false;
});
});
I am guessing it is instead of the *window.location.replace("poll_results.php")* that I want to replace the HTML within the #poll-area with the #poll-area in the poll_results.php, but I do not know how do it.
HTML for the poll results (what is contained in poll_results.php)
<div id="poll-area">
<fieldset>
<legend>Results</legend>
<ul>
<li>
<span class="total-votes">Yes</span>
<br />
<div class="results-bar" style="width:52%;">
52%
</div>
</li>
<li>
<span class="total-votes">No</span>
<div class="results-bar right-bar" style="width:48%;">
48%
</div>
</li>
<li>
</ul>
<p>Total votes: 100</p>
</fieldset>
</div>
Thanks for the help!
in the output of poll_results.php you can remove the outer div with the id "poll-area". You don't want duplicate IDs when it is pulled into your current page.
For your jQuery, this should do the trick:
success: function(result) {
$j("#poll-area").html(result);
As I'm aware, anything that currently exiits inside the poll-area div will be overwritten with the result from the ajax query. (The voting options should disappear, and the results will be shown)
Edit (summary of comments): poll_vote.php should output the HTML contained within poll_results.php
Easiest but not the cleanest: use innerhtml and getElementById()
You will get something like:
var div = getElementById('poll-area'); //The poll itself
div.innerHtml = getElementbyId('answers'); //The answers
Note that I used 'answers' as ID, since you use the same ID for the answers and the poll. So you will get a nested which will not work. Give your first child of the answers () a new id called 'answers'.
If you know more of javascript, use the createElement to add a new element. This will improve speed and is better, but a bit more advanced.

Categories