Not able to store ajax variables in session array - javascript

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.

Related

Updating mySQL table with user interface - PHP

[Sample Look]
I'm trying to make an interface where you can edit/add/remove fields of a mySQL database. This is how it looks visually, and I have all the functionality on the client side working.
My question is: How can I pass any edits/adds/removals to the server side? I'll include a link for my JSFiddle.
And the code below will show how I currently great the table.
<?php
$servername = "localhost";
$username = "lalalal";
$password = "lalalal";
$link = mysqli_connect("localhost", "lalala", "lalala", "lalala");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sqlStart = "SELECT `Name`, `EXT`, `Returning Time`, `Returning Date`, `Out`, `Reset`, `Booked` FROM `lalala`";
if($result = mysqli_query($link, $sqlStart)){
if(mysqli_num_rows($result) > 0){
echo "<table id = contactTable>";
echo "<tr id = row1>";
echo "<th id = sortTable onclick=sortTable(0)>Name ↕</th>";
echo "<th style = width:100px;>EXT</th>";
echo "<th style = width:300px;>Returning Time</th>";
echo "<th style = width:300px;>Returning Date</th>";
echo "<th style = width:70px;>Out</th>";
echo "<th style = width:100px;>Reset</th>";
echo "<th style = width:600px;>Booked</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
$currentCheck = $row['Out'];
if ($currentCheck == 0) {
echo "<tr>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['EXT'] . "</td>";
$currentTime = $row['Returning Time'];
if ($currentTime == 0) {
echo "<td> <form> <input type = 'time', id = 'timePickChange'> </form> </td>";
} else {
echo "<td> <form> <input type = 'time', id = 'timePickChange' value =" . $currentTime . "> </form> </td>";
}
$currentDate = $row['Returning Date'];
echo "<td> <form> <input type = 'date', id = 'datePickChange' value =" . $currentDate . "> </form> </td>";
echo "<td> <form onclick = 'checkIfOutRow(this)'> <input type = 'checkbox', onclick = 'checkIfOutValue(this)'> </form> </td>";
echo "<td> <button onclick = 'clearForm(this)', id = buttonClear>Reset</button> </td>";
echo "<td> <textarea rows = '1', cols = '60'> </textarea> </td>";
} else if ($currentCheck == 1) {
echo "<tr style = 'background-color: #E2E9FD'>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['EXT'] . "</td>";
$currentTime = $row['Returning Time'];
echo "<td> <form> <input type = 'time', id = timePickChange disabled> </form> </td>";
$currentDate = $row['Returning Date'];
echo "<td> <form> <input type = 'date', id = datePickChange disabled> </form> </td>";
echo "<td> <form onclick = 'checkIfOutRow(this)'> <input type = 'checkbox', onclick = 'checkIfOutValue(this)' checked> </form> </td>";
echo "<td> <button onclick = 'clearForm(this)', id = buttonClear>Reset</button> </td>";
echo "<td> <textarea rows = '1', cols = '60'> </textarea> </td>";
}
echo "</tr>";
}
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sqlStart. " . mysqli_error($link);
}
?>
Depending on your data validation model, you might want to control the inputs value client side before posting them to your back-end.
AFAIK, you're already adding/editing/removing your contacts on the client side, so If I understand correctly, when your user should click on Edit/Remove & confirm , it would be a confirmation of what the user has done in the browser, this doesn't really change much apart from the fact that otherwise you might need dedicated buttons/row (or any other bindable events).
For these operations what you could do is proceed to bulk delete / edit, and this could be easily done by filtering out in your JS all the modified/deleted data and sending it to your back end PHP with Ajax/jQuery in the form of a stringified array.
As for insertion operation you'd submit them at the same time you add them to your table, by executing a POST operation.
And it could be done with something like this :
$.ajax({
method: "PUT",
url: "some.php",
data: JSON.stringify(myUpdatedDataInAnArray)
// you might need to stringify your array to ensure format ?
})
.done(function( msg ) {
alert( "Data Updated: " + msg );
});
In your back end php, you'd listen for POST/PUT/DELETE methods with something like that :
if (isset($_POST['add'])){
do your thing
}
if (isset($_PUT['updated'])){
//Since you're sending a stringified array, you must parse it with
$myArray = json_decode($_PUT['updated']);
do your thing
}
if (isset($_DELETE['deleted'])){
do your thing
}
I say Ajax because using a traditional POST/PUT/DELETE form would result in refreshing the page.
Here are some useful refs :
JS JSON Stringify and JSON Parse
PHP : JSON DECODE and JSON Encode
Ajax docs
Ajax Examples

Execute AJAX from Main file after previously inserting data through AJAX

I have a questions for which I need some help.
I have a page which, after it is finished loading, executes an AJAX, creates a table in PHP containing 2 buttons: 1 change password, the other is delete. Once the table is complete it is injected into a div in the main file. That works great so far. Now after that table is loaded, I want to be able to call another AJAX function linked in the JS file in the main page. So I have 3 components:
1. <div id="DbInfo"></div>
That is where I add the information from the users.
my php which executes the code and gets the information from my database.
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT LoginName FROM table";
$res = mysqli_query($conn, $sql);
if (mysqli_num_rows($res) > 0) {echo "<center>";
echo "<table border='1'>";
echo "<tr>";
echo "<td>User</td>";
echo "<td colspan=2 align=center>Available Functions</td>";
echo "</tr>";
while($row = mysqli_fetch_assoc($res)) {
echo "<tr>";
echo "<td>" . $row['User'] . "</td>";
echo "<td><button type='button' class='smallbutton' id='removeUser' value='" . $row['LoginName'] . "'>Delete User</button></td>";
echo "<td><button type='button' class='smallbutton' id='CPW' value='" . $row['LoginName'] . "'>Change Password</button></td>";
echo "</tr>";
}
echo "</table>";
echo "</center>";
} else {
echo "";
}
mysqli_close($conn);
And lastly the AJAX which does the injection of the created table into the HTML:
$(document).ready(function(){
$.ajax({
method: "POST",
url: "UserData.php",
success: function(data){
//document.getElementById("DbInfo").innerHTML = data;
document.getElementById("DbInfo").html(data);
}
});
});
Again, these functions are working fine. What I want to do after the page is done, be able to click one of these injected buttons and execute another AJAX. Unfortunately the standard declaration that I use for AJAX does not work.
$(document).ready(function(){
$("#removeUser").click(function(){
The question: How can I make sure after the table is injected, that I can call an AJAX function which is linked as an external source (<script src="script.js"></script>) in the main document?
Thanks for your help.
try :
$('#DbInfo').on('click', 'button[id="removeUser"]', function(i,e){
console.log('remove :' + $(this).val());
});

Updating MySQL Database with checkboxes and PHP

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

Calling a POST variable in PHP-function

I have a PHP-file with multiple php functions in it.
I am sending a Javascript Variable with an AJAX-call, POST method to that PHP-file.`
Now the variable IS accessible in my PHP-file but not in that specific function where I want it...
$("#dropdown").change(function () {
var value = $("#dropdown").val();
console.log(value);
$.ajax({
type: "POST",
dataType: 'text',
url: "PhpFunctions.php",
data: {id:$("#dropdown").val()},
success: function (data) {
console.log(data);
$("div.geselecteerdVliegtuig").fadeIn("slow", function () {
console.log("Vliegtuigdetail faded in");
});
/*
$("div.vliegtuigenEnabled2").hide();
console.log("vliegtuigEnabled ID's hidden");
*/
},
error: function (err) {
alert('error: ' + err);
}
}); //END AJAX CALL`
//I CAN ACCESS DATABASE AND ID IS ACCESSIBLE HERE
//Connect to server
$connect = mysql_connect("localhost", "root", "root") or die(mysql_error());
//Connect to database
$select_db = mysql_select_db("Luchthaven") or die("Could not find database");
$id = $_POST['id'];
echo $id; //WORKS
//NEED TO ACCESS IS HERE
function GeselecteerdVliegtuig() {
makeConnection();
//Query the database
$id = $_POST['id'];
//$query = "SELECT * FROM vliegtuig WHERE vliegtuig_ID = 'PEG431';";
//echo "SELECT * FROM vliegtuig WHERE vliegtuig_ID = 'PEG431';<br/>";
$query = "SELECT * FROM vliegtuig WHERE vliegtuig_ID = '" . $id . "';";
echo "SELECT * FROM vliegtuig WHERE vliegtuig_ID = '" . $id . "';<br/>";
$fetch = mysql_query($query) or die("could not fetch data");
while ($row = mysql_fetch_assoc($fetch)) {
echo "<tr id=" . $row['vliegtuig_ID'] . ">";
echo "<td>" . $row['vliegtuig_ID'] . "</td>";
echo "<td>" . $row['maatschappij'] . "</td>";
echo "<td>" . $row['lengte'] . "</td>";
echo "<td>" . $row['breedte'] . "</td>";
echo "<td>" . $row['kilometerstand'] . "</td>";
echo "<td>" . $row['bouwjaar'] . "</td>";
echo "<td>" . $row['bereik'] . "</td>";
echo "<td>" . $row['aantalMotoren'] . "</td>";
echo "</tr>";
} // END WHILE
mysql_close(); //Make sure to close out the database connection
echo "<b>Connection closed<b><br/><br/>";
}
You can pass the $_POST['id'] variable to that function GeselecteerdVliegtuig($id) and call the function with GeselecteerdVliegtuig($_POST['id'])
Get rid of this line:
$id = $_POST['id'];
as you might want to use your functionality even if your value is not located in your $_POST["id"]. Modify your function header from
function GeselecteerdVliegtuig() {
to
function GeselecteerdVliegtuig($id) {
Call your function this way:
if (isset($_POST['id'])) {
GeselecteerdVliegtuig($_POST['id']);
}
and call your function from the page where you posted the value, make sure that the page where you posted exists, works and responds.
Finally, when everything is working change the way you are working with the database, because your current approach has a security leak due to SQL injection possibilities. What if I visit your page and execute the following in the console:
$("#dropdown").val("0'; delete from vliegtuig where '' = '");
and then trigger the post? It will remove every single record from your table unless you are making sure that these attempts fail.

how to get the wordID and send it to another php file

I have a table that third column of it is checkboxe, and first two columns of it come from database
I want to send the wordID of words that checked:
$result = mysql_query("SELECT * FROM words");
echo "<table border='1'>
<tr>
<th>word</th>
<th>meaning</th>
<th>checking</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['word'] . "</td>";
$idd= $row['id'] ;
echo "<td>". "<div class='hiding' style='display:none'>".$row['meaning']."</div>"."</td>";
echo "<td>";
echo "<input class=\"box\" name=\"$idd\" type=\"checkbox\" value=\"\"> ";
echo "</td>";
echo "</tr>";
}
echo "</table>";
and in my function I have this:
function feedback(){
var boxes = document.getElementsByClassName('box');
for(var j = 0; j < boxes.length; j++){
if(boxes[j].checked) {
assign=1;
}
else{
assign=0;
}
$.ajax({
url: "assigner.php",
type: "POST",
data: { wordid: wordid, assign: assign}
}).done(function( e ) {
/*alert( "word was saved" + e );*/
});
}
}
I dont know how can I get WordId from the first part and use it in second part that I said
Just put another form element outside of the table, like:
<input type="hidden" value="[id]" name="wordid_name" id="worid_id" class="wordid_class">
You only have to replace [id] with the id of the row, then on Javascript you can call the attribute you prefer:
var wordid= document.getElementsByClassName('worid_class').value;
var wordid= document.getElementsById('worid_id').value;
var wordid= document.getElementsByName('worid_name').value;
Can make it outside for structure, just below var boxex.
I recommend you to create an Javascript object with the values of the checkboxes and then call just 1 time to Ajax.
Hope it helps you.

Categories

Resources