This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 6 years ago.
I've just started with php and js (jquery) and need help. I'm trying to do smth like betting service.
1. On html page user choose racecoast, using jquery I send its ID to php file, and it loads timetable:
like this:
while($row = mysqli_fetch_array($result)) { if ($row['date_time'] > date("Y-m-d h:i:sa")){
echo "<tr>";
echo "<td colspan='6' class='race' style = 'font-size: 14pt;' id = '".$row['raceID']."' >" . $row['raceID'] . "</td>";
it works.
2. Then, in the same php file I use
echo "<script type='text/javascript'>
$(document).ready(function(){
$('.race').click(function() {
var elid = $(this).attr('id');
and js perfectly gets the ID of racecoast.
But I can't send elid value back to php.
I've tried to use simple $_[GET], sessions, cookies, to set value on some attrib in my html and then get it, created one more php file, to send information there by load(...) function. Maybe, I did something wrong?..
I feel that my script should be in php file, but how to be then?
my last try, and more code:
while($row = mysqli_fetch_array($result)) { // if ($row['date_time'] > date("Y-m-d h:i:sa")){
echo "<tr>";
echo "<td colspan='6' class='race' style = 'font-size: 14pt;' id = '".$row['raceID']."' >" . $row['raceID'] . "</td>";
echo "<td colspan='6' class='race' style = 'font-size: 14pt;'id = '".$row['raceID']."'>" . $row['date_time'] . "</td>";
echo "<td colspan='6' class='race' style = 'font-size: 14pt;'id = '".$row['raceID']."'>" . $row['special_title'] . "</td>";
echo "</tr>";//} }
echo "</tbody>
</table>";
echo "
<script type='text/javascript'>
$(document).ready(function(){
$('.race').click(function() {
var nid = $(this).attr('id')
alert(nid);
document.cookie = 'newid=' + nid;
});});
</script>";
$choise = $_COOKIE["newid"];
echo $choise;
To give you a short example, using $.post():
jQuery:
$(document).ready(function() {
$('.race').click(function() {
var elid = $(this).attr('id');
$.post('path/to/your/phpfile.php', {
'elid': elid
});
});
});
And to recieve the data in your PHP-file:
$elid = $_POST['elid'];
Some sidenotes:
Is it really necessary to echoing the total javascript in PHP? Would be better to create a seperate JS-file for that.
But without seeing your whole script it's hard to say if there are other issue present.
Related
I am making a cart-mechanism with jquery, ajax and php. The problem is that the text in the html element aren't getting appended to the session array. This is my ajax code:
$(document).ready(function(){
$("#cart").on("click", function(){
var name = $("#name").text();
var cost = $("#cost").text();
$.ajax({
type:"post",
data:"name="+name+"&cost="+cost,
url:"senddata.php",
success:function(data){
$("#info").html(data);
}
});
});
});
This is my html displayed with php:
function getData()
{
require_once('../config.php');
$query = mysqli_query($conn, "SELECT p_name, p_cost, p_pic, p_desc FROM products");
while($row = mysqli_fetch_assoc($query))
{
echo "<form><tr>";
echo "<td id='name' name='name'>" . $row['p_name'] . "</td>";
echo "<td id='cost' cost='cost'>" . $row['p_cost'] . "</td>";
echo "<td>" . $row['p_pic'] . "</td>";
echo "<td>" . $row['p_desc'] . "</td>";
echo "<td id='cart'><input type='button' id='submit' value='Add To Cart'></td><tr></form>";
}
mysqli_close($conn);
}
And finally, this is where I have stored the ajax variables in a session array:
session_start();
$_SESSION['cart_name'] = array();
array_push($_SESSION['cart_name'], $_POST['name']);
var_dump($_SESSION['cart_name']);
$_SESSION['cart_cost'] = array();
array_push($_SESSION['cart_cost'], $_POST['cost']);
var_dump($_SESSION['cart_cost']);
I am getting no error whatsoever but the items get appended to the array the first time, but after that, the variables don't get appended at all.
Variables does not appended because you initialize every time the
$_SESSION['cart_name'] = array();
$_SESSION['cart_cost'] = array();
That means that every time before you push the new data you empty the SESSION var.
I have many links which are dynamically created with PHP and now I want to add an onclick event.
while($row = mysqli_fetch_array($xyz)) {
echo "<tr>";
echo "<td><a href=\"test.php?parameter=". $row['z'] ."\" target=\_blank>" . $row['z'] . "</a></td>";
echo "</tr>";}
but I want like this:
while($row = mysqli_fetch_array($xyz) {
echo "<tr>";
echo "<td><a href=\"test.php?parameter=". $row['z'] ."\" target=\_blank>" . $row['z'] . onclick="test()"</a></td>";
echo "</tr>";}
is this possible?
I am not sure if I understood what exactly you are asking but I try to answer you the same:
You can't record a normal JS variable in a page session and then to access to it after the loading of a page.
For this case you can use cookies (that are accessible via server-side too):
// put this code into methods that users suggested you.
document.cookie = "value_selected=something"
and once page is loaded:
var cookies = document.cookie.split(';');
var value_selected = JSON.parse(JSON.stringify(cookies[YOUR_COOKIE].split("=")[0]))
or server side:
echo "<td><a href=\"test.php?parameter=". $row['z'] ."\" data-something=htmlentities($_COOKIE['value_selected']) target=\_blank>" . $row['z'] . "</a></td>"; //(example)
Or more simply, pass the value selected through query
?value_selected=something //elaborate the new link in the method users suggested you
and
in server-side, use $['GET'] to obtain all values in query string.
IMHO I think the first choice is simpler than second.
I hope I helped you
Try Like this
while($row = mysqli_fetch_array($xyz) {
echo "<tr>";
echo "<td><a class='myclick' href=\"test.php?parameter=". $row['z'] ."\" target=\_blank>" . $row['z'] . **onclick="test()"**</a></td>";
echo "</tr>";}
i have added a class to link as myclick
and in jquery
$(document).on('click','.myclick',function(e){
e.preventDefault();
alert('clicked');
});
You can try like this..just a simple way.
<script type="text/javascript">
function test(){
alert('test');
}
</script>
<?php
while($row = mysqli_fetch_array($xyz) {
echo "<tr>";
echo "<td><a href='your link' onclick='test()'></a></td>";
echo "</tr>";
}
?>
I am trying to update a MySQL database with checkboxes and PHP. I have read a lot of code examples online and read many questions on here but I seem to be stuck at the last hurdle.
My code first queries MySQL to bring back a list of users and then a checkbox (which is either 0 or 1 in MySQL) next to each one, indicating whether or not the user is completed.
What I am wanting to do is when the checkbox is checked, for that to update the MySQL database and update the column with 1, or if it is unchecked, for it to change the column to 2.
Here is my code so far:
HTML Snippet (Checkboxes):
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['Firstname'] . "</td>";
echo "<td>" . $row['Surname'] . "</td>";
echo "<td>" . $row['Department'] . "</td>";
echo "<td>" . $row['RequestedBy'] . "</td>";
echo "<td>" . $row['StartDate'] . "</td>";
echo "<td class='tbl-chk'> <input type='checkbox' name='WSCompleted' value='"; echo $row['ID'] . "'" ; if ($row['WSCompleted']=='1') { echo "checked='checked'";} echo "/></td>";
Here is my jQuery that successfully retrieves the values and IDs and then posts them:
$(document).ready(function(){
$('input[name=WSCompleted]').click(function(){
var wsCompleted = $(this).is(':checked') ? 1 : 0;
var wsCompletedID = $(this).attr('value');
$.ajax({
type: "POST",
url: "/usr-handler.php",
data: {id: wsCompletedID, wsCompleted: wsCompleted},
success: function(){
$('div.success').fadeIn();
}
});
return true;
});
});
And finally here is a snippet of my PHP:
$wsCompleted = $_POST['wsCompleted'];
$id = $_POST['wsCompletedID'];
$query = "UPDATE newusers SET WSCompleted = '$wsCompleted' WHERE id = '$id'";
mysqli_query($con, $query) or die(mysqli_error());
mysqli_close($con);
I am setting the value of the checkbox to what is actually the row ID in MySQL, then I can use the checkbox value to select the correct row in MySQL, and update it.
The problem I am having is that currently, how the code is, I get the following response from FireBug:
Unidentified index: WSCompletedID
After looking online it was suggested to change:
$id = $_POST['wsCompletedID'];
To:
$id = (ISSET($_POST['wsCompletedID']));
But doing so clears the error message, but then doesn't actually update the value on MySQL.
If I manually set the $id to something, the update works, but obviously that isn't right as it would only ever update the ID I have chosen it to.
I am completely stumped as to what is causing the problem. I have tried finding out online but cannot get anywhere with it.
Any help is greatly appreciated.
Thank you
You are loading data here in your javascript AJAX code
data: {id: wsCompletedID, wsCompleted: wsCompleted},
This will create the following $_POST array
id => whatever was in wsCompletedID
wsCompleted => whatever was in wsCompleted
So your PHP code should be looking for $_POST['id'] and $_POST['wsCompleted'] as these are the names you have given in your data:...
$wsCompleted = $_POST['wsCompleted'];
$id = $_POST['id'];
$query = "UPDATE newusers SET WSCompleted = '$wsCompleted' WHERE id = '$id'";
mysqli_query($con, $query) or die(mysqli_error());
mysqli_close($con);
HOWEVER: Your script is at risk of SQL Injection Attack
Have a look at what happened to Little Bobby Tables Even
if you are escaping inputs, its not safe!
Use prepared statement and parameterized statements
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a db table with several fields and i want to make a countdown with the integer value of one of the fields (as minutes). How can i loop and display the countdown of each of those rows in a php table using these values and adding or subtracting time in the process if I need to?
Table.php
$sql="SELECT * FROM List where depName='Admisiones' and personStatus='Espera'";
$result=mysqli_query($con, $sql);
echo "<table border='15' cellpadding='10' cellspacing='3' bordercolor='00FF00'>
<tr>
<th>Turno</th>
<th>Nombre</th>
<th>Apellido</th>
<th>Segundo Apellido</th>
<th>Id Studiante</th>
<th>Status</th>
<th>Multiples Motivos</th>
<th>Tiempo Categoria</th>
<th>Tiempo Estimando</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['listNum'] . "</td>";
echo "<td>" . $row['personName'] . "</td>";
echo "<td>" . $row['personLast'] . "</td>";
echo "<td>" . $row['secondLast'] . "</td>";
echo "<td>" . $row['stuId'] . "</td>";
echo "<td>" . $row['personStatus'] . "</td>";
echo "<td>" . $row['manyMotive'] . "</td>";
echo "<td>" . $row['categoryTime'] . "</td>";
echo "<td>" . $row['estimatedTime']"</td>"; //USE THE CLOCK.PHP TO MAKE A COUNTDOWN FOR EACH ESTIMATED TIME.
//And have the ability to add or substrac time if needed.
echo "</tr>";
}
echo "</table>";
Clock.php
<script>
$('.countdown').each(function(){
var minutes = $(this).data('minutes');
var count = $(this); //countdown
var id = $(this).id;
$(this).countdown({
date : Date.now() + (minutes * 60000),
refresh : 1000
});
setInterval(function(count)
var minuteValue = count.text();
$.ajax({
url : 'TEST.php', //I created to make the test..
type : 'POST',
data : {currentMin : minuteValue, id:id},
success : function(response){
console.log(response);
}
});
});
});
TEST.php
<?php
include 'Connection.php';
$minValue = mysqli_real_escape_string($con, $_POST['minuteValue']);
$ID = mysqli_real_escape_string($con, $_POST['id']);
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
$sql ="Update List SET estimatedTime='$minValue' WHERE listNum='$ID'";
mysqli_query($con,$sql);
mysqli_close($con);
?>
OK, here's how I would do it. I would delete clock.php and use something more sophisticated. For example this js plugin:
http://rendro.github.io/countdown/
Download the file and include it in your <head> tag. Make sure you include jquery before that.
Inside your table.php change this line:
echo "<td>" . $row['estimatedTime']"</td>";
to:
echo "<td><div class=\'countdown\' data-minutes=\'{$row['categoryTime']}\' id=\{$row['id']'\'></div></td>";
Basically your html for that countdown field has to look like this (PS:30 is dynamic number coming from 'categoryTime') :
<td><div class="countdown" data-minutes="30" id="16"></div></td>
In footer of that page or in your javascript file include this script:
<script>
$('.countdown').each(function(){
var minutes = $(this).data('minutes');
var id = $(this).id;
$(this).countdown({
date : Date.now() + (minutes * 60000),
refresh : 60000
});
var minuteValue = $(this).text();
setInterval(function(){
$.ajax({
url : 'url/to/php/file', //php file that updates your DB. Take the values from POST VAR.
type : 'POST',
data : {currentMin : minuteValue, id:id},
success : function(response){
console.log(response);
}
});
});
});
</script>
With this, you will loop thru each .countdown element, get its minutes from data-minutes attr, and tell the countdown plugin when timer should expire by adding those minutes to Date.now() value.
EDIT after your comment:
What you are looking for is node.js. That would be perfect for you. But I've updated the code anyways. It is not tested so I don't know if that's gonna work. It should be something like that. The only issue could (MAYBE) be in setting interval for each row in your table.
EDIT2
in php file, run query that updates rows in db
depending on your DB, see if you can get number of rows affected
if affected rows > 0, echo 1, otherwise echo 0
in Firebug (or similar) check the console message to see output of your php or any other errors
This might help you find where the problem lies
I've got a webpage that returns a dynamic number of rows from a mysql db, which is output to the webpage via table, of which the first column is a checkbox via the following code:
while($row = mysql_fetch_array($result))
{
$id = $row['circuit_id'];
echo "<tr>";
echo "<td align=\"center\"><input name=\"checkbox[]\" type=\"checkbox\" id=\"checkbox[]\" value=" . $row['circuit_id'] . "></td>";
if ($row['status_name'] == 'Disconnected') {
echo "<td><font color=\"red\">" . $row['status_name'] . "</font></td>";
} else {
echo "<td>" . $row['status_name'] . "</td>";
};
echo "<td>" . $row['circuit_name'] . "</td>";
echo "<td>" . $row['circuit_appID'] . "</td>";
echo "<td>" . $row['circuit_appID'] . "</td>";
echo "<td><img src=\"images/icons/application_edit.png \"></td>";
echo "<td><img src=\"images/icons/note_add.png \"></td>";
echo "</tr>";
}
echo "</table>";
below this data presentation, I've added a few HTML buttons (one of which is shown below) that will allow the user to do 'mass' updates on the shown data, in this particular case to change the status from one state to another via the checkbox selection.
echo "<table align=\"center\">";
echo "<tr>";
echo "<td>Set status to Migrated for selected records</td><td><img src=\"images/icons/application_edit.png \"></td>";
echo "</tr>";
echo "</table>";
Is there a way to get the list of checkboxes that have been selected without changing everything to forms, and using a simple html based button to submit the request to the server?
I've been looking for an online solution for something like this via javascript but haven't managed to find anything that matches what I need.
Thanks
I've tried to piece together a few bits and pieces to get where I need to be, but am not making much progress at all, here's the current code:
var obj = {}
$('#click').on('click', function() {
$('input[type="checkbox"]').each(function() {
var name = $(this).attr('id');
obj[name] = $(this).is(':checked') ? 1 : 0;
});
$.each(obj, function(key, value) {
alert(key + ' : ' + value);
});
console.log(obj);
});
how do I get the list of 'true' ie. ticked boxes into a string and update the button with a 'new' url?
Any help is appreciated...
jQuery has the option to select all checkboxes and submit them in the background via AJAX..
jQuery Selectors: http://api.jquery.com/category/selectors/
jQuery AJAX: http://api.jquery.com/jQuery.ajax/
Good luck and hope this helps you!