Get variable to pass to php form - javascript

I'm working on getting the following block of code to send the array variable 'row' to another page. The other page should pull the vendor_id from this array and help populate a form with database information. I'm completely lost at how to accomplish this as I am relatively new to web dev. Can someone point me in the right direction?
function operateFormatter(value, row, index) {
return [
'<a class="remove" href="javascript:void(0)" title="Remove">',
'<i class="fa fa-trash"></i>',
'</a>',
'<a class="view" href="viewVendor.php" title="View">',
'<i class="fa fa-eye"></i>',
'</a>'
].join('')
}
window.operateEvents = {
'click .view': function (e, value, row, index) {
sessionStorage.setItem("vendor_id", JSON.stringify(row));
},
'click .remove': function (e, value, row, index) {
$table.bootstrapTable('remove', {
field: 'id',
values: [row.id]
})
}
}
viewVendor.php
<?php
include 'config.php';
require './db_inc.php';
$user = $_SESSION['username'];
## Fetch records
$stmt = $conn->prepare("SELECT * FROM vendor_data");
$stmt->execute();
$Records = $stmt->fetchAll();
$data = array();
foreach($Records as $row){
$data[] = array(
"name"=>$row['name'],
"company"=>$row['company'],
"type"=>$row['type'],
"status"=>$row['status'],
"owner"=>$row['owner'],
"descr"=>$row['descr'],
"owner_email"=>$row['owner_email'],
"dept"=>$row['dept']
);
}
return json_encode(($data));
?>
<script>
alert(sessionStorage.getItem("vendor_id[1]"));
</script>
I have a php page that includes the above mentioned viewVendor.php file which should pass along the information. Maybe I'm over complicating things?

You could add the vendor_id to the query string in your a tag like (assuming 'row' is the vendor id value):
'<a class="view" href="viewVendor.php?vendor_id=' + row + '" title="View">',
Then in your viewVendor.php file, access it with:
$_GET['vendor_id']
Though you may want to validate the vendor id in the PHP if it's going to be used to query your db.

Related

Ajax - Response from another page

My HTML as follows, located in index.php
<div id="showDetails">
</div>
<div id="showList">
</div>
And my Ajax as follows, still in index.php
function funcReadRecord() {
var readrecord1 = "readrecord1";
var sometext = $('#SNOW_INC').val();
$.ajax({
url : "findsql.php",
type : 'post' ,
data : { readrecord1 : readrecord1,
sometext : sometext } ,
success : function(data, status){
$('#showList').html(data);
}
});
}
Now, I can return my list and view the required list (shown as a list group) in index.php.
I have a button in index.php that when clicked, runs the function.
<div>
<button type="button" onclick="funcReadRecord()" class="btn btn-primary">Search SQL (LIKE)</button>
</div>
The code in findsql.php as follows
if(isset($_POST['readrecord1']) && isset($_POST['sometext'])){
$displaysql = "SELECT * from datadump where short_description LIKE '%".$_POST['sometext']."%'";
$result = mysqli_query($conn, $displaysql);
if(mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_array($result)) {
$items[] = array(
"number" => $row['number'],
"priority" => $row['priority'],
"description" => $row['short_description']);
}
}
echo '<p class="lead">SEARCH SQL (LIKE)<p>';
echo '<div class="list-group">';
foreach($items as $result) {
?>
<a href="#" class="list-group-item list-group-item-action">
<div class="d-flex w-100 justify-content-between">
<h5 class="mb-1"><?php echo $result['number']; ?></h5>
<small></small>
</div>
<p class="mb-1"><?php echo $result['description']; ?></p>
<small><?php echo $result['priority']; ?></small>
</a>
<?php
}
echo '</div>';
}
All I'm doing is getting the data from MySQL and assigning them to array and listing them. I know I could do it directly but I need the array in some other function.
The question is how do I make details from the array to show in showDetails div tag when I click the list? Right now, the HREF is #. I could assign a function, but not sure where to write them.
If I should write a function to return them, should I write in index.php or findsql.php?
Thanks in advance.
I understand that you need individual record information in #showDetails div right ! then
step1: assign new function while clicking the particular item as onclick="funcReadRecord(number)", this should at findsql.php file.
step2: write an ajax function in index.php which will send that particular unique id or in your case number
function funcReadRecord(number) {
$.ajax({
url : "findsql.php",
type : 'post' ,
data : { id: number } ,
success : function(data, status){
$('#showDetails').html(data);
}
});
Step3: Write another function in findsql.php with else if block as checking id isset or not, change the query that takes the number or any key that gets only that particular record.
else if(isset($_POST['id'])){
$displaysql = "SELECT * from datadump where number = ".$_POST['id'].";
// remaining design code below
}
We can use the if-else statement to write multiple ajax calls as above.
Edited, Note: kindly ignore the syntax issue in the above code, concentrate on the process used to a single PHP file for multiple ajax calls using branching statements.

Entire database deletes instead of one row

I have been trying to delete a row in my mySQL database on the onclick of a delete button. But instead of the one mySQL row getting deleted, all rows in the database get deleted.
I am targeting just the specific ID, so I am unclear as to why all other ID's are getting deleted.
HTML:
<?php foreach ($movies as $movie) : ?>
<div class="col-4">
<div class="card card-cascade">
<div class="view gradient-card-header purple-gradient">
<h2><?php echo $movie['name']; ?></h2>
<p><?php echo $movie['genre']; ?></p>
</div>
<div class="card-body text-center">
<!-- Delete -->
<a type="button" class="btn-floating btn-small btn-dribbble delbutton" data-toggle="tooltip" data-placement="top" title="Delete" id="<?php echo $movie['id']; ?>"><i class="fa fa-trash-o" aria-hidden="true"></i></a>
</div>
</div>
</div>
<?php endforeach; ?>
JS:
$(function () {
// Tooltips Initialization
$('[data-toggle="tooltip"]').tooltip();
// Delete Movie
$(".delbutton").click(function() {
console.log('watch me')
var del_id = $(this).attr("id");
var info = 'id=' + del_id;
if (confirm("Sure you want to delete this post? This cannot be undone later.")) {
$.ajax({
type : "POST",
url : "../movieApp/delete.php", //URL to the delete php script
data : {id:info},
success : function() {
console.log("success");
},
error: function () {
console.log("failed");
},
});
$(this).parents(".record").animate("fast").animate({
opacity : "hide"
}, "slow");
}
return false;
});
});
PHP:
require 'config/config.php';
require 'config/db.php';
if($_POST['id']){
$id=$_POST['id'];
$delete = "DELETE FROM movies WHERE id=$id";
$result = $conn->query($delete);
}
if (mysqli_query($conn, $sql)) {
mysqli_free_result($result);
mysqli_close($conn);
echo "Worked!";
exit;
} else {
echo "Error deleting record";
}
You set ajax method POST, But Post data format is not correct as per your requirement.
Change your ajax Data like as
//var info = 'id=' + del_id;
var info = {
id : del_id
}
And
$.ajax({
/*...*/
data : info,
/*.../
});
And also check if your id field is string, If integer then change the Query string to -
#$delete = "DELETE FROM movies WHERE id='$id'";
$delete = "DELETE FROM movies WHERE id=$id";
Also change -
#$_POST['info']
$_POST['id']
Because, You didn't set $_POST['info'] anywhere in your code.
Note : And don't forget to console your correct Ajax URL
In your HTML use data-id="<?php echo $movie['id']; ?>" for the tag. Then in your JS you can pick up the value like so: var del_id = $(this).data("id");. I would also inspect element in your browser to see if you are in fact sending an "id" to your PHP script. If you are then possibly you may want to enable error debugging in your PHP script like so: error_reporting(E_ALL);
ini_set('display_errors', 1);. Also wouldn't hurt to change your SQL statement to something like this: $delete = "DELETE FROM movies WHERE id='" . $id . "'";. Good luck with this one doesn't sound too hard.

bring data from a JSON and show in a popup

I have a leaderboard where if you click on a name a popup is displayed : https://jsfiddle.net/pvwvdgLn/1/
In practice, I will pull the list of the leaderboard from a DB.What you see here in the list are static names of employees,just for reference. So,how do I assign names using data attributes and search for that name in the JSON?
There are various fields in the popup like: Name,Email,Date of birth etc which I want to display for the respective person whose name is clicked by the user.
I have below JSON which is fetching me the array which contains all these data of all the people in the list :
<?php
session_start();
$servername = "xxxxx";
$connectioninfo = array(
'Database' => 'xxxxxxxxxxxxx'
);
$conn = sqlsrv_connect($servername, $connectioninfo);
if (!$conn) {
echo 'connection failure';
die(print_r(sqlsrv_errors() , TRUE));
}
$q1 = "select top 10 *
from pointsBadgeTable
WHERE WeekNumber ='week51'
order by pointsRewarded desc";
$stmt = sqlsrv_query($conn, $q1);
if ($stmt == false) {
echo 'error to retrieve info !! <br/>';
die(print_r(sqlsrv_errors() , TRUE));
}
do {
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$result[] = $row;
}
}
while (sqlsrv_next_result($stmt));
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn); //Close the connnectiokn first
//Set content type to json
header('Content-Type: application/json');
//Echo a json object to the browser
echo json_encode($result);
?>
As can be seen in the query,it fetches JSON for all the top10 ,whose names can be seen in the list.
the html and JS related to the popup is here : https://jsfiddle.net/woef5mn6/
How can I display the respective data in the popup from the JSON only for the person whose name is clicked ?
please help me.
I have edited your fiddle to show how your problem can be solved. This is just a simple solution. It needs to modified according to your requirement.
Here is the fiddle
I am creating the employee list from your JSON and populating the ordered list
function employeeList() {
$("#myOL").empty();
$.each(employee, function(i,o) {
$("#myOL").append("<li><mark>" + o.EmployeeName + "</mark><small>" + o.score + "</small></li>");
});
}
Then onclick of the individual employee, i am getting his details from JSON by his name and then populating the popup details (as a best practice here - you should get the employee details by calling a service through ajax using a unique identifier [employeeId] ):
function getEmployeeByName(name) {
var index = -1;
var filteredObj = employee.find(function(item, i) {
if(item.EmployeeName === name){
index = i;
}
});
return employee[index];
}
Hope this helps!

Trying to delete an entry in a table. Query doesn't delete the row, no idea how to debug

I'm trying to delete an entry in my database using the code below. The javascript function takes me to index.php?delpost= with the correct "adventureID" but when I check my database the row is still there. I've very recently started using PDO so I'm wondering if the execute() statement might be the issue. $dbh connect to my database at the top of the page and it is working as it prints every row from the table I'm trying to delete rows from. My goal is to successfully delete a row when I call the javascript function. The issue is - it doesn't.
<script language="JavaScript" type="text/javascript">
function delpost(adventureID, title)
{
if (confirm("Are you sure you want to delete '" + title + "'" + " '" + adventureID + "'"))
{
window.location.href = 'index.php?delpost=' + adventureID;
}
}
</script>
<?php
if(isset($_GET['delpost'])){
$stmt = $dbh->prepare("DELETE FROM adventure WHERE adventureID = :adventureID");
$stmt->execute(array(':adventureID' => $_GET['delpost']));
header('Location: index.php?action=deleted');
exit;
}
?>
<?php
if(isset($_GET['action'])){
echo '<h3>Post '.$_GET['action'].'.</h3>';
}
try {
foreach($dbh->query("SELECT adventureID, title, postDate FROM adventure ORDER BY adventureID DESC") as $row) {
echo '<tr>';
echo '<td>'.$row['title'].'</td>';
echo '<td>'.date('jS M Y', strtotime($row['postDate'])).'</td>';
?>
<td>
Delete
</td>
<?php
echo '</tr>';
}
} catch(PDOException $e) {
echo $e->getMessage();
}
?>
Probably you are facing problem with MYSQL SAFE UPDATES being ON. To avoid it and be able to finally delete rows, you can engage in the following tactics:
SET SQL_SAFE_UPDATES = 0;
--- YOUR DELETE STATEMENT ---
SET SQL_SAFE_UPDATES = 1;
To check if you have SQL_SAFE_UPDATES enabled you can do by running:
SHOW VARIABLES LIKE 'sql_safe_updates'
Try to replace this code :
$stmt = $dbh->prepare("DELETE FROM adventure WHERE adventureID = :adventureID");
$stmt->execute(array(':adventureID' => $_GET['delpost']));
By the following :
$stmt = $dbh->prepare("DELETE FROM adventure WHERE adventureID = :adventureID");
$stmt->bindParam('adventureID', $_GET['delpost']);
$stmt->execute();
Explanation :
You can either : Use ":variable" in your query, then pass variables by binding them with the "bindParam" function.
Or : Use "?" in your query, and then pass variables in the "execute" function.
Full example can be found here : http://php.net/manual/fr/pdostatement.execute.php#example-1050

Jquery autocomplete custom HTML results

I'm building a search with jQuery UI Autocomplete (http://jqueryui.com/demos/autocomplete/)
I am also utilizing the jQuery UI Autocomplete HTML Extension so I can style the search nicely and display icons according to the category where the search result is in.
My problem is, when I click on a result which looks like this:
(Category Icon) Pink Floyd - Category
It comes out like this in the search input field:
<div class="search_icons"><img src="images/ico/search_icon_rock.png" class="search_pic_radius"></div>Pink floyd<div class="autocomplete_category"> Rock</div><div class="artist_id_search">15</div><div class="artist_name_search">pink-floyd</div>
This is how my search.php looks like:
if (isset($_GET['term'])){
$return_arr = array();
try {
$conn = new PDO("mysql:host=".DB_SERVER.";port=8889;dbname=".DB_NAME, DB_USER, DB_PASSWORD);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT url_name,name,category,id FROM artists WHERE name LIKE :term OR category LIKE :term LIMIT 10');
$stmt->execute(array('term' => '%'.$_GET['term'].'%'));
while($row = $stmt->fetch()) {
if($row['category'] == '1') { $category_icon = '<div class="search_icons"><img src="images/ico/search_icon_rock.png" class="search_pic_radius"></div>'; }
if($row['category'] == '2') { $category_icon = '<div class="search_icons"><img src="images/ico/search_icon_pop.png" class="search_pic_radius"></div>'; }
$return_arr[] = $category_icon . $row['name'] . '<div class="autocomplete_category"> ' . $row['category'] . '</div>'. '<div class="artist_id_search" id="artist_id_search">' . $row['id'] . '</div>'. '<div class="artist_name_search" id="artist_name_search">' . $row['url_name'] . '</div>' ;
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
echo json_encode($return_arr);
}
What I'm trying to achieve is, when clicking on something on the autocomplete it should submit the form with the value from the last two div's artist_id_search and artist_name_search so on submit the next page would become whatever.php?id=15&artist=pink-floyd
What I have tried is to remove the unnecessary parts from the search string with the split function but then I just ended up with the id and the url_name parameters in the search field which didn't really achieve anything also it didn't really work reliably with changing icon names and such.
Well instead of returning HTML from the PHP service you have made in JSON, you should be returning a proper JSON like in the form of
[
{"id":"15","name":"pink-floyd","value":"Pink Floyd"},
{...
]
then handle it in your javascript as:
$( "#your_input_id" ).autocomplete({
source: "your_php_page.php",
minLength: 2,
select: function( event, ui ) {//callback function when you select an item
log( ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id :
"Nothing selected, input was " + this.value );
window.location.href = 'whatever.php?id=ui.item.id&artist=ui.item.name';
}
});
Hope you get it sorted :)

Categories

Resources