I'm avoiding using a database for my latest project and so I am using files and folders. I list folders of a directory as buttons and each one loads a screen with a list of files within it. I'm now trying to load in the file's contents dynamically without refresh to avoid loosing the menu (list of files shown on screen as buttons). I'm trying to use ajax but because the file buttons are created using a foreach php loop, the value I pass to javascript/ajax when I click one of the file buttons is incorrect as it always wants to pass the first button's value in the list!
Here is the PHP code:
<?php
if(isset($_POST['FolderContent'])) {
foreach (glob($_POST['FolderContent']."/*.*") as $file) {
if(is_file($file)){
$fileNoExt = substr($file, 0, -4); //Remove file extension so the menu item shows only the name of the file
$character = explode('/', $fileNoExt);
$filePathTrimmed = trim(end($character));
echo "<form method='POST'>
<input type='submit' ID='selectBtn' value='$filePathTrimmed' onclick='return displayData();'/>
<input type='hidden' id='dataField' name='content' value='$file'/>
<input type='hidden' name='title' value='$filePathTrimmed'/>
</form>";
} else {
echo "Files not found!";
}
}
}
?>
And this is the JS:
<script>
function displayData()
{
var btnData = document.getElementByID('selectBtn').value;
alert("The currently selected button is "+btnData);
});
}
</script>
As you can see the PHP loops and creates a form for each button plus hidden fields. The JS just tries to grap the value of the button clicked and alert it. Problem is that the value is always the first file in the list.
What am I doing wrong please? If I use a class on the button instead of an ID then I will need to state the number in the array:
var btnData = document.getElementsByClassName('selectBtn')[0].value;
But this means I'd need to know the place within the array and make using the value pretty pointless.
I'm pretty stuck - or thick!
Thanks.
You need to use this inside onclick='return displayData(); and then use it in your function like below:-
Working snippet:-
function displayData(ele){
var btnData = ele.value;
alert("The currently selected button is "+btnData);
return false;
}
<form method='POST'>
<input type='submit' value='hi' onclick='return displayData(this);'/>
<input type='hidden' name='content' value='$file'/>
<input type='hidden' name='title' value='$filePathTrimmed'/>
</form>
You are setting the same id value for each separate form. You should ensure that all the id attribute values are unique for all html elements as a rule of thumb to avoid unpredictable behaviours in the dom.
<?php
if(isset($_POST['FolderContent'])) {
foreach (glob($_POST['FolderContent']."/*.*") as $idx => $file) {
if(is_file($file)){
$fileNoExt = substr($file, 0, -4); //Remove file extension so the menu item shows only the name of the file
$character = explode('/', $fileNoExt);
$filePathTrimmed = trim(end($character));
echo "<form method='POST'>
<input type='submit' id='selectBtn-{$idx}' value='$filePathTrimmed' onclick='return displayData(this.id);'/>
<input type='hidden' id='dataField' name='content' value='$file'/>
<input type='hidden' name='title' value='$filePathTrimmed'/>
</form>";
} else {
echo "Files not found!";
}
}
}
?>
And javascript:
<script>
function displayData(clicked_id)
{
var btnData = document.getElementByID(clicked_id).value;
alert("The currently selected button is "+btnData);
return false;
}
</script>
Solution: I used 'return false' at the end of the javascript/ajax code block, and 'this' in the php code to pass current data held in 'value' - thanks Alive to Die.
I also I made use of the 'name' attribute to store and access further data data.
PHP:
echo "<form method='POST'>
<input type='submit' id='selectBtn' name='$file' value='$filePathTrimmed' onclick='return displayData(this);'/>
</form>";
JS:
<script>
function displayData(fileName)
{
var btnData =fileName.name;
var name = fileName.value;
$.ajax({
type : "POST",
url : "DisplayFileContents.php",
data : {"data": btnData, "name": name},
success : function(result) {
$('.page-content').html(result);
$('body').animate({scrollTop: 0}, 200);
}
});
return false;
};
DisplayFileContents.php:
<?php
$filename=$_POST['data'];
$title = $_POST['name'];
echo "<h2>".$title."</h2>";
echo "<pre>";
Include $filename;
echo "</pre>";
?>
Related
I have created my own "like" button. With AJAX I'm able to post changes to database to add 1 to the "like" button. Then JavaScript will update the first "like" button with the updated information once. It will not update again if I click the "like" again. Also none of other "like" buttons work, they only refresh the page.
I have searched all over trying to find an answer for this. I have gotten it down to where I have each like button to where it has its own id. Even though I'm passing the id for the button into AJAX and back to JavaScript from the server. I'm still not able to update the other "like" buttons. Only the first one and only once.
<html>
<script>
window.addEventListener("load", function () {
function sendData() {
var XHR = new XMLHttpRequest();
// Bind the FormData object and the form element
var FD = new FormData(form);
XHR.onload = () =>{
var response
try{
response = JSON.parse(XHR.responseText);
}catch (e){
console.error('no parse');
}
if(response){
handleresponse(response);
}
}
// Set up our request
XHR.open("POST", "likes.php");
// The data sent is what the user provided in the form
XHR.send(FD);
}
// Access the form element...
var form = document.getElementById("likesform");
// ...and take over its submit event.
form.addEventListener("submit", function (event) {
event.preventDefault();
sendData();
});
});
function handleresponse(response){
console.log(response.message);
let value = response.message;
let id = response.id;
console.log(id);
document.getElementById(id).value = "Liked " + value;
value = 0;
id = 0;
}
</script>
<?php
function postcommentbar($imagenumber, $likes, $num_rows){
echo "<div id='postcommentbar'>";
echo "<form id='likesform' ><input type='hidden' name='imagenumber' value='".$imagenumber."'><input type='hidden' name='like' value='Like'><input type='hidden' name='likes' value='".$likes."'><input type='submit' class='likebutton' id='".$imagenumber."' value='Like ".$likes."'></form>";
echo "<form action='comments.php' method='POST'><input type='hidden' name='imagenumber' value='".$imagenumber."'><input id='commentbutton' type='submit' name='comment' value='Comment ".$num_rows."'></form>";
echo "</div>";
$num_rows = 0;
}
?>
I expect to be able to click any "like" button on the page and see it updated accordingly with the increased number of "like"s.
Could you please advise me on how I can achieve this?
I have onload before send. If you look at the code you wool see this.
As you suggested that you are using the imagenumber as identifier.I have updated my code and this should work with your code.
I have implemented php code to dynamically generate numbers and bind them to get unique names and then send them to the sendData function.This code executes well at my end.
Please have a look, if this helps
<body>
<?php
for($i=1;$i<=3;$i++){
?>
<div>
<form id='likesform<?= $i ?>' ><input type='hidden' name='imagenumber' value='imagenumber<?= $i ?>'><input type='hidden' name='like' value='Like'>
<input type='hidden' name='likes' value='adas'><input type='button' class='likebutton' id='imagenumber<?= $i ?>' value='Like' onclick="sendData('likesform<?= $i ?>')">
</form>
</div>
<?php
}
?>
</body>
<script type="text/javascript">
function sendData(form_id){
var XHR = new XMLHttpRequest();
var form = document.getElementById(form_id);
var FD = new FormData(form);
XHR.onload = () =>{
var response
console.log(XHR.responseText);
try{
response = JSON.parse(XHR.responseText);
}catch (e){
console.error('no parse');
}
if(response){
handleresponse(response);
}
}
// Set up our request
XHR.open("POST", "likes.php");
// The data sent is what the user provided in the form
XHR.send(FD);
}
function handleresponse(response){
// console.log(response.message);
let value = response.message;
let id = response.id;
console.log(id);
document.getElementById(id).value = "Liked " + value;
value = 0;
id = 0;
}
</script>
I also created a file named "likes.php".This is the output which i sent from the file and appended it with the DOM.
<?php
echo json_encode(array('message' => 1, 'id' => $_POST['imagenumber']));
?>
Update your function with the below one.I have made some changes to your html binding.The problem was you were not escaping the quotes properly.
Try with this function, this will work.
<?php
function postcommentbar($imagenumber, $likes, $num_rows){
echo "<div id='postcommentbar'>"; echo "<form id='".$imagenumber."' ><input type='hidden' name='imagenumber' value='".$imagenumber."'><input type='hidden' name='like' value='Like'><inputtype='hidden' name='likes' value='".$likes."'><input type='button' class='likebutton' id='".$imagenumber."' onclick=\"sendData('$imagenumber')\" value='Like ".$likes."'></form>";
}
?>
This code does not generates any syntax errors at my end.
Hope this helps
Thanks
Do you have multiple forms with multiple like buttons?
If yes then you cannot use the same id for multiple forms.ID has to be unique in a DOM. That's the first issue with your code.
The second thing is when you are sending data through ajax, due to the same form name it will always consider the last form data with the id "likesform", because you are using static id, that's the second issue.
Anyways this issue are only relevant if you have multiple forms on a single page, and i do think you have multiple forms.
Now solution for your problem.
Why use the event listener when you can add a onclick function to the element itself during rendering the elements.Until and unless you are doing that for some purpose!
Have a look to the code below.
function sendData(id, form_id){
console.log("Called");
var XHR = new XMLHttpRequest();
var form = document.getElementById(form_id);
var FD = new FormData(form);
XHR.onload = () =>{
var response
try{
response = JSON.parse(XHR.responseText);
}catch (e){
console.error('no parse');
}
if(response){
handleresponse(response);
}
}
// Set up our request
XHR.open("POST", "likes.php");
// The data sent is what the user provided in the form
XHR.send(FD);
}
function handleresponse(response){
console.log(response.message);
let value = response.message;
let id = response.id;
console.log(id);
document.getElementById(id).value = "Liked " + value;
value = 0;
id = 0;
}
<body>
<div>
<form id='likesform' ><input type='hidden' name='imagenumber' value='"asdadddd"'><input type='hidden' name='like' value='Like'>
<input type='hidden' name='likes' value='adas'><input type='button' class='likebutton' id='id1' value='Like' onclick="sendData('id1','likesform')">
</form>
</div>
<div>
<form id='likesform1' ><input type='hidden' name='imagenumber' value='"asdadddd"'><input type='hidden' name='like' value='Like'>
<input type='hidden' name='likes' value='adas'><input type='button' class='likebutton' id='id2' value='Like' onclick="sendData('id2','likesform1')">
</form>
</div>
<div>
<form id='likesform2' ><input type='hidden' name='imagenumber' value='"asdadddd"'><input type='hidden' name='like' value='Like'>
<input type='hidden' name='likes' value='adas'><input type='button' class='likebutton' id='id3' value='Like' onclick="sendData('id3','likesform2')">
</form>
</div>
</body>
Explanation to the code.
I have removed the onload eventListener as there is no need to add a function inside the listener.
This is because a function is compiled and only runs when you call them, so there is no risk of it being called before the DOM or any elements render.
I have created multiple forms and buttons with different id, that are then supplied to the sendData function as parameters.
The id from that parameter is then used to pull the data from relevant form.You also have the id of the button being clicked, which you can further use to manipulate the button value.
I have also changed the input type="submit" to type="button" which will not reload the page and we wont have to use event.preventDefault.
You can further process your required functionality once you receive the response.
Hope this helps
Thanks
I have a submit button"Certificate copy" when i clicked the button it should show a popup.
The below one is my html code.
print "<script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script>";
print "<form action='details.php' name='copy' method='POST' target='_blank'>";
print "<input type='hidden' name='certificate_name' value='$certificate_name'>";
print "<input type='hidden' name='certificate_id' value='$certificate_id'>";
print "<input type='submit' name='certificatecopy' id='certificate' value='Certificate Copy'>";
print "</form>" ;
and my code for popup is
print "<script> $(document).on('click','#certificate',function(){val = confirm('Do you want to create a new certificate?');
alert(val);
if(val)
{
alert('proceed ');
return true;
}
else
{
alert('Dont proceed');
return false;
}
});</script>";
My problem is, when i click the button at first time the popup box doesn't appear. but when the button clicked second time, the popup box is appear. what is the problem. I need the popup when the button clicked first time. please help.
Instead of adding in $_SESSION['pop_up'] just echo it:
if(isset($_POST['certificatecopy'])){
echo "<script>
.....................
.....................
</script>";
You need to do this in client side on button click event .
Confirm will return the Boolean value true or false . Based on user click.
$(document).on('click','#certificate',function(){
val = confirm('This will create a new certificate with all properties and links from the original certificate. A certificate user may edit the new certificate properties, but may not delete the certificate. Do you want to create a new certificate?');
alert(val);
if(val)
{
alert('proceed ');
return true;
}
else
{
alert('Dont proceed');
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action='details.php' name='copy' method='POST' target='_blank'>
<input type='hidden' name='certificate_name' value='$certificate_name'>
<input type='hidden' name='certificate_id' value='$certificate_id'>
<input type='submit' name='certificatecopy' id="certificate" value='Certificate Copy'>
</form>
Update 1 :
<?php
print "<script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script>";
print "<form action='details.php' name='copy' method='POST' target='_blank'>";
print "<input type='hidden' name='certificate_name' value='$certificate_name'>";
print "<input type='hidden' name='certificate_id' value='$certificate_id'>";
print "<input type='submit' name='certificatecopy' id='certificate' value='Certificate Copy'>";
print "</form>" ;
print "<script> $(document).on('click','#certificate',function(){val = confirm('Do you want to create a new certificate?');
alert(val);
if(val)
{
alert('proceed ');
return true;
}
else
{
alert('Dont proceed');
return false;
}
});</script>";
?>
You want to ask for the confirmation Client side before sending a request to the server?
If you use Bootstrap, you can try a little jQuery plugin I made, https://github.com/delboy1978uk/bs-delete-confirm. It doesn't need to be used solely for deletion, it's only named that since it's the most used case.
All you do is add a CSS class to your link:
Do stuff!
And the javascript:
$(document).ready(function(){
$('.confirm').deleteConfirm();
});
Now when you click the link, the JS intercepts it, launches a bootstrap modal window, and upon confirming, follows your hyperlink.
You can pass options in to the deleteConfirm() method too:
{
heading: "Please confirm",
body: "Are you sure you wish to perform this action?",
ok_text: "Proceed",
cancel_text: "Back",
log: false
}
Hope this helps! If you don't use Bootstrap, it's well worth addingto your project! Here's a link to the modal functionality:
https://getbootstrap.com/docs/3.3/javascript/#modals
im currently using jquery booklet Moleskine Notebook with jQuery Booklet to make a logbook with some images to be uploaded for every page.
what im doing is im looping the div of every page in php as im calling data from DB, but when i tried to use file upload form as follows , it only works on first page on. the upload button appeared on every other page but it does nothing, not even call the upload window.
every page has its own log_id $row['log_id'].
so any solution is much appreciated.
if (mysqli_multi_query($conn, $sql)) {
do {
if ($result = mysqli_store_result($conn)) {
while ($row = mysqli_fetch_array($result)){
echo '<div>';
echo ' <form method="post" name="upload_form" id="upload_form" enctype="multipart/form-data" action="php/multiple_upload.php">';
echo ' <input type="hidden" name="form_submit" value="1"/>';
echo ' <input type="file" class="hidden" name="images[]" id="upload-images" multiple >';
echo ' <input name="log_id" type="hidden" value="'.$row['log_id'].'">' ;
echo ' </form>';
echo '</div>' ;
}
mysqli_free_result($result);
}
} while (mysqli_next_result($conn));
}
and the here is the script for calling form
$(document).ready(function(){
$('#upload-images').on('change',function(){
$('#upload_form').ajaxForm({
beforeSubmit:function(e){
$('.progress').show();
},
success:function(e){
$('.progress').hide();
location.reload(true);
},
error:function(e){
}
}).submit();
});
});
If you're using id $('#upload_form').ajaxForm({***});. This will only find and target the first #upload_form
And if you're using class like $('.upload_form').ajaxForm({***});. This will find and target all the form class .upload_form
You need to define which form you're looking for. In this case, You just need to find the closest/parent of .upload-images form. Like below.
Do like this.
$(document).ready(function(){
$('.upload-images').on('change',function(){
$(this).closest('form').ajaxForm({ // target the parent form
beforeSubmit:function(e){
$('.progress').show();
},
success:function(e){
$('.progress').hide();
location.reload(true);
},
error:function(e){
}
}).submit();
});
});
I'm coding a voting system for multiple uploads; each uploaded image is in a foreach statement with a form attached to each, with three buttons to vote up, down or none, each associated with an INT in my mysql database.
I got it to work by submitting the form data straight to the PHP function that 'UPDATE's the database. To avoid a page refresh, I attach ajax. I got the ajax to send the two variables needed for the PHP function to update the correct "image" row and INT in the db.
Question: The ajax function works, but the PHP function doesn't seem to update.
SUSPECTED PROBLEM: I'm pretty sure it's the way I'm defining the variables in ajax that I want to pass, I was trying to grab the ID of the "image" it's handling, but I don't know how to translate this data to the PHP function so that it UPDATE's correctly.
Here's the form, javascript, and php:
// IMAGE, and rest of foreach above this, and ending after form
// This form only shows one button, there are three, each
// I'll treat the same once I get one to work
<form action="feed.php" method="post" id="vote_form_1">
// If js isn't turned on in broswer, I keep this
// hidden input, to send unique ID
<input type="hidden" name ="input_id"
class="input_id" value="<?php echo $row['id']; ?>"/>
<input type="submit" name="post_answer1" onclick="sayHi(event);"
class="answer_L" id="<?php echo $row['id']; ?>"
value="<?php echo $row['post_answerL']; ?>"/>
</form>
// end of foreach
//AJAX
<script type="text/javascript">
function sayHi(e) {
var input_id = $(e.currentTarget).attr('id');
var post_answer1 = $("input[name='post_answer1']");
jQuery.ajax({
type: 'POST',
url: 'feed.php', //name of this file
data:input_id,post_answer1,
cache: false,
success: function(result)
{
alert ('It worked congrats');
}
});
e.preventDefault();
</script>
// PHP VOTE UPDATE FUNCTION
<?php>
if(isset($_POST['post_answer1'],$_POST['input_id'])){
$current_id = $_POST['input_id'];
$vote_1 = "UPDATE decision_post set " .
"post_answer1=post_answer1+1 WHERE id = '".$current_id."' ";
$run_vote1 = mysqli_query($conn2, $vote_1);
if($run_vote1){ echo 'Success'; }
}
?>
Here a simple answer, just serialize all your form data!
$('form').submit(function(){
$.post('feed.php', $(this).serialize(), function(data){
console.log(data);
}, 'json');
return false;
});
var post_answer1 = $("input[name='post_answer1']").val();
im using ajax to query my mysql to my database.
But im stock at issue with my php generated html form input - javascript/jquery will simply not pick up the value. From normal html is no issue of course.
php (works fine, all echos are good)
<?php
function getAge() {
$age = "<select name='age'>";
$result = $mysqli->query("select * from ages");
while ($row = $result->fetch_row()) {
$age.="<option value=" . $row[0] . ">". $row[1] ."</option>";
}
$age.="</select>";
return $age;
}
?>
html
<form id="myform">
<input name='name' value='Nick'>
<input name='sport' value='Football'>
<?php echo getAge(); ?>
<input type='submit'>
</form>
javascript
$("form#myform").on('submit', function(e){
e.preventDefault();
var json = {}
$.each(this.elements, function(){
json[this.name] = this.value || '';
});
}
Everything works well except it wont get the value of the <select>. If i make a normal html select it works.. ?!
Also anybody know how to delete the submit button from the json object? :-)
Any dynamically generated HTML will not have the events applied to them, as those events are applied on page load. So if you apply the events to the document, you will be able to pull values from dynamically generated html. Like so:
var json = {};
$(document).on('submit', 'form#myform', function(e){
$('*', this).each(function(){
json[$(this).attr('name')] = $(this).val();
});
});
Hope this helps!
change this line:
$age.="<option value=" . $row[0] . ">". $row[1] ."</option>";
to this:
$age.="<option value='" . $row[0] . "'>". $row[1] ."</option>";
//----------------^---------------^------put quotes
And i think you can make use of .serializeArray() which does the same you want but in a different way like multiple objects with multiple [{ name : value}] pairs:
$(function(){ //<-----put this block too
$("form#myform").on('submit', function(e){
e.preventDefault();
var json = $(this).serializeArray();
}); //<----checkout the closing
}); //<---doc ready closed.