I have a php class handler that I am using to create html output for my exercise-group.php page. However, this output (an array of items) is called on by using Jquery/AJAX and added to the page. However, there are some data values that are not displayed because they will be passed onto the exercise-single.php page. How can I gather these data values using jquery, load them into a php value and store them into a $_Session variable so the exercise-single.php can display these vars after the user clicks on on href tag. Sorry for the long post but this is the best I can do to explain what im trying to do.
Exercise.class.php
class Exercises {
public $vidSource;
public function displayExercises($result) {
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
echo "<div class='media'>" .
"<div class='media-object pull-left'>" .
"<a href='exercise-single.php'><img src='".$row["ImgResource"]."' class='img-responsive' alt='curl'></a>" .
"</div>" .
"<div class='media-body'>" .
"<h4 class='media-heading'><a href='#'>".$row["Exercise"]."</a></h4>" .
"</div>" .
"</div>";
$vidSource = $row["VidResource"];
}
} else {
echo "<img src='https://media.giphy.com/media/cwTtbmUwzPqx2/giphy.gif' class='img-responsive'>";
echo "<h3 class='media-heading'>No workouts exist for this muscle yet.<br>Please try another one.</a></h3>";
}
}
}
?>
ExerciseHandler.php
<?php
include 'Exercises.class.php';
include 'dbconnect.php';
if(isset($_POST['muscle'])){
$muscle =$_POST['muscle'];
$connect = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT * FROM exercises WHERE Muscle = '".$muscle."'";
$result = $connect->query($sql);
$exercises = new Exercises();
$exercises->displayExercises($result);
}
?>
loadExercises.js
var muscle_id;
function getMuscle(clicked_muscle){
muscle_id = clicked_muscle;
$.post("ExerciseHandler.php", {
muscle: muscle_id
},
function(data, status){
$("#exercise-list").html(data);
});
}
//Handler
echo $exercises->displayExercises($result);
//Exercise Class
public function displayExercises($result) {
if ($result->num_rows > 0) {
return json_encode(
array(
'status' => 'success',
'data' => $result->fetch_assoc())
);
} else {
return json_encode(
array(
'status' => 'error',
'data' => array(
'url' => "https://media.giphy.com/media/cwTtbmUwzPqx2/giphy.gif",
'class' => 'img-responsive',
'prompt' => 'Please try another one.'
)
)
);
}
}
// Jquery Here
$.ajax({
url : "ExerciseHandler.php",
method : "POST",
success : function(response){
var result = JSON.parse(response);
if(result.status == 'error'){
$('img').attr('src',result[0].url);
$('img').attr('class',result[0].class);
$('h3').text(result[0].prompt);
}else{
$.each(result.data,function(index,value){
// do the html append thing here
});
}
}
});
if you want to access data globally in all page per session you should create session like this in while block like this,
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
$_SESSION["name"] = $row["column_heading"];//create session
echo "<div class='media'>" .
"<div class='media-object pull-left'>" .
"<a href='exercise-single.php'><img src='".$row["ImgResource"]."' class='img-responsive' alt='curl'></a>" .
"</div>" .
"<div class='media-body'>" .
"<h4 class='media-heading'><a href='#'>".$row["Exercise"]."</a></h4>" .
"</div>" .
"</div>";
$vidSource = $row["VidResource"];
}
} else {
echo "<img src='https://media.giphy.com/media/cwTtbmUwzPqx2/giphy.gif' class='img-responsive'>";
echo "<h3 class='media-heading'>No workouts exist for this muscle yet.<br>Please try another one.</a></h3>";
}
}
this will work. and don't forget to start session in your php files. remember, you should start session on every page of your php files in which you are going to set or get session. You could do this by simply adding
session_start();
Related
I'm running around the issue which I don't really know how to solve - I simply want to remove uploaded file from the database, but I'm failing to do so.
My personal guess now is that my delete_shop_item.php doesn't work or that upload.php loop messes up the deletion process from the database (but that's only my guess).
Ajax:
$(document).on('click', '#rmvBtn', function() { /*press the button to remove selected item*/
del_title = $("#"+ $("#selectOpt").val()); /* select dynamically generated option to remove*/
$.ajax({
type: 'POST',
url: 'delete_shop_item.php',
cache: false,
processData: false,
data: {title:del_title.val()},
success: function() {
$("#" + $("#selectOpt").val()).remove();
$("#selectOpt option:selected").remove();
}
});
delete_shop_item.php
$title = $_POST['title'];
$pdo = new PDO('mysql:host=localhost;dbname=project', 'root', '');
$query = 'DELETE FROM photos WHERE title = :title';
$stmt = $pdo->prepare($query);
$stmt->bindPARAM(':title', $title);
$stmt->execute();
upload.php
<?php $count = 1;
while($data = mysqli_fetch_array($result)) {
if($count === 1) {
echo "<div class='img_container'>";
}
echo "<div class='img_div' id='".$data['title']."'>";
echo "<img src='uploads/" . $data['filename']."'>";
echo "<p class='img_title' >" .$data['title']. "</p>";
echo "<p class='img_desc'>" .$data['photo_description']. "</p>";
echo "<p>" .$data['price']. "</p>";
echo "</div>";
if($count % 5 === 0) {
echo "</div>";
$count = 1;
continue;
}
$count++;
}
?>
try data: {title:del_title} in ajax request
The code is supposed to fetch the query result and display it according to the number written in the text box, i tried (onkeydown and onkeyup) and both didn't work, i have no idea why it is not working and what is my mistake.
HTML code:
<script>
function showRoom(rid) {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "getRoomAJAX.php?q="+rid, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
}
</script>
<form>
<input type="text" name="rid" onkeydown="showRoom(this.value)">
</form>
<div id="txtHint">Room...</div>
getRoomAJAX.php code:
<?php
session_start();
ob_start();
$q = $_GET["q"];
$db = new Database();
$dbc = $db->getConnection();
if (!$dbc) {
die('Could not connect: ' . mysql_error());
}
$query = "SELECT * FROM indvProj_room WHERE rid = '".$q."'";
$result = mysqli_query($dbc, $query);
//start creating the table HTML
if ($result) {
echo "<table border='1' align='center' cellspacing = '2' cellpadding = '4' width='100%'>
<tr>
<th><b>Room ID</b></th>
<th><b>Room Description</b></th>
</tr>";
while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
echo "<tr>";;
echo "<td>" . $_SESSION['adminRoomChoice'] = $row['rid'] . "</td>";
echo "<td>" . $row['roomDesc'] . "</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo '<p class="error">Sorry, cannot find the room, are you sure of the entered Room ID?</p>';
echo '<p class = "error">' . mysqli_error($dbc) . '</p>';
}
?>
Does showRoom() get called at all? Put a console.log(rid); inside showRoom() to see if that is getting called and whether the value is being passed in correctly.
If you can determine that it's getting into the showRoom(), then follow the code down and into PHP to see where it's failing. Echo some sample text at the top of the PHP file with return; right below it. That will tell you if the error is in the XMLHttpRequest code or somewhere in the PHP file.
Normally, I don't pass any variables/params with onkeydown type of events. Usually, I call a method like this without params and then retrieve the value based on the element's id. See this answer for more detail on that: https://stackoverflow.com/a/54040431/3103434
I have 2 files, A .js and a .php. The .php connects to the MySQL DB and the .js is the front end of the system.
I'm in the middle of trying to set it up so it sends a hash key to the ajax which returns the correct data for the related person from the database.
So far it does work as it send the hash from the URL to the PHP file and returns back the data in the console log.
//AJAX Function
//Grabs Varibles from PHP
var hash = window.location.hash.substr(1);
$(function() {
$('.hashfield').text(hash)
});
$.ajax({
type: "POST",
async: false,
cache: false,
url: "SelectFromSQL.php",
//Sending URL password
data:{ hash: hash, WorkingHash : "yes" },
success: function(data){
//Return of AJAX Data
console.log(data);
},
error:function() {
console.log("FAIL");
}
})
This is within the .js file which sends the hash
<?php
if(isset($_REQUEST['WorkingHash'])){
$hash = $_POST['hash'];
function IDHASH($hash){
echo $hash;
}
IDHASH($hash);
}
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT ID, CustomerName, ContactName, Address, City, PostalCode, Country FROM customers WHERE ID=$hash";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["ID"] . "<br>";
echo $row["CustomerName"] . "<br>";
echo $row["ContactName"] . "<br>";
echo $row["Address"] . "<br>";
echo $row["City"] . "<br>";
echo $row["PostalCode"] . "<br>";
echo $row["Country"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
This is the .php file. I need to return the data from the database related to the correct customer ID.
All the data being echoed from the while loop will need it's own variably within a js format
My Goal is to retrieve each entry from the database
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["ID"] . "<br>";
echo $row["CustomerName"] . "<br>";
echo $row["ContactName"] . "<br>";
echo $row["Address"] . "<br>";
echo $row["City"] . "<br>";
echo $row["PostalCode"] . "<br>";
echo $row["Country"] . "<br>";
}
}
instead use
if ($result->num_rows > 0) {
// output data of each row
$row = $result->fetch_assoc();
print_r(json_encode($row));
}
and in js
javacript
$.ajax({
type: "POST",
async: false,
cache: false,
url: "SelectFromSQL.php",
//Sending URL password
data:{ hash: hash, WorkingHash : "yes" },
success: function(data){
//Return of AJAX Data
data = JSON.parse(data);
console.log(data);
//YOU CAN USE data.ID , data.CustomerName and so on
},
error:function() {
console.log("FAIL");
}
})
How about something like this:
Edit
instead of return data echo it like this:
if ($result->num_rows > 0) {
// echo the data instead of return
echo json_encode($result->fetch_assoc());
}
To access the properties of the object you can in your success function do that :
success: function(data){
// parse your data first
data = JSON.parse(data);
//Return of AJAX Data
console.log(data.CustomerName);
console.log(data.ContactName);
// you can assign them to a variables if you want
var customerName = data.CustomerName;
var ccontactName = data.CustomerName;
}
I have the below PHP file through which I am trying to make an ajax call and fetch my required data from the JSON array :
<?php
$username = 'xxxxxxxxxxxx';
$password = 'xxxxxxx';
$server = 'ldap://xxxxxxx';
$domain = '#asia.xxxxxxxx.com';
$port = 389;
$ldap_connection = ldap_connect($server, $port);
if (! $ldap_connection)
{
echo '<p>LDAP SERVER CONNECTION FAILED</p>';
exit;
}
// Help talking to AD
ldap_set_option($ldap_connection, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ldap_connection, LDAP_OPT_REFERRALS, 0);
$ldap_bind = #ldap_bind($ldap_connection, $username.$domain, $password);
if (! $ldap_bind)
{
echo '<p>LDAP BINDING FAILED</p>';
exit;
}
else
{
echo 'login successful';
}
$base_dn = "OU=Employees,OU=Accounts,OU=xxxxxx,DC=asia,DC=xxxxxx,DC=com";
//$dispname=$_POST['employeeID'];
$dispname="100676";
$filter ="(&(objectClass=user)(displayName=$dispname))";
$attr = array("sn","givenname","employeeid","distinguishedname","displayname","samaccountName","department","manager","mail","title","thumbnailphoto");
$result = ldap_search($ldap_connection,$base_dn,$filter,$attr);
$rescount = ldap_count_entries($ldap_connection,$result);
$data = ldap_get_entries($ldap_connection,$result);
// echo json_encode($data);
if ($data["count"] > 0)
{
for ($i=0; $i<$data["count"]; $i++)
{
echo "<p> sn: " . $data[$i]["sn"][0]."<br/>";
echo "givenname: ". $data[$i]["givenname"][0] ."<br/>" ;
echo "employeeID: " . $data[$i]["employeeid"][0]."<br/>";
echo "distinguishedName: " . $data[$i]["distinguishedname"][0]."<br/>";
echo "displayName: " . $data[$i]["displayname"][0]."<br/>";
echo "sAMAccountName: " . $data[$i]["samaccountname"][0]."<br/>";
echo "department: ". $data[$i]["department"][0]."<br/>";
echo "manager: " .$data[$i]["manager"][0]."<br/>";
echo "mail: ". $data[$i]["mail"][0]."<br/>";
echo "title: " .$data[$i]["title"][0]."<br/>";
echo "photo: " .$data[$i]["thumbnailphoto"][0]."<br/>";
echo "<br/><br/>";
}
}
else
{
echo "<p>No results found!</p>";
}
?>
The kind of output I am getting now :
<p> sn: xxxxxx<br/>givenname: xxxxx<br/>
employeeID: 0050<br/
>distinguishedName: CN=xxxx xxxxx,OU=Employees,OU=Accounts,OU=India,DC=asia,DC=xxxxxxx,DC=com<br/>
displayName: Mark Hewettk<br/>sAMAccountName: xxxxxxx<br/>
department: xxxxx<br/>manager: CN=xxxxxx xxxxxxx,OU=Employees,OU=Accounts,OU=India,DC=asia,DC=xxxx,DC=com
<br/>
mail: mhewettk#abc.com<br/>
title: xyz<br/>
photo :����%&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz���������������������������������������������������������������������������
I do not want to echo the data(I am doing so here to show you guys that it is fetching the correct data), I want it as JSON so that I may use it in my UI.
Kindly help me on how to fetch the data from active directory as JSON ?
JS involved :
$('.leaderboard li').on('click', function () {
$.ajax({
url: "../popupData/activedirectory.php", // your script above a little adjusted
type: "POST",
data: {id:$(this).find('.parent-div').data('id')},
success: function(data){
console.info(data);
data = JSON.parse(data);
$('#popup').fadeIn();
//whatever attributes you want to pull from active directory
error: function(){
alert('failed, possible script does not exist');
}
});
});
How about converting the array you get back from ldap_get_entries to a json object using json_encode
echo json_encode($data, JSON_PRETTY_PRINT);
Hey, I have been trying to get this pagination class that I am using to be more ajaxy - meaning when I click on the page number like page [2] the data loads, but I want to load in the data without going to a different page (HTTP request in the background, with no page reloads).
Being new to both php and jquery, I am a little unsure on how to achieve this result, especially while using a php class.
This is what the main page looks like by the way:
<?php
$categoryId=$_GET['category'];
echo $categoryId;
?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery_page.js"></script>
<?php
//Include the PS_Pagination class
include('ps_pagination.php');
//Connect to mysql db
$conn = mysql_connect('localhost', 'root', 'root');
mysql_select_db('ajax_demo',$conn);
$sql = "select * from explore where category='$categoryId'";
//Create a PS_Pagination object
$pager = new PS_Pagination($conn, $sql, 3, 11, 'param1=value1¶m2=value2');
//The paginate() function returns a mysql
//result set for the current page
$rs = $pager->paginate();
//Loop through the result set
echo "<table width='800px'>";
while($row = mysql_fetch_assoc($rs)) {
echo "<tr>";
echo"<td>";
echo $row['id'];
echo"</td>";
echo"<td>";
echo $row['site_description'];
echo"</td>";
echo"<td>";
echo $row['site_price'];
echo"</td>";
echo "</tr>";
}
echo "</table>";
echo "<ul id='pagination'>";
echo "<li>";
//Display the navigation
echo $pager->renderFullNav();
echo "</li>";
echo "</ul>";
?>
<div id="loading" ></div>
<div id="content" ></div>
Would I need to do something with this part of the class?, as seen above:
$pager = new PS_Pagination($conn, $sql, 3, 11, 'param1=value1¶m2=value2');
Or this?:
echo $pager->renderFullNav();
I don't no much about jquery,but i guess I would start it like:
$("#pagination li").click(function() {
Then load something maybe...
I don't no. Any help on this would be great. Thanks.
Im not sure how to go about it using that class, it seems it would be a bit tricky, as the script you make the ajax call to, to retrieve the data, will need to have access to the current PS_pagination instance.
Without the class though, it wouldnt be too tricky.
You would need a php script to actually return the data, which takes in the number of records per page, and the current page number. In this script, rather than returning the data, i return the html. So i take the data from the database, then generate the table. This means that all i have to do on success of ajax is replace what is in the able currently, with the new html that i get from this script. Heres an example..
//Current Page Number
$page_num = isset($_GET['page_number']) ? mysql_real_escape_string($_GET['page_number']) : 1;
//Number of records to show on each page
$num_records = isset($_GET['num_records_pp']) ? mysql_real_escape_string($_GET['num_records_pp']) : 10;
//Row to start collecting data from
$start_row = $num_records * ($page_num - 1);
//String to store html to return
$return_html = '';
//SQL Query
$sql = mysql_query("SELECT * FROM my_table LIMIT $start_row, $num_records");
//Query success
if($sql) {
//Construct html for table
$return_html = "<table width='800px'>";
while($row = mysql_fetch_array($sql) {
$return_html .= "<tr>";
$return_html .= "<td>" . $row['id'] . "</td>";
$return_html .= "<td>" . $row['site_description'] . "</td>";
$return_html .= "<td>" . $row['site_price'] . "</td>";
$return_html .= "</tr>";
}
$return_html .= "</table>";
//Query Failed
} else {
$return_html = "<p class='error'>Error Fetching Data</p>";
}
return $return_html;
Then you just make a get request via ajax and pass the page number, and the number of rows you want.
$.get("get_data.php", { page_number: 1, num_records_pp: 20 },
function(data){
$('div#my_table').html(data);
});
So, this query assumses that you have a div with an id of "my_table" which contains your table, it will then replace this with a new table consistion of just the data you requested.
This code was just to give you the jist, so i may have some errors in there, but hope it helps.