Parsing JSON response from PHP by array index. How? - php

I would like to know what is the latest JQuery syntax for parsing a JSON response by array index from a HTTP GET or POST request. My server side works great so I am look for way to parse the table row returned by PHP.
Here is my SERVER SIDE PHP code:
function qry_select_account($pk_account) {
// Global variables
Global $db_host, $db_user, $db_pass, $db_name;
// Connect to database server
$dbc = mysql_connect($db_host, $db_user, $db_pass) or die(mysql_error());
// Select target database
mysql_select_db($db_name) or die(mysql_error());
// suchislife801 <--- Selects account information
// Run query
$sql_qry = mysql_query("SELECT * FROM tblaccount
WHERE pk_account = '$pk_account'") or die(mysql_error());
// SQL Criteria AND acc_confirmed = 'y' AND acc_locked = 'n'
// Fetch table row for this user
$row = mysql_fetch_row($sql_qry);
print json_encode($row);
//echo 'Account: ' . $row[0];
//echo '<br />';
//echo 'Passowrd: ' . $row[1];
//echo '<br />';
//echo 'Acc Level: ' . $row[2];
//echo '<br />';
//echo 'Email: ' . $row[3];
//echo '<br />';
//echo 'Language: ' . $row[4];
//echo '<br />';
//echo 'Time Zone: ' . $row[5];
//echo '<br />';
//echo 'Signup: ' . $row[6];
//echo '<br />';
//echo 'Conf Code: ' . $row[7];
//echo '<br />';
//echo 'Confirmed: ' . $row[8];
//echo '<br />';
//echo 'Locked: ' . $row[9];
mysql_free_result($sql_qry);
// Close Connection
mysql_close($dbc);
}
Here is my JQuery code which is not working.
<script type="text/javascript">
$(function(){
$('#test_btn').live('click', function() {
$.getJSON("http://localhost/api.php?call=select_account&p0=suchislife801", function(json){
alert("JSON Data: " + json);
});
});
</script>

You can use jQuery.parseJSON( json ) function.
Make sure that json returned from server is a valid json
You can validate json response from here
Use following to check if error is returned by server
$.getJSON("example.json", function(data) {
alert(date);
})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
);
looping through json depends on type of json
if its a map type structure, like following
var map = {
"data1": "value1",
"data2": "value2"
};
you can use following to iterate through
$.each(map, function(key, value) {
alert(key + ': ' + value);
});
Reference: http://api.jquery.com/jQuery.each/

Related

Ajax - Sending and Receiving

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

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

Http Get and PHP

On my website, I'm using ajax to send data to an external php script, which queries a database and returns the result to the website. I ran into the problem, that I can only return strings with php, but I want to return an array of objects (which is valid json). My code looks like this at the moment:
php
$connection = mysqli_connect($adrs, $usr, $pw, $db);
if(mysqli_connect_errno()) {
die(mysqli_connect_error());
}
if($_GET["feed"] == "hausaufgaben") {
$query = "SELECT fach, aufgabe, datum FROM hausaufgaben WHERE fachgruppe != '";
if($_GET["fremdsprache"] == "latein") {
$query .= "französisch";
}
else {
$query .= "latein";
}
$query .= "' AND fachgruppe != '";
if($_GET["englisch"] == "koch") {
$query .= "schopper";
}
else {
$query .= "koch";
}
$query .= "' AND datum > '" . date("Y-m-d") . "' ORDER BY datum ASC;";
$result = mysqli_query($connection, $query);
$data = [];
while($row = mysqli_fetch_row($result)) {
$object = '{"fach": "' . $row[0] . '", "datum": "' . $row[2] . '", "aufgabe": "' . $row[1] . '"}';
array_push($data, json_decode($object));
}
echo $data;
}
ajax
$.ajax({
type: "GET",
url: "php/getFeed.php",
cache: false,
dataType: "json",
data: {feed: "hausaufgaben", fremdsprache: this.fremdsprache, englisch: this.englisch}
})
.done(function(data, textStatus, jqXHR) {
alert(typeof(data));
this.hausaufgaben = data;
})
.fail(function(jqXHR, textStatus, error) {
alert("error: " + error);
});
It always throws the error "Unexpected token A". I got it to return each single line in the array as string, but I can't use a string in my website. My problem is, that I can't echo an array of objects with php and get the array with ajax.
Instead of trying to build a json string yourself you can do it all much easier by building the $data array using PHP data structures and then using json_encode() to convert it all to a JSON string for sending to your javascript.
Reference json_encode and json_decode
Like this :-
$data = [];
while($row = mysqli_fetch_object($result)) {
$data[] = $row;
}
echo json_encode($data);
You will also have to change you javascript to process an array of objects rather than a string, but that should be easy

ajax.reload from mysql server has error: property is undefined

I am gathering live data from a mysql database using php and ajax. I want the data to be live updated every 2 seconds.
My code displays the chart and data as I want it, but does not live update the data from the database. The piece of code meant to be doing that is:
setInterval(function(){
jsonData.ajax.reload();
}, 2000);
And I think the error lies somewhere there as when I inspect the element with google chrome it tells me "Uncaught TypeError: Cannot read property 'reload' of undefined".
Here is the full JS code:
<script type="text/javascript">
// load chart lib
google.load('visualization', '1', {
packages: ['corechart']
});
// call drawChart once google charts is loaded
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "php/connection3_temp.php",
dataType:"json",
async: true
}).done(function (results) {
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'Time');
data.addColumn('number', 'Ambient Temp.');
data.addColumn('number', 'Object Temp.');
data.addColumn('number', 'Humidity');
$.each(results, function (i, row) {
data.addRow([
(new Date(row.timestamp)),
parseFloat(row.amb_temp),
parseFloat(row.obj_temp),
parseFloat(row.hum)
]);
});
var options = {
title: 'Temperature and Humidity against Time',
legend: { position: 'bottom' },
series: {
0: {targetAxisIndex: 0},
1: {targetAxisIndex: 0},
2: {targetAxisIndex: 1}
},
vAxes: {0: {title: 'Temp. (°C)',
minValue: 0,
maxValue: 30
},
1: {title: 'Humidity (%)',
minValue: 20,
maxValue: 80
}
},
hAxis: {
title: 'Time (s)'
},
};
var chart = new google.visualization.LineChart($('#temp_chart').get(0));
chart.draw(data, options);
});
setInterval(function(){
jsonData.ajax.reload();
}, 2000);
}
</script>
and also the PHP:
<?php
$servername = "localhost";
$username = "root";
$password = "raspberryblue";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM sensortag3 ORDER BY id DESC LIMIT 3000";
$result = $conn->query($sql);
// All good?
if ( !$result ) {
// Nope
$message = 'Invalid query: ' . mysqli_error() . "<br>";
$message .= 'Whole query: ' . $sql;
die( $message );
}
// Print out rows
$prefix = '';
echo "[\n";
while ( $row = mysqli_fetch_assoc( $result ) ) {
echo $prefix . " {\n";
echo ' "timestamp": "' . $row['timestamp'] . '",' . "\n";
echo ' "amb_temp": "' . $row['amb_temp'] . '",' . "\n";
echo ' "obj_temp": "' . $row['obj_temp'] . '",' . "\n";
echo ' "hum": "' . $row['hum'] . '"' . "\n";
echo " }";
$prefix = ",\n";
}
echo "\n]";
$conn->close();
?>
There's no property named reload() in your script. That's why the console is showing undefined property reload(). So add the reload method inside ajax() for refreshing the data.

Get response text back from php after ajax request

I want to add data to my database, and get back the response from php which accesses the database.
javascript code:
var request = $.ajax({
type: "POST",
url: "nieuwDuel.php",
data: dataString,
success: function(response)
{
var responseText = "onbekend";
responseText = jQuery(response);
document.getElementById("duelToegevoegd").innerHTML=responseText;
$( "#openstaandeDuels" ).load( "getOpenstaandeDuels.php" );
}
});
So when the a name isn't valid or is already in existence, I can add this message to a span element in my html.
This is my php code:
<?php
if($_POST)
{
// Create connection
$con=mysqli_connect("localhost","root","root","websitedb");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$date = getdate();
$date_time = $date['year'] . "-" . $date['mon'] . "-" . $date['mday'] . " " . $date['hours'] . ":" . $date['minutes'] . ":" . $date['seconds'];
$uitdagerArray = mysqli_query($con,"SELECT id FROM deelnemers WHERE naam='" . $_POST['uitdager'] . "'");
$uitgedaagdeArray = mysqli_query($con,"SELECT id FROM deelnemers WHERE naam='" . $_POST['uitgedaagde'] . "'");
$uitdager = mysqli_fetch_array($uitdagerArray);
$uitgedaagde = mysqli_fetch_array($uitgedaagdeArray);
$uitdagerId = $uitdager['id'];
$uitgedaagdeId = $uitgedaagde['id'];
$sql="INSERT INTO duels (uitdager, uitgedaagde, aanmaakdatum, gespeeld) VALUES ('" . $uitdagerId . "','" . $uitgedaagdeId . "','" . $date_time . "','" . "0" . "')";
if(!mysqli_query($con,$sql)) {
echo mysql_errno() . ": " . mysql_error() . "\n";
}
else {
echo "Duel Toegevoegd";
}
mysqli_close($con);
}
?>
So is it possible that the text from echo in my php code will be passed to the 'response' from the succes function?
edit:
this is my html code
<div id="nieuwDuel">
<h2>Nieuw Duel</h2>
<form name="form" method="post">
Uitdager: <input type="text" id="naamUitdager" placeholder="naam uitdager">
Uitgedaagde: <input type="text" id="naamUitgedaagde" placeholder="naam uitgedaagde">
<input type="submit" class="nieuwDuelToevoegen">
</form>
<span id="duelToegevoegd" style="display:none"></span>
Home
</div>
I assume that your PHP code is right. then what you need to change is your jQuery code.
just change the following code :
responseText = jQuery(response);
document.getElementById("duelToegevoegd").innerHTML=responseText;
into following :
responseText = response;
$('#duelToegevoegd').html(responseText);
I don't know what you are going to do with
$( "#openstaandeDuels" ).load( "getOpenstaandeDuels.php" );
So, I leave it out for now
hope it helps
Yes it should work. Try changing your JS to
var request = $.ajax({
type: "POST",
url: "nieuwDuel.php",
data: dataString,
success: function(response)
{
console.log(response);//This will output the response you are getting to the console so you can check it
$("#duelToegevoegd").html(response);
$( "#openstaandeDuels" ).load( "getOpenstaandeDuels.php" );
}
});
Also I wouldn't echo out any errors you get back to the client
echo "Failed to connect to MySQL: " . mysqli_connect_error();
Although it depends who the user is, but you don't want anyone unauthorised to see these errors

Categories