How to access array in if statement? - javascript

I have an admin panel for an application. For this admin panel, the admin has the option to select a user from a dropdown list. When the user is selected, I use an AJAX call to grab the users data and store it in a variable called $result. Now when I try to access $result outside of the if statement in my HTML file, it is not recognized. What are the possible ways I can access this variable?
HTML file (AJAX call)
$(document).ready(function(){
$('#user').change(function() {
var user_id = $(this).val();
$.ajax({
url: 'adminNew.php',
method:'POST',
data: {user_id : user_id},
success: function(data) {
alert(user_id);
}
});
});
});
Php file (if statement)
if (isset($_POST["user_id"])) {
if ($_POST["user_id"] != '') {
$sql = "SELECT * FROM user_data WHERE user_id ='".$_POST["user_id"]."'";
}
$result = mysqli_query($connect, $sql);
}
HTML file (table)
<tr>
<tbody id="expBody">
<?php
if ($result != ''){
while($row1 = mysqli_fetch_array($result)) {
echo '
<tr id = '.$row1["id"].'>
<td> '.$row1['user_id'].'</td>
<td> '.$row1['name'].'</td>
<td> '.$row1['email'].'</td>
<td> '.$row1['city'].'</td>
<td> '.$row1['state'].'</td>
<td> '.$row1['zip'].'</td>
';
}
}
?>
</tbody>
</tr>

Your PHP code needs to send something back to the ajax request
i have seen this done as below before
if (isset($_POST["user_id"])) {
if ($_POST["user_id"] != '') {
$sql = "SELECT * FROM user_data WHERE user_id ='".$_POST["user_id"]."'";
}
$result = mysqli_query($connect, $sql);
echo $result;
die;
}

you can load the new table into your #expBody via jquery:
$('#user').change(function() {
var user_id = $(this).val();
$("#expBody").load("yourphpfile.php?userid="+userid);
});
and in your phpfile you actualy "make" the table out of the result..
<?php
$userid = $_GET["userid"];
// make your db query
if ($result != ''){
while($row1 = mysqli_fetch_array($result)) {
echo '
<tr id = '.$row1["id"].'>
<td> '.$row1['user_id'].'</td>
<td> '.$row1['name'].'</td>
<td> '.$row1['email'].'</td>
<td> '.$row1['city'].'</td>
<td> '.$row1['state'].'</td>
<td> '.$row1['zip'].'</td>
';
}
}
?>
that way, this table will be put into your div!

Related

Changing input field based on other input field?

I want to have the datalist from "Serienummer" change based on what "Product" is chosen.
<td>Product</td>
<td>
<Select name="ProductID" placeholder="Productnaam" required>
<?php
$query2 = "SELECT DISTINCT ProductID FROM HW_Serial WHERE Prefix = '$prefix'";
$result2 = mssql_query($query2);
$numRows = mssql_num_rows($result2);
while($row = mssql_fetch_array($result2))
{
$DisProductID=$row["ProductID"];
$query3 = "SELECT ProductID, ProductName FROM Products WHERE ProductID = '$DisProductID' order by ProductName";
$result3 = mssql_query($query3);
$numRows = mssql_num_rows($result3);
while($row = mssql_fetch_array($result3))
{
$xProductID=$row["ProductID"];
$xProductName=$row["ProductName"];
if ($ProductID == $xProductID) {
echo "<OPTION value =\"$xProductID\">$xProductName</OPTION>";
} else {
echo "<OPTION value =\"$xProductID\">$xProductName</OPTION>";
}
}
}
?>
</select>
</tr>
<tr>
<td>Serienummer</td>
<td>
<input list="devicesn" name="devicesn" autocomplete="off" placeholder="Serienummer" required>
<datalist id="devicesn">
<?php
$query2 = "SELECT devicesn FROM HW_Serial WHERE ProductID = '$ProductID' order by devicesn";
$result2 = mssql_query($query2);
$numRows = mssql_num_rows($result2);
while($row = mssql_fetch_array($result2))
{
$xdevicesn=$row["devicesn"];
if ($devicesn == $xdevicesn) {
echo "<OPTION value =\"$xdevicesn\">$xdevicesn</OPTION>";
} else {
echo "<OPTION value =\"$xdevicesn\">$xdevicesn</OPTION>";
}
}
?>
My guess is that this has to be done by use of JavaScript but I'm a complete beginner when it comes to that.
Thanks in advance
You can redirect to current page with parameter when <select> changed. And receive the parameter in your php code in datalist section.
For example:
<select name="ProductID" placeholder="Productnaam" required onchange="location.href='?product' + this.value">...</select>
Then I just say sorry, I do not know how to receive url parameters like yourpage?p=project in PHP.

How to delete row after i select the row and press the button

Screenshot
<?php
if(isset($_GET['View']) && $_GET['View']=="HistoryEntry"){
echo '
<h2>History Of Entries</h2>
<table id="table" class="table table-hover">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Date In</th>
<th scope="col">Date Out</th>
<th scope="col">Rfid</th>
<th scope="col">Plate #</th>
</tr>
</thead>
<tbody>';
global $connection;
$query = "SELECT * FROM history_entries";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)){
echo '<tr>
<th scope="row">'.$row['Entry_ID'].'</th>
<td>'.$row['Date_in'].'</td>
<td>'.$row['Date_out'].'</td>
<td>'.$row['Acc_rfid'].'</td>
<td>'.$row['Plate_num'].'</td>
</tr>';
}
echo ' </tbody>
</table>
<center>
<button>Delete</button>
</center>
<div class="line"></div>';
}
?>
?>
$("#table tr").click(function() {
$('.selected').removeClass('selected');
$(this).addClass("selected");
});
$("#Sample").click(function() {
var value = $(".selected th:first").html();
value = value || "No row Selected";
});
As you can see this my codes, i already know how to select the row and get the ID but cant pass the ID "value" to php in order to do the delete function in database. can i use here $.POST function here? or is it better to use GET function here but i think it wouldn't be secure.
This is how you can do it without get param :
1/ Your FRONT :
HTML (just an example)
<table>
<tr id="row_id">
<td>Data 1</td>
<td>Data 2</td>
...
</tr>
...
</table>
<button id="delete_row" type="button">Delete</button>
JS / jQuery
var current_row_id = "";
// You select the row
$("#table tr").click(function() {
$('.selected').removeClass('selected');
$(this).addClass("selected");
current_row_id = $(this).attr("id"); // Here you get the current row_id
});
// You delete the row
$("#delete_row").on("click", function() {
$.ajax({
type: "POST",
url: "delete.php",
data: {"id" : current_row_id }, // You send the current_row_id to your php file "delete.php" in post method
dataType: 'json', // you will get a JSON format as response
success: function(response){
// you do something if it works
},
error: function(x,e,t){
// if it doesn't works, check the error you get
console.log(x.responseText);
console.log(e);
console.log(t);
}
});
});
2/ Your BACK
PHP "delete.php" file
<?php
$id = $_POST['id']; // You get the 'current_row_id' value
// Now you do your DELETE request with this id :
$sql = "DELETE ... WHERE id = :id";
etc...
$result = array(); // You can prepare your response and send information about what you did
$result['row_deleted'] = $id;
$result['message'] = "The row with id = " . $id . " was deleted with success";
$result['type'] = "success";
//etc....
echo json_encode($result); // You send back a response in JSON format
3/ Back to the FRONT
Your ajax call, the success part :
success: function(response){
// You can display a success message for example using your response :
alert(response.message); // You will get 'The row with id = {the row id} was deleted with success' here for example
},
Is it what you are looking for?
here is a simple Ajax request
var data = {
rowId: 1
};
$.ajax({
type: "POST",// GET|POST
url: 'delete.php', // Where you want to send data like url or file
data: data, // this is what you want to send to server, in this case i send data with id = 1 to server
dataType: 'json' // here we say what data type we want "json"
success: function(response) {
alert(response);
}, // this is the callback were u will get response from your server
});
delete.php here is how u can handle this ajax
$rowId = htmlspecialchars($_POST['rowId']);
if ($rowId) {
global $connection;
$query = "DELETE FROM history_entries WHERE Entry_ID = " . $rowId;
$result = mysqli_query($connection, $query);
$response = array(
'success' => true
);
echo json_encode($response);
exit;
} else {
echo json_encode(array('success' => false));
exit;
}
Hope this will help you to understand how to use Ajax

integrate ajax script in zf2 project

I want to save checkbox change using ajax.But I can't get any saved changes.
this is the view:actionacces.phtml
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
$title = 'Action \'s acces by role ';
$this->headTitle($title);
?>
<h1><?php echo $this->escapeHtml($title); ?></h1>
<table class="table">
<tr>
<th>Action</th>
<?php foreach ($roles as $role) : ?>
<th><?php echo $this->escapeHtml($role['name']); ?> </th>
<?php endforeach; ?>
</tr>
<tr><?php foreach ($actions as $action) : ?>
<th> <?php echo $this->escapeHtml($action['name']);
'<\br>' ?></th>
<?php
foreach ($roles as $role) :
$exist = 0;
foreach ($acls as $acl) :
if ($acl['fk_role_id'] == $role['id'] && $acl['fk_action_id'] == $action['id'] && $acl['acces'] == 1) {
$exist = 1;
}
endforeach;
?>
<th> <?php if ($exist == 1) { ?>
<label class="css-input switch switch-sm switch-primary push-10-t">
<input type='checkbox' class="checkboxAccess" id_role="<?= $role['id'] ?>" id_action="<?= $action['id'] ?>" acces="<?= $exist ?>" checked><span></span>
</label>
<?php } else { ?>
<label class="css-input switch switch-sm switch-primary push-10-t">
<input type="checkbox" class="checkboxAccess" id_role="<?= $role['id'] ?>" id_action="<?= $action['id'] ?>" acces="<?= $exist ?>" > <span></span>
</label>
</th>
<?php }
endforeach;
?>
</tr>
<?php endforeach; ?>
</table>
this is the droit.js:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
$(document).ready(function () {
$(".checkboxAccess").on('click', function () {
// console.log($(this).attr("id_role"));
// var role_id = $(this).attr("id_role");
// var action_id = $(this).attr("id_action");
// var droit = $(this).is(':checked');
console.log($(this).attr("id_role"));
var role_id = $(this).attr("id_role");
var action_id = $(this).attr("id_action");
var acces = $(this).is(':checked');
// alert(role_id);
// alert(action_id);
$.ajax({
type: "POST",
// url:'Privilege/ACL/addACL',
url: 'Detect/Acl/modifrole',
// data: {
// "id_role": role_id,
// "id_action": action_id,
// "droit": droit},
data: {
"id_role": role_id,
"id_action": action_id,
"acces": acces
},
Success: function (result) {
alert('Success');
console.log(result);
},
Error: function () {
alert('Error');
}})
});
});
this function in controller:
public function modifroleAction() {
$request = $this->getRequest();
// echo'<pre>'; print_r($this->getRequest());die;
if ($request->isPost()) {
$parametres = $this->params()->fromPost();
$acl = new Acl();
$acl->fk_role_id = $parametres['role_id'];
$acl->fk_action_id = $parametres['action_id'];
$acces = $parametres['acces'];
if ($acces == "false") {
$acl->acces = 0;
} else {
$acl->acces = 1;
}
$this->getAclTable()->saveAcl($acl);
return $this->redirect()->toRoute('acl');
}
}
Can you help me ?
You are trying to get data by $parametres['role_id'] and $parametres['action_id'] that means role_id and action_id
But you sending -
data: {
"id_role": role_id,
"id_action": action_id,
"acces": acces
},
that means id_role, and id_action.
Change your post index may work.

AJAX JQuery delete from html but not from mysql database

What is wrong here?
My PHP/HTML (The only part that matters):
if(isset($_POST['submit']))
{
$date = date('Y-m-d', strtotime(str_replace("-","/",$_POST['dateOfEntry'])));
$username = $_POST['user'];
$query = 'SELECT `ID`, `Date`, `Description`, `TypeOfDowntime`, `Machine#` FROM `machineissuesreport` WHERE `Date`="'.$date.'" AND `UpdatedBy` = "'.$username.'" ORDER BY `ID` DESC';
$conn = mysqli_query($connection, $query);
while($row = mysqli_fetch_array($conn))
{
echo '<tr>';
echo '<td style="text-align: center" width="5px"><input type="button" name="edit" value="Edit"></td>';
echo '<td style="text-align: center" width="5px">Delete</td>';
echo '<td style="display: none;"><input type="hidden" value='.$row['ID'].'></td>';
echo '<td>'.$row['Date'].'</td>';
echo '<td>'.$row['Description'].'</td>';
echo '<td>'.$row['TypeOfDowntime'].'</td>';
echo '<td>'.$row['Machine#'].'</td>';
echo '</tr>';
}
}
?>
My Ajax/Javascript:
$(document).ready(function()
{
$('.delete').click(function()
{
if(confirm("Are you sure you want to delete this row?"))
{
var del_id = $(this).attr('id');
var $ele = $(this).parent().parent();
$.ajax({
type: 'POST',
url: 'machineEntryLogEdit.php',
data: {'del_id':'del_id'},
success: function(data)
{
$ele.fadeOut().remove();
},
error: function (xhr, status, error)
{
alert(this);
}
});
}
});
});
My PHP (on an external script: machineEntryLogEdit.php):
include('connServer.php');
$deleteID = $_POST['del_id'];
$query = 'DELETE FROM `machineissuesreport` WHERE `ID` ="'.$deleteID.'"';
$result = mysqli_connect($connection, $query);
if(isset($result))
{
echo "YES";
}
else
{
echo "NO";
}
?>
I have searched around and around for solutions but no avail. The only things it does is delete the record from the HTML table, but not from the database, causing the supposed-to-be-deleted row to reappear after refresh. I am still very new to AJAX (in fact I just learned it myself today) and still reading the documentations and forums. Thanks.
This should be data: {'del_id': del_id} remove quotes so it react as a variable, not just a single string. And one more thing, your delete query does not execute cause you're using :
$result = mysqli_connect($connection, $query);
Should be mysqli_query like the one you did on selecting data's part:
$query = 'DELETE FROM `machineissuesreport` WHERE `ID` ="'.$deleteID.'"';
$result = mysqli_query($connection, $query);
It looks to me like you didn't pass the submit variable in your data. If you want to include a form you need to pass the data, right now the server is receiving only one parameter, del_id

Load more posts using ajax, php

I am displaying posts in a table and then trying to call more posts using ajax, but I am encountering problems here, on clicking show more same posts appear again so how to call next posts by id, and another problem is on clicking show more it changes to loading and remains their, I want it to hide after posts have been loaded.
I am calling the whole table again I think I would be better to call only rows. Here are my two files
index.php
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click','.show_more',function(){
var ID = $(this).attr('id');
$('.show_more').hide();
$('.loding').show();
$.ajax({
type:'POST',
url:'ajax_more.php',
data:'id='+ID,
success:function(html){
$('#show_more_main'+ID).remove();
$('#posts').append(html);
}
});
});
});
</script>
$sql = "SELECT * FROM posts order by id desc limit 6";
$query = $db->prepare($sql);
$query->execute();
$row = $query->fetch(PDO::FETCH_ASSOC);
$ID = $row['id'];
<div id="posts">
<table>
<tr>
<?php do { //horizontal looper?>
<td>
<div>id</div>
<div>title</div>
<div>body</div>
<div>date</div>
</td>
<?php
$row = $query->fetch(PDO::FETCH_ASSOC);
if (!isset($nested_List)) {
$nested_List= 1;
}
if (isset($row) && is_array($row) && $nested_List++%3==0) {
echo "</tr><tr>";
}
} while ($row); //end horizontal looper
?>
</table>
<div class="show_more_main" id="show_more_main<?php echo $ID; ?>">
<span id="<?php echo $ID; ?>" class="show_more" title="Load more posts">Show more</span>
<span class="loding" style="display: none;"><span class="loding_txt">Loading…</span></span>
</div>
</div>
ajax_more.php
<?php
include('db.php');
if(isset($_POST["id"]) && !empty($_POST["id"])){
$sql = "SELECT * FROM posts order by id desc limit 6";
$query = $db->prepare($sql);
$query->execute();
$row = $query->fetch(PDO::FETCH_ASSOC);
$ID = $row['id'];
?>
<table>
<tr>
<?php do { //horizontal looper?>
<td>
<div>id</div>
<div>title</div>
<div>body</div>
<div>date</div>
</td>
<?php
$row = $query->fetch(PDO::FETCH_ASSOC);
if (!isset($nested_List)) {
$nested_List= 1;
}
if (isset($row) && is_array($row) && $nested_List++%3==0) {
echo "</tr><tr>";
}
} while ($row); //end horizontal looper
?>
</table>
<div class="show_more_main" id="show_more_main<?php echo $ID; ?>">
<span id="<?php echo $ID; ?>" class="show_more" title="Load more posts">Show more</span>
<span class="loding" style="display: none;"><span class="loding_txt">Loading…</span></span>
</div>
<?php
}
?>
You will have to use OFFSET and LIMIT for your SQL Query. Currently you are using SELECT * FROM posts order by id desc limit 6. That isn't going to load you "more", as it will always only fetch the 6 biggest posts (ordered descending by their id).
You have a couple of problems.
When your AJAX call completes and you want the loading message to disappear, you need to hide that in your success callback of the ajax call. Like so:
$(document).on('click','.show_more',function(){
var ID = $(this).attr('id');
$('.show_more').hide();
$('.loding').show();
$.ajax({
type:'POST',
url:'ajax_more.php',
data:'id='+ID,
success:function(html){
$('#show_more_main'+ID).remove();
$('#posts').append(html);
$('.loding').hide();
}
});
});
In your SQL, you aren't doing anything to select alternative posts because after checking if the ID was sent. You don't do anything with it. Change your SQL to select id's greater than it if it exists.
$postedId = (int)$_POST['id'];
$sql = "SELECT * FROM posts order by id desc WHERE id > $postedId limit 6";
You want to make sure that the id is escaped to prevent any sort of SQL injection. So as a simple measure, I converted it to an integer (I am assuming on that). Otherwise, you should look into using prepared statements for your queries to prevent SQL injection. http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
Your SQL query needs to be fixed. Lets say you want to load the next 6 (ordered in descending order by ID). To do this, you should send some kind of variable like offset. Then you can say:
$sql = "SELECT * FROM posts ORDER BY id DESC LIMIT $offset, $end;"
Where $end = $offset + 6;
Before using this, though, be sure to check that $offset is numeric to prevent SQL injection. This could be implemented using:
if(i!sset($_POST["id"]) || empty($_POST["id"])){
die("No ID value present.");
}
$offset = (isset($_POST['offset']) ? $_POST['offset'] : 0);
if(!is_numeric($offset)){
die("Abnormal input detected.");
} else {
// Input is numeric
$offset = intval($offset);
}
$end = $offset + 6;
$sql = "SELECT * FROM posts ORDER BY id DESC LIMIT $offset, $end;"
/* Your code for actually querying the DB and processing results */
Note: I'm not too familiar with PDO, however, this should be compatible with PDO and safe/secure to use.

Categories

Resources