Loading Modals with data from database - php

I'm using php to create 'x' amount of buttons based on the rows from a db table.
Once the button is selected i want to pass the Variable onto the php so i can used this to load specific data from the database to the Modal.
This works for the first button click and loads the data to the modal as expected, however once i close the modal and open another modal the new userdata.php?uid=$var1 doesn't seem to get received in the php by the $var2 = $_GET['uid'] and the variable just remains the same as before.
Do i need to clear the uid in the php somehow?
The Button,
$var1 = $row["Scope_ID"];
echo "<button type='button' href='userdata.php?uid=$var1' class='btn btn-
info btn-lg' data-toggle='modal' data-button='$var1' data-
target='#myModal'>$var1</button>";
The PHP,
$var2 = $_GET['uid'];
echo "<h3>$var2</h3>";

the solution is,
$( document ).ready(function() {
$('#editBox').on('hidden.bs.modal', function () {
$(this).removeData('bs.modal');
});
});

Related

first ajax attempt--not syncing correctly

So i'm trying to use a table that generates multiple submit buttons per row. I'm doing this with a php while loop. Each button has a value of the corresponding "id" from the database. The table populates with everything from the database that has a status of "Ordered". On each row I can click a button that will change it to "Received" or "Cancelled". This is why I assigned a value of "id" to each button, so it only affects the status of the row that's being clicked. So far, all this is working fine but I would like to be able to do this using ajax instead of refreshing the page each time.
Currently I have this for my ajax:
$('#cancel').click(function(e) {
e.preventdefault();
//set value of cancel button to a variable
var value = $("#cancel").val();
$.ajax({
method: "POST",
url: "updatetable.php",
data: {cancel: value},
});
});
and this for my PHP:
//updatetable.php
if($_POST['cancel']) {
echo $_POST['cancel'];
}
the reason for the "if" statement is because I also need to click received but if yall help me figure this part out, i can go the rest of the way on my own.
Right now, I can't even get this to connect with a simple echo of the POST variable.
Just for reference, here is my html markup for the buttons:
<button type='submit' class='btn btn-danger' name = 'cancel' id = 'cancel' value='".$row['order_id']."'>Cancel</button>
<button type='submit' class='btn btn-success' name = 'received' id= 'received' value='".$row['order_id']."'>Received</button>
(the buttons are output by a PHP echo statement-hence the concats in the value setting)
I've tried to follow several tutorials but I can't figure out why this doesn't connect the right way. Perhaps I need to change it to an input with type "button" instead of button type submit? But then the actual value of the "value" would appear as the text instead of the word "cancel". Any help is appreciated.
you are going to want to put a unique identifier on your IDs. Here is what I would do (instead):
function cancelClick(btn){
e.preventdefault(); // I dont think this is needed
var value = $(btn).val();
$.ajax({
method: "POST",
url: "updatetable.php",
data: {cancel: value},
});
});
actually I would do this but that isnt what you used:
function cancelClick(btn){
var value = $(btn).val();
$.post("updatetable.php",{cancel: value});
});
then your UI like:
<button type='button'
class='btn btn-danger'
value='<?=$row['order_id'] ?>'
onClick="cancelClick(this)">Cancel
</button>
<button type='button'
class='btn btn-success'
value='<?=$row['order_id'] ?>'
onClick="otherFnName(this)>Received
</button>
edit: to perform a task on return you do something like this:
function cancelClick(btn){
var value = $(btn).val();
$.post("updatetable.php",{
cancel: value
}, function (d){
// here is where you will do stuff on return.
// I suggest first console.log(d); and see what is returning
// return (echo) a value to at least identify the row
// you are wanting to delete, if that is what you are attempting
// be sure the element you are attempting to manipulate has
// a unique identifier (id), and then do whatever.
// you can call a function from here also, to make it neater
// this area will `happen` when your ajax is complete.
});
});

JQuery specific variable from a php printed table

Ive got a table with buttons:
and Ive set specific ID's to each one but I dont see how I can access them all from a JQuery script so i can set a specific get to each one of them.
Edit:
All of the buttons have unique ids:
Shown in google chrome inspect element :
When I click REMOVE i want the row to get removed. I can do this and have done this with PHP via GET however I dont want to have to refresh the page every time I remove one. I tested doing it with JQuery .GET and it works fine however I dont want to have to make a new script to have to delete every single row, rather do it dynamically by getting the ID of the row and removing the row that the REMOVE button is in. Ive tried multiple ways of doing this but all I do is fail.
This is the script that prints the data in the table
function print_data($info1,$info2,$info3,$info4,$info5,$info6,$info7,$info8){
echo"<tr><td id='notice1id$info8'>$info1</td><td id='noticename$info8'>$info2</td><td id='noticetype$info8'>$info3</td><td id='noticecontent$info8'>$info4</td><td id='noticeshow$info8'>$info5</td><td id='noticeedit$info8'><a href='admincp.php?edit=1&editid=$info6'><div class='btn btn-success'>Edit</div></a></td><td id='noticeremove$info8'><input type='button' id='remove$info8' value='remove' onclick='removeMe();' class='btn btn-danger' name='$info8'></td><td style='display:none;'><p id='getid' name='$info8' style='display:none;'></p></td><td style='display:none;'><script> function removeMe() { alert($info8);}</script></td><input id='noticeid$info7' class='form-control' style='display:none;' type='text' name='$info8' value=$info7></td></tr>";
?><?php
}
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
print_data($row['NoticeID'],$row['NoticeName'],$row['NoticeType'],$row['NoticeContent'],$row['NoticeShow'],$row['NoticeID'],$row['NoticeID'],$row['NoticeID']);
}
JavaScript:
$(document).ready(function () {
var id = $("#getid").attr("name");
alert("#remove" + id);
$("#remove" + id).click(function () {
var getcontent = $("#noticeid4").val();
$("#notice1id5,#noticename5,#noticetype5,#noticecontent5,#noticeshow5,#noticeedit5,#noticeremove5").slideUp(300, function () {
// Animation complete.
});
});
});

Saving data to database using Jquery

I'm creating a browser RPG game. I want to allow a user to save their current stats by updating the mysql db without having to reload the page... So I thought jquery could help.
The user will not be adding their own stats. The stats are generated through user actions, such as solving a challenge. I want the user to be able to save those updated stats to the database whenever they would like.
The issues are:
the jQuery is outputting the echo "saved..." . $stats . ", " . $stats2; before I click the Save button.
When I click save, the database field isn't being updated.
I'm wondering why this isn't working. When I click save, the stats fields shouldn't be 0, but should be the stats that are shown- 11. The database fields should also be updated.
For testing purposes, I've just created js variable var stats that is updated when the arrow keys are pressed.
I call the function updateHUD() to do $('#stats').html(stats); which updates the HTML.
function updateHUD() {
$('#stats').html(stats);
}
Then updateHUD is called after arrow key is pressed.
HTML
<div class="span12">
<button onclick="saveData(stats)" name="input" value="">Save Data</button>
<br /><span id="output"></span><br />
<ul>
<li><b>Stats 1:</b> <span id="stats"></span> </li>
</ul>
</div>
jQuery
//Pass saved data to store in DB
$(document).ready(function() {
saveData();
});
function saveData() {
$.get("php/CRUD.php", {"_input" : $('input[name=input]').val()},
function(returned_data) {
$("#output").html(returned_data);
}
);
}
PHP
<?php
//store all player data in array and save to/update db
include 'DbConnect.php';
session_start();
$stats = (isset($_GET['_input']) ? ($_GET['_input']) : 0);
$formvars = array();
array_push($formvars, $stats);
echo $stats;
echo $_SESSION['username'];
$qry = 'UPDATE users SET stats="'.$stats.'" WHERE username="' . $_SESSION['username'] . '"';
$mysqli->query($qry) or die(mysqli_error($mysqli));
echo "saved..." . $stats;
mysqli_close($mysqli);
?>
Output
saved...0 //this should be 11
Stats 1: 11
You do a
$('input[name=input]').val()
but you have named the submit button "input" instead of adding a input box with this name.
But the question is unclear anyways.
You want to give a user the permission to update his stat with the value that he wants? You should update the question to make it more clear since it does not make much sense at the moment.
First your selector where you are getting your data from is incorrect. You need to either change your html...
<button name="input"></button>
to an...
<input type="button" name="input" />
or change your jQuery selector...
$('input[name=input]')
to select the correct element
$('button[name=input]')
Second you need to make sure your button's 'value=""' actually has data in it when the ajax function is being called.
<button onclick="saveData(stats)" name="input" value="[Data Value Goes Here]">Save Data</button>
Finally the reason your jQuery is outputting before you click the the save button is because you are executing the function as soon as the document loads.
$(document).ready(function() {
saveData();
});
Try something more like this:
HTML
<button name="input" value="[data goes here]">Save Data</button>
JavaScript / jQuery
//Pass saved data to store in DB
$('button[name=input]').on('click', saveData);
function saveData() {
$.get("php/CRUD.php", {"_input" : $(this).val()},
function(returned_data) {
$("#output").html(returned_data);
}
);
}
Also you can try using load:
//Pass saved data to store in DB
$(document).ready(function() {
saveData();
});
$.fn.saveData=function(){
$('#divforload').css('display','none');
$('#divforload').load("php/CRUD.php?stats="+$('#stats').val(),function(){$('#divforload').fadeIn();});
}
//Just call the function onClick...
//Need an input called 'stats'
});

Checkbox state do not change after button is pressed

I have a button that when it is pressed calls an ajax function with some parameters and then the ajax posts some values on the database. The user might use this form a lot of times before he leaves the application or refreshes the page. Up to now, this works great!
In my last update, I added a checkbox that will hold one more piece of information that I want to be saved on the database using the aforementioned ajax function. So, when the button is pressed, I check if the checkbox is checked and I send to the ajax function true or false. Up to now, this works great too!
What doesn't work great, though, is the fact that the last features works properly only for the first time! Every other time the user hits the button, no matter what the checkbox checked state is, it will submit the state it was the first time. It is like the checkbox.checked property freezes after the button is pressed for the first time.
It might be irrelevant, but I also tried the same with toggle buttons and I get the same issue!
Do you have an idea on how to overcome this problem?
Thanks a lot!
Here is the code:
The form: It has 1 toggle button and 3 buttons that call the sendTask function.
<button type='button' class='btn btn-info' data-toggle='button' style='margin-top: 5px; width: 216px; height: 40px;' name='yesterday".$category['id']."' id='yesterday".$category['id']."'>This one was yesterday!</button></div>
<button class='btn btn-".$buttoncolor."' id='btn-spec-small' type='button' onClick='sendTask(".$category['id'].", '1', yesterday".$category['id'].")'>0-15min</button>
<button class='btn btn-".$buttoncolor."' id='btn-spec-small' type='button' onClick='sendTask(".$category['id'].", '2', yesterday".$category['id'].")'>15-60min</button>
<button class='btn btn-".$buttoncolor."' id='btn-spec-small' type='button' onClick='sendTask(".$category['id'].", '3', yesterday".$category['id'].")'>60+min</button>
The sendTask function:
function sendTask(category, weight, checkbox){
var ieri = $(checkbox).hasClass('active');
TaskSubmit(category, weight, ieri);
};
The TaskSubmit function:
function TaskSubmit (taskidsubmitted, weight, ieri) {
$.ajax({
url: 'submit_task.php?taskid=' + taskidsubmitted + '&weight=' + weight + '&ieri=' + ieri,
success: function (response) {
if (response !== "fail") {
document.getElementById('score-label').innerHTML = response;
} else {
document.location = "index.php";
}
}
});
}
The problem is that this line:
var ieri = $(checkbox).hasClass('active');
only changes the fist time a button is pressed. All the other times keeps the first state (true or false).
I believe you should be using .prop().
function sendTask(category, weight, checkbox){
var ieri = ($(checkbox).prop('checked') != undefined);
TaskSubmit(category, weight, ieri);
};
The browser -should- remove this property if the checkbox is unchecked. If this is not the case, use console.log() to find out what it is doing.
In your html, you are passing yesterdaySomeCategory to the function, instead of "yesterdaySomeCategory". I am not sure what jQuery does with that, but the normal way of selecting an element is by $("#yesterdaySomeCategory"). Try changing it to
<button class='btn btn-".$buttoncolor."' id='btn-spec-small' type='button' onClick='sendTask(".$category['id'].", '1', \"#yesterday".$category['id']."\")'>0-15min</button>

catching nested button clicks

I have php code on a page which generates a series of buttons, like so: (in a loop)
echo "<input type=\"button\" event='$eventID' id=\"sendsomeone\" value=\"Send a family member\"/>";
echo "<span id='$eventID'></span>";
Then I have jquery which catches those clicks, and also creates a button:
$('input:button').click(function() {
$(this).next("span").append('You clicked this button!');
$(this).next("span").append('<input type=\"button\" event=' + eventID + ' id=\"submitbutton\" value=\"Send\"/>');
$('#submitbutton').click(function() {
}
}
My objective is to correctly catch all button clicks on the page. (no matter the order they are clicked in, the PHP generated buttons should all behave in one way, the secondary buttons should all behave a different way)
In the code I have above, it works correctly at first, letting you click buttons and creating the secondary button for each. But once you click one of the secondary buttons, it all starts behaving strangely. After clicking a second button, then /any/ click executes code for #submitbutton.
Do I need to use a class in here somewhere? If so, an example would be great. What will make this work?
You don't need to append the button an then select it. You can create the input element in a jQuery object and then just bind to that objects click event like so:
$('input:button').click(function() {
var span = $(this).next("span");
span.append('You clicked this button!');
$('<input type=\"button\" event=' + eventID + ' value=\"Send\"/>')
.appendTo( span )
.click(function() {
//do stuff here
});
});

Categories