Ajax - Sending and Receiving - php

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;
}

Related

Item isn't deleted from database through ajax call

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

how to fetch the data from active directory as JSON?

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);

refresh jquery mobile div after getting data using php and ajax

php file:
if (mysql_num_rows($result) > 0) {
// output data of each row
while($row = mysql_fetch_assoc($result)) {
$orgID=$row["InstancesID"];
echo "description: " . $row["describtion"]. "<br><br>"." - Type: " . $row["type"]. "<br><br>". "-Amount: " . $row["amount"]. "<br><br>";
echo"<input type='button' onclick=SendID($orgID) value='updateee'/> <br><br>";
}
ajax function:
$(document).ready(function(){
$("#show").click(function(){
$.ajax({url: "http://127.0.0.1/testupdate.php?f=ShowAllInstances",
success: function(result){
//alert(result);
$("#divshow").html(result);
}});
});
});
this displays the returned data in html page I want to display them in jquery mobile page.
any help please

ajax success doesnt alert anything

I have an AJAX request and if get id succeeds I would like to alert the data.
If I print_r my PHP function I get the correct result.
My ajax:
$.ajax({
type: "GET",
url: "getQuestions.php",
datatype: "json",
data:{
compid: id[4].innerHTML
},
success: function(response){
alert(response);
}
});
My getQuestions.php:
<?php
include "functions.php";
getQuestions($_GET['compid']);
My function getQuestions($compid) in functions.php:
function getQuestions($compid){
$int=intval($compid);
$vastus=array();
$conn = dbconnect();
$sql="SELECT * FROM bet_question WHERE compid = $int";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
array_push($vastus,$row);
}
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
return json_encode($vastus);
}
If I do print_r(getQuestions("some valid id")) in getQuestion.php I get valid result and if I do var_dump($_GET['compid']) in getQuestion I'll get the correct id from ajax request.
If I check if the request is sent using inspect elements I get that request is sent with correct params, but the response is empty.
Instead of return you need to use echo and it should be updated as
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
array_push($vastus,$row);
}
echo json_encode($vastus);
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
exit;
You don't have to return the data, use echo instead, and set content type:
function getQuestions( $compid ) {
$int=intval($compid);
$vastus=array();
$conn = dbconnect();
$sql="SELECT * FROM bet_question WHERE compid = $int";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
array_push($vastus,$row);
}
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
#header( 'Content-Type: application/json' );
echo json_encode( $vastus );
exit;
}
Hope it helps

how i can insert data in mysql and retrieve simulteneously in php on the click of one button?

actually i want to send a comment to the each image and it should display just after clicking the button . I am able to do insert and retrieve the comment but it require refresh the page and i don't want to refresh....just like orkut.plz help me i m new in php...
thans to all............
insertimg.php
//________________________________________FOR INSERT COMMENT_____________________________________________________
if (isset($_POST['Submit']))
{
$sql = "INSERT INTO comment(imid, comm) values ('".mysql_real_escape_string(stripslashes($_REQUEST['imgId']))."', '".mysql_real_escape_string(stripslashes($_REQUEST['Comment']))."')";
//$sql = "INSERT INTO comment (com) VALUES ($_POST['Comment'])";
//$sql="UPDATE upload SET comm='$_REQUEST['Comment']'WHERE id='$_REQUEST['imgId']'";
if($result = mysql_query($sql ,$conn))
{
echo "submited:";
}
else
{
echo "<h1>problem </h1> ".mysql_error();
}
}
For display comment..
$page=$_GET["page"];
$sql = "select comm from comment where imid = '".$page."'";
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
echo"Comments:";
echo "<br>";
echo "<br>";
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
//echo $row['comm'];
echo "<textarea name=\"Comment\" style=\"background-color:#81F7BE;\">"; echo $row['comm']; echo "</textarea>";
//echo "<font>";
echo "<br>";
echo "<br>";
}
mysql_close($conn);
?>
You can solve it with AJAX.
You can use something like jQuery Ajax library.
$.ajax({
type: "POST",
url: "inserting.php",
data: "imid=1&comm=Hi",
success: function(msg){
alert( "Ajax Response: " + msg );
}
});

Categories