Making button dissapear AFTER data is submitted - javascript

So I have this code:
Javascript:
<script>
function hidenow(id) {
var divelement = document.getElementById(id);
var button = document.getElementById("hidebutton");
if(divelement.style.display == 'none')
divelement.style.display ='block',
button.style.display = "block";
else
divelement.style.display = 'none',
button.style.display = "none";
}
</script>
And two buttons:
<p>Programma's waarop u kunt abonneren:</p>
<form action="#" enctype="multipart/form-data" method="post">
<?php wp_nonce_field( 'set_programma_action', 'set_programma' ); ?>
<table>
<?php foreach ( $retrieve_data as $retrieved_data ) { ?>
<tr>
<th>Programma:</th>
<td id="hideit" style="vertical-align: middle;">
<?php
echo $alreadysub; echo esc_html( $retrieved_data->Anaam );
?>
</td>
<th>
<button id="hidebutton" style="display:block" onclick="hidenow('hideit')" name="programma" type="submit" value="<?php echo esc_attr( $retrieved_data->Anaam ); ?>">Abonneer</button>
</th>
</tr>
<?php } ?>
</table>
</form>
<!-- Dit stuk code laat de programma's zien waar de radiostation al op geabonneerd is. -->
<br>
<p>De programma's waarop u geabonneerd bent:</p>
<form action="#" enctype="multipart/form-data" method="post">
<?php wp_nonce_field( 'set_programmatest_action', 'set_programmatest' ); ?>
<table>
<?php foreach ( $retrieve_data as $retrieved_data ) { ?>
<tr>
<th>Programma:</th>
<td style="vertical-align: middle;"><?php echo esc_html( $retrieved_data->meta_value ); ?></td>
<th>
<button name="programmatest" type="submit" id="button" value="<?php echo esc_attr( $retrieved_data->meta_value ); ?>">Abonnement opzeggen</button>
</th>
</tr>
<?php }
?>
</table>
</form>
At the moment, when I click a button; it dissapears. But it comes back as soon as the data is submitted to the database and the page is refreshed. I want the button (along with the program that comes with it) to dissapear. I already tried making a isset. But this results in BOTH buttons dissapearing and not just one.
Example:
This is the first button, it is written in the second piece of code. When I click one button, it needs to dissapear along with the program. I tried doing this using isset but it resulted in the button dissapearing all together (both).
I also have this button:
I have done nothing to this button, since I do not want it.
I have tried looking on Stack Overflow and several articles and youtube videos. I have been busy making this for a week but I do not know how to make it work.
How can I make sure that the first button is not shown even after the data is submitted in the db or after the page is refreshed?

Have you tried https://developer.mozilla.org/pt-BR/docs/Web/API/Event/preventDefault ?
This stops the page from refreshing.
document.getElementById("form").addEventListener("click", function(event){
event.preventDefault()
});

You have to add some condition which checks whether to display button or not.
After submitting form you can set localStorage data and in your logic first check for this localStorage, if it is set do not display button otherwise display them.
This way if someone also refreshes page the localStorage will not loose and your button will not display.You can reset localStorage through your code to display them again.
Otherwise you can do on page load check for data / value in database, if it exist do not display the button otherwise display them.

Related

Subscription system not working after clicking button

I have the following code:
Button:
<br>
<p>Programma's waarop u kunt abonneren:</p>
<form action="#" enctype="multipart/form-data" method="post" onSubmit="return processForm();">
<?php wp_nonce_field( 'set_programma_action', 'set_programma' ); ?>
<table>
<?php foreach ( $retrieve_data as $retrieved_data ) { ?>
<tr>
<th>Programma:</th>
<td id="hideit" style="vertical-align: middle;">
<?php
echo $alreadysub; echo esc_html( $retrieved_data->Anaam );
?>
</td>
<th>
<div><button id="some_id" style="display:block" onclick="hidenow('hideit')" name="programma" type="submit" value="<?php echo esc_attr( $retrieved_data->Anaam ); ?>">Abonneer</button></div>
</th>
</tr>
<?php } ?>
</table>
</form>
Javascript:
<script>
var divelement = document.getElementById("some_id");
window.addEventListener('DOMContentLoaded', function(){
if(localStorage.getItem("form_submitted")){
divelement.style.display = 'none';
}else{
//Local Storage Not Set
}
});
function processForm(){
//Send Ajax to submit data and after its response set the local Storage
divelement.style.display = 'none';
//Set
localStorage.setItem("form_submitted", 1);
return false; //this will prevent form from submitting and refreshing the page.
}
Once the user clicks a button, he/she is subscribing to a program. To allow the user to subscribe to a program, I created the following code:
if (isset( $_POST['programma'] ) && isset( $_POST['set_programma'] ) && wp_verify_nonce( $_POST['set_programma'], 'set_programma_action' )) {
$data = filter_input( INPUT_POST, 'programma', FILTER_SANITIZE_STRING );
$current_user_id = get_current_user_id();
if ( $current_user_id && ! empty( $data ) ) {
//voeg de huidige user_id en data toe in de rij met meta_key programma
$addprog = add_user_meta( $current_user_id, 'programma', $data );
echo "U bent geabonneerd op". ' ' . $data;
}
}
?>
I created the Javascript code to make sure that once the user is subscribed to a program, the button he clicked on along with the program dissapear. The only problem I have is that the user is not able to subscribe to a program anymore. The program is also not saved in the database. I have searched for several youtube videos on the issue but I cannot find a solution.
Also, for some reason, only the top button dissapears when clicked on. Not the buttom.
I am trying to put the button and the element inside of it in none display as soon as it is pressed. See image down here for the 2 buttons.
Here is the solution if you want all the button to hide when form is submitted.For this you have to use class instead of id.
var divelement = document.getElementsByClassName("some_class");
function hideByClass(){
for(var i = 0; i < divelement.length; i++){
divelement[i].style.display = "none";
}
}
window.addEventListener('DOMContentLoaded', function(){
if(localStorage.getItem("form_submitted")){
hideByClass();
}else{
//Local Storage Not Set
}
});
function processForm(){
//Send Ajax to submit data and after its response set the local Storage
hideByClass();
//Set
localStorage.setItem("form_submitted", 1);
return true;
}
And use class instead of id.You also have to use class on td as it is also in loop so id should not repeat.
<div><button class="some_class" style="display:block" onclick="hidenow('hideit')" name="programma" type="submit" value="<?php echo esc_attr( $retrieved_data->Anaam ); ?>">Abonneer</button></div>
Solution 2
If you want only clicked one to be hidden.For this you need to do modifications.Here are the modifications.
Remove onSubmit from form.
Add Id to form.
Add a counter variable before starting loop also increment its value inside loop body. This is for making unique ids.
Concatenate this counter variable in id for td and button.
Change button type from submit to button.
Call processForm function on button click with passed value of counter to identify which button is clicked.
HTML / PHP
<form action="#" enctype="multipart/form-data" method="post" id="myForm">
<?php wp_nonce_field( 'set_programma_action', 'set_programma' ); ?>
<table>
<?php
$counter=0;
foreach ( $retrieve_data as $retrieved_data ) { ?>
<tr>
<th>Programma:</th>
<td id="hideit<?php echo $counter;?>" style="vertical-align: middle;">
<?php
echo $alreadysub; echo esc_html( $retrieved_data->Anaam );
?>
</td>
<th>
<div><button id="some_id<?php echo $counter;?>" style="display:block" name="programma" type="button" value="<?php echo esc_attr( $retrieved_data->Anaam ); ?>" onClick="processForm(<?php echo $counter;?>);">Abonneer</button></div>
</th>
</tr>
<?php
$counter++;
} ?>
</table>
</form>
JS
function processForm(counter){
//Send Ajax to submit data and after its response set the local Storage
document.getElementById("hideit"+counter).style.display = 'none';
document.getElementById("some_id"+counter).style.display = 'none';
//Set
localStorage.setItem("form_submitted", 1);
document.getElementById("myForm").submit();
}

jQuery less/more button set in php foreach

I want show post with for-each. My condition is 1st show 5 post and hide other post with a show more button if loop has more than 5 post, then when I click show more then will show other post and hide show more button and show less more button. If post has less then 5 then no showing show more button. How can I do that by jQuery?
<?php
foreach ($hotel_data as $key => $hoteldata)
{
//Show 3 lowest price of hotel link
if(isset($hoteldata[0]->rooms)){
/*$ii = 0;*/
foreach ($hoteldata[0]->rooms as $key => $bookinginfo) {
?>
<tr>
<td class="">
<div class="hotel_name">
<?php echo $bookinginfo->desc; ?>
</div>
</td>
<td class="booking-img">
<img src="http://pics.avs.io/hl_gates/100/30/<?php echo $bookinginfo->agencyId; ?>.png"/>
</td>
<td>
<div class="hotel-price">
Price : $ <?php echo $bookinginfo->price; ?>
</div>
</td>
<td class="booking-url">
BOOK NOW
</td>
</tr>
<?php
/*$ii++;
if($ii > 2){
break;
}*/
}
}
}
?>
You need to re-think your strategy. What you want can be best achieved with AJAX calls. Therefore you need to write your loop with with JS /jQuery. PHP would only handle the retrieval of posts.
For example, you can create an AJAX call that sends a POST request to a PHP script, sending the number of posts you would want. When PHP receives the request, it fetches the posts needed from the DB and sends the results back in JSON format, JS will then parse the results into your HTML.
The AJAX call can be called once at page load (loads first 5), then it can be called again when the "load more" button is clicked.
Take count of array if more than 5 show "show more" button. Please see example below:
<?php
// Get count
$count = count($hotel_data);
foreach ($hotel_data as $key => $hoteldata) {
//Show 3 lowest price of hotel link
if(isset($hoteldata[0]->rooms)) {
/*$ii = 0;*/
foreach ($hoteldata[0]->rooms as $key => $bookinginfo) {
?>
<tr>
<td class="">
<div class="hotel_name">
<?php echo $bookinginfo->desc; ?>
</div>
</td>
<td class="booking-img">
<img src="http://pics.avs.io/hl_gates/100/30/<?php echo $bookinginfo->agencyId; ?>.png"/>
</td>
<td>
<div class="hotel-price">
Price : $ <?php echo $bookinginfo->price; ?>
</div>
</td>
<td class="booking-url">
BOOK NOW
</td>
</tr>
<?php
}
}
if ($count>5) {
// Code for "show more" button
}
}
?>
Then you have to hide other post by some css class's style property display: none;.
For jQuery code, you have to make script on show more button and change property of other posts you have hide. Also change button text to "show less".

When I try to send id value of row via POST to another page, this page will always GET id value 1

I started learning webdeveloping and i tried to send "id" of one of the rows generated from database to another page. The rows are clickable thanks to the javascript code, so i can choose whichever row i want. The problem is, that even though the POST method seems right:
<form id="send" method="POST" action=<?php echo "secondpage.php?id=". $row['id']; ?> ></form>
// In inspect of the main page it gets the value.
However
second page always receive id value of 1. Doesn't matter if i click on the row with id=18 or any other. It will always recieve value of 1...
I heard that this could be a problem with javascript code which i put under PHP code.
Here is a code with PHP:
<div id="content">
<table id="usersTable" class="table table-bordered table-hover table-sm ">
<form action=http://localhost/dodawanie.php>
<input class="btn btn-primary" type="submit" value="Dodawanie">
</form>
<?php if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {?>
<tr>
<td><?php echo "id: ". $row['id']; ?> </td>
<td><?php echo "Name: ". $row["first_name"]; ?> </td>
<td><?php echo "Last: ". $row["last_name"];?> </td>
<form id="send" method="POST" action=<?php echo "secondpage.php?id=". $row['id']; ?> >
</form>
</tr>
<?php }
} else {
echo "0 results";
}
$conn->close();
?>
</table>
</div>
Here is javascript:
<script type = "text/javascript">
$(document).ready(function(){
$('#usersTable').find('tr').click( function(){
// alert('You clicked row ' + ($(this).index()+1) );
$('#send').submit();
});
});
</script>
I would gladly accept any help to find an error here.
Change the <form id="send" id value as unique
or use a class some thing like below:
<form class="form_send" then in your javascript search for the form_class inside the clicked tr:
$(document).ready(function(){
$('#usersTable').find('tr').click( function(){
$(this).find('form.form_send').submit();
});
});
Ids have to be unique. $('#send').submit() only finds and submits the first form with that id.
You could add your row id to the form's id attribute to make them unique for example.

Display select query results by using jQuery

I'm pretty new to jQuery and I'm practicing with it. I've this html simple page:
<html>
<head>
<title> Testing jQuery
</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="script.js" type="text/javascript"></script>
<link href="mycss.css" rel="stylesheet" type="text/css">
</head>
<body>
<h2 id="myH"> This is a title.</h2>
<br>
<br>
<fieldset>
<legend>Data</legend>
<form name="myForm">
<input type="text" id="firstData" placeholder="Write something in here" \>
<br>
<br>
<input type="text" id="secondData" placeholder="Write something else in here" \>
<br>
</form>
<button id="formButton" value="Confirm">Confirm</button>
</fieldset>
<br><br><br>
<div id="myDiv"></div>
</body>
</html>
This PHP script:
<?php
/* Connection to DB*/
.... CONNECTIONS STUFF.........
$query = " SELECT * FROM table1;";
$results = mysql_query($query);
echo " <table border=\"2\"><tr> <th>ID</th><th>First</th><th>Second</th></tr>";
while($row = mysql_fetch_array($results)) {
?>
<tr>
<td>
<?php echo $row['ID']?>
</td>
<td>
<?php echo $row[ 'First']?>
</td>
<td>
<?php echo $row[ 'Second']?>
</td>
</tr>
<?php
} echo "</table>"; ?>
And finally this js code:
$(function () {
$('#formButton').on('click', function (e) {
var firstData = $('#firstData').val();
var secondData = $('#secondData').val();
var query = 'first=' + firstData + '&second=' + secondData;
// Here I use another php script.
$.get('myData.php', query, function (data) {
$('#myDiv').html(data);
});
});
$('#formButton').on('click', function (e) {
$.ajax({
url: "myquery.php",
type: "POST",
success: function (data) {
$("#myDiv").empty().html(data);
}
});
});
});
Ok , now that I've inserted all the code , the problem is that I can add elements to my database by using myData.php script but I'd like to create a page where in the top you can add elements and when you click on the confirmation button in the bottom (with a query) all the contents of the table are displayed. So I can add elements but I'm not able to display them. I'm new to jQuery and I'm trying to make it work , I've made different researches on the Web but I couldn't find anything that solved my problem. Could please someone help me? Thanks!
You can do both operation by single file myData.php
Put below code right after record inserted in myData.php
$query = " SELECT * FROM table1;";
$results = mysql_query($query);
echo " <table border=\"2\"><tr> <th>ID</th><th>First</th><th>Second</th></tr>";
while($row = mysql_fetch_array($results)) {
?>
<tr>
<td>
<?php echo $row['ID']?>
</td>
<td>
<?php echo $row[ 'First']?>
</td>
<td>
<?php echo $row[ 'Second']?>
</td>
</tr>
<?php
} echo "</table>"; ?>
No need of two ajax call. Remove the second button click jquery code.
On first button click event myData.php file will be called. First record will be inserted in your DB table with your existing code. After it place your code to fetch records from DB. your HTML will be sent in the response and place that HTML in the DIV with your existing jquery code.
you can use jquery load function for it, its very easy for you
http://www.w3schools.com/jquery/jquery_ajax_load.asp
just load a div from there to a div in current page
follow this url for the video tutorial, its very simple, use a div here then enter the id and in the page you are loading, please use another id and load that id into this page div
https://www.youtube.com/watch?v=mtz8MdQXhno
it works in wordpress and will simply work in php
same code

How can I update a specific record in a sql database based on a selection made in a dropdown select box?

Ok, I have spent days on this, and I am out of my depth. I admit I am completely new to sql, jquery, and ajax. I apologize in advance for this.
I am trying to build an application where an admin can see a users performance over time, averaging the last 2 weeks of input scores. Using a dropdown box a member should be selected from the DB (this part seems to work), then a form below can be filled out and an "update" button pressed to update the record in the DB (this is completely broken).
The select box is populated from the DB with ajax, and I can return values from the selection with an onchange function, but when I try to then update the database with my form, nothing is updated.
The insert button and associated code work properly, and information is stored correctly in the DB. (I will break the data off into more accurate tables when I have the code correct as I did not want to deal with joins and multiple tables while struggling.)
When selecting a name from the select menu $_POST['memberID'] shows the correct number.
Once information is entered into the form and "update" is pressed, $_POST['memberID'] is blank and the DB is not updated.
Controller.php:
<?php require 'php/dbconnect.php';
$records = array();
if(!empty($_POST)) {
switch (true) {
case isset($_POST['insert']):
if(isset($_POST['name'], $_POST['designation'], $_POST['rank'], $_POST['currentScore'])) {
// The following trim functions followed by !empty ensures that a series of spaces is not accepted from users as input.
$name = trim($_POST['name']);
$designation = trim($_POST['designation']);
$rank = trim($_POST['rank']);
$currentScore = trim($_POST['currentScore']);
if(!empty($name) && !empty($designation) && !empty($rank) && !empty($currentScore)) {
$insert = $conn->prepare("INSERT INTO members (name, designation, rank, currentScore) VALUES (?,?,?,?)");
$insert->bind_param('ssii' , $name, $designation, $rank, $currentScore);
if($insert->execute()) {
$insert->free(); //Remove Query Data from memory since it is no longer needed.
header('location: index.php');
die();
}
}
}
break;
case isset($_POST['update']):
$name = trim($_POST['name']);
if(!empty($name)) {
$update = $conn->prepare("UPDATE members SET name = ? WHERE '$memberID'");
$update->bind_param('s', $name);
if($update->execute()) {
header('location: index.php');
die();
}
}
break;
// case isset($_POST['delete']):
// // Delete statement goes here
// break;
// else
}
}
if($results = $conn->query("SELECT *, ((previousScore + currentScore) / 2) AS avgScore FROM members")) {
if($results->num_rows) {
while($row = $results->fetch_object()) {
$records[] = $row; //Appending value to array
}
$results->free();
}
}
?>
Index.php:
<?php include 'header.php' ?>
<?php if(!count($records)) {
echo 'No Records' ;
} else {
?>
<form id="memberSelect" method="post">
<select name="memberID" id="members" onchange="change()">
<!-- Populated with function members in footer.php -->
</select>
</form>
<table>
<thead>
<tr>
<th>Name</th>
<th>Designation</th>
<th>Rank</th>
<th>Previous Score</th>
<th>Current Score</th>
<th>Average Score</th>
</tr>
</thead>
<tbody>
<?php
foreach($records as $r) {
?>
<tr>
<td><?php echo escape($r->name); ?></td>
<td><?php echo escape($r->designation); ?></td>
<td><?php echo escape($r->rank); ?></td>
<td><?php echo escape($r->previousScore); ?></td>
<td><?php echo escape($r->currentScore); ?></td>
<td><?php echo escape($r->avgScore); ?></td>
<!-- Remember when putting data in that current score needs to be moved to previous score's
position and the NEW score will take the place of current score(which will be the old score until updated) -->
</tr>
<?php
}
?>
</tbody>
</table>
<?php
}
?>
<hr>
<form action="" method="post">
<div class="field">
<label for="name">Member name</label>
<input type="text" name="name" id="name" autocomplete="off">
</div>
<div class="field">
<label for="designation">Designation</label>
<input type="text" name="designation" id="designation" autocomplete="off">
</div>
<div class="field">
<label for="rank">Rank</label>
<input type="text" name="rank" id="charLevel" autocomplete="off">
</div>
<div class="field">
<label for="currentScore">Current Score</label>
<input type="text" name="currentScore" id="currentScore" autocomplete="off">
</div>
<div id="submit">
<!-- Add a comment section to be input into DB -->
<input type="submit" name="insert" value="Insert">
<input type="submit" name="update" value="Update">
<input type="submit" name="delete" value="Delete">
<!-- <input type="hidden" name="id" value="<?php //echo $?>"> -->
</div>
</form>
<?php include 'footer.php' ?>
Footer.php:
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.11.3.min.js"><\/script>')</script>
<script src="js/plugins.js"></script>
<script src="js/main.js"></script>
<script>
//How do you explain something you barely understand? The following function uses JQUERY
//json, and ajax to fill a select dropdown with items populated from a linked database.
//See the jsonData.php for the json data being referenced here, it is imperitive to the operation of
//this function that json data be available.
function members(){
$('#members').empty();//Removes all content of the associated ID 'members' to ensure a clean default value
$('#members').append("<option>Loading</option>");//fill them with a default message
$.ajax({
type:"POST",
url:"php/jsonData.php",//the location of the json data, for this it is required to be in its own file
contentType:"application/json; charset=utf-8",
dataType: "json",
success: function(records){ //only fires if the json data is found
$('#members').empty();//If everything is ok, removes previous default value
$('#members').append("<option value='0'>--Select Member--</option>");
$.each(records,function(i,memberID){//Uses a foreach loop to fire a function for every memberID, assigning the value to i
$('#members').append('<option value="'+ records[i].memberID +'">'+ records[i].name +'</option>');
//^ The workhorse. Grabs the select value by the ID, appends the option value by looking within the records array
//(which is defined and assigned values in the jsonData.php file) and assigns the member id as the value and the 'name'
//as the option. This populates the dropdown with the names and gives them the value 'memberID' from the database.
});
},
complete: function(){
}
});
}
$(document).ready(function(){
members();
});
</script>
<script>
function change(){
$('#memberSelect').submit();//Submits the page to the server when called
}
</script>
<!-- Google Analytics: change UA-XXXXX-X to be your site's ID. -->
<script>
(function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=
function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;
e=o.createElement(i);r=o.getElementsByTagName(i)[0];
e.src='https://www.google-analytics.com/analytics.js';
r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));
ga('create','UA-XXXXX-X','auto');ga('send','pageview');
</script>
</body>
</html>
I think the problem is in this line of the Update Block:
$update = $conn->prepare("UPDATE members SET name = ? WHERE '$memberID'");
I am assuming the primary key of your member table is: member_id
Then this code will be:
$update = $conn->prepare("UPDATE members SET name = ? WHERE member_id = ?");
$update->bind_param('si', $name, $memberID);
Try this. Hope it helps.

Categories

Resources