Background:
I have a page which dynamically pulls up a modal window, which displays extended information on a row (with multiple columns) through mySQL. I am having issues where my JSON code will not populate the information correctly so that it can be outputted. I have tried multiple nested arrays, while loops and for loops. However, I only need to return one full row of information from the database. After scratching my head, I am asking the help of all the SO experts. Any pointers are much appreciated.
Ajax Code For Div Population (Works)
var data_id = $(this).data('id');
$.ajax({
url: 'view_agency_info.php',
type: 'POST',
data: {id: data_id},
dataType: 'json',
success: function(data){
$('.view_modal_content').html(data.html); // LOAD THE DATA INTO THIS DIV
},
error: function(jqXHR, textStatus, errorThrown){
$('.view_modal_content').html(''); // LOAD THE DATA INTO THIS DIV
alert('Error Loading Information');
}
});
JSON Code To Pull Information and return HTML
<?php
$customer_id=$_SESSION['customer']['customer_id'];
$id = (int)$_POST['id'];
$query = "SELECT * FROM collections_list WHERE id={$id} && customer_id=$customer_id LIMIT 1"; //expecting one row
$result = mysql_query( $query );
//$message = mysql_fetch_assoc( $result ); //expecting just one row
$message=array();
while ($row = mysql_fetch_assoc($result)) {
$message[]=$row['agency_name'];
$message[]=$row['account_number'];
$message[]=$row['phone'];
}
$json = array();
$json['html'] = '<p><pre><code>id:'.$id.'.<br>Agency Name: '.$message[0].'<br>Account Number:'.$message[1]."<br>Phone:".$message[2].'</code></pre></p>'.'<br><br>test';
header('Content-Type: application/json');
echo json_encode( $json );
?>
Additional Question:
Is it possible to reference the headers in the array using " $message['agency_name'] "inside the html that gets returned?
After solving this problem, I will need to turn the outputted html into a structure to allow my users to view the information in a properly understandable format. I know how to do this in html, but I am unfamiliar with JSON... Is there a way to output the information without having to manually code the structure?
Thank you in advance.
$con = mysql_connect("localhost","user","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db(db_nname", $con);
$result = mysql_query("SELECT phone,agency_name FROM '''' ");
$rows = array();
while($r = mysql_fetch_assoc($result)) {
$rows['results'][] = $r;
}
print json_encode($rows);
?>
and in your html
<table id ="listtable"></table>
var listdiv = $("#listtable");
$.getJSON("whatever.php",function(json){
$.each(json.results,function(i,data){
listdiv.append("<tr><th>" + data.phone + "</th><th>" + data.agency_name + "</th></tr>");
});
});
and in the append use data. and whatever your fields are
data.agency_name
data.phone
etc....
Related
Kindly help me with the ajax / jQuery to fetch all the objects of a array.
I am using the following code and it doesn't work
$(window).on("load", GetAllProperties);
function GetAllProperties() {
$.ajax({
url: 'userdetailfetch.php', //the script to call to get data
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
$('#ph').html(data[0]);
$('#email').html(data[1]);
$('#name').html(data[2]);
$('#fname').html(data[3]);
$('#date').html(data[4]);
$('#course').html(data[5]);
$('#branch').html(data[6]);
$('#sem').html(data[7]);
$('#roll').html(data[8]);
}
});
}
fetchuserdetail.php
<?php
$cnx = mysqli_connect("localhost", "root", "", "loginerp");
$result = mysqli_query($cnx, "SELECT * FROM user_info WHERE id='" . $_SESSION['sessuser'] . "'");
$data = array();
while($row = mysqli_fetch_array($result)) {
$data[] =$row;
}
echo json_encode($data);
?>
I want to display all the details when the page loads .
Thanks for your help.
Start session in fetchuserdetail.php file
session_start();
Correct the page name
url: 'fetchuserdetail.php',
I want to check if a user has favourited an item but I'm unsure how to return the result of a database query to ajax.
I will show different html depending on the result.
Php
$query = "SELECT itemID from favourites WHERE userid = '" . $user. "'";
$result = mysql_query($query);
echo json_encode($result);
Jquery
$.ajax({
url: "inc/functions.php",
type: "POST",
data: {--result--},
success: function () {
// if result found in database
$('favourite').hide();
// if result not found
$('favourite').show();
}
});
I can't figure out how to display $result in the jquery code.
Any help much appreciated.
$result in this case is a PHP object representing a result.
You will have to use a fetch() method in order to extract the result before sending it back to your JS.
See this link. There's a list of all fetch-family method right above the comments.
Also, you will need to make a connection with you database beforehand using mysqli_connect (or mysql_connect in your case).
As stated in the comments, you should however use mysqli* functions family instead of mysql*.
Thanks to the comments for info regarding mysqli. I updated the code and solved the ajax part.
For anyone else stuck, I got it working like this:
PHP
require ("../../connection.php");
$sql = "SELECT * FROM favourites WHERE userID = ? AND itemID = ?";
$user = $_POST['userID'];
$item = $_POST['itemID'];
$statement = $db->prepare($sql);
if($statement === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $db->error, E_USER_ERROR);
}
$statement->bind_param('ii',$user,$item);
$statement->execute();
$statement->bind_result($user,$item);
while($statement->fetch()){
echo 1;
}
$statement->close();
Jquery
$.ajax({
url: "inc/userList.php",
data: userList,
type: "POST",
success: function (result) {
if (result == 1){
$('#addItem').css('display', 'none');
$('#removeItem').css('display', 'inline-block');
} else {
$('#addItem').css('display', 'inline-block');
$('#removeItem').css('display', 'none');
}
}
});
So I have an issue where I want to be able to query some data with the user's current location but I am still new to JSON and trying to figure out how to send the data back to the main page.
Here are the hidden inputs for the lat/lng values on the index.php page
<input type="hidden" id="latitude">
<input type="hidden" id="longitude">
Here is the code to send the lat/lng to tables.php from the index.php page
$.getJSON(GEOCODING).done(function(location) {
$('#latitude').html(position.coords.latitude);
$('#longitude').html(position.coords.longitude);
$.ajax({
url:'table.php',
method: 'POST',
dataType: 'json',
data:{
lat: $('#latitude').val(),
lng: $('#longitude').val()
},
success: function(data){
console.log();
}
});
});
I am using datatables to display the data on the index.php page.
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.css">
<script>
$(document).ready(function(){
var dataTable = $('#searchTable').dataTable();
$("#searchbox").keyup(function() {
dataTable.fnFilter(this.value);
});
});
</script>
echo'<table id="searchTable" class="display">
<thead>
<tr>
<th>Latitude</th>
<th>Longitude</th>
</tr>
</thead>
<tbody>
';
(data to display from tables.php)
echo'</tbody>
</table>
';
And then on the tables.php page I am pulling the data from the MYSQL database, now this is where I have to figure out how to send the data back to the index.php page through JSON and display it in the table.
<?php
require_once("connect.php");
$lat = isset($_POST['lat']) ? $_POST['lat'] : null;
$lng = isset($_POST['lng']) ? $_POST['lng'] : null;
if($lat && $lng){
$locations = array();
$stmt = "SELECT * FROM location LIMIT 500"; //Query data from table
$stmt = $conn->prepare($stmt);
$stmt->execute();
if($stmt->rowCount() > 0){
$result = $stmt->fetchAll();
foreach($result as $row){
echo'<tr>
<td>';
$locations['Latitude'][] = $row;
echo'</td>
<td>';
$locations['Longitude'][] = $row;
echo'</td>
</tr>';
}
}
return json_encode($locations);
}
?>
What I am looking to do is update the table with data from the database based on the user's current location, when the user lands on the index.php page, Or the user can also search for a location using the search bar provided on the index.php page.
Thank you in advance for your time.
You need to first send JSON correctly from PHP file, and then receive at the AJAX response and parse to use it further to show in data tables. See below codes for the help.
Client side code:
$.getJSON(GEOCODING).done(function(location) {
$('#latitude').html(position.coords.latitude);
$('#longitude').html(position.coords.longitude);
$.ajax({
url:'table.php',
method: 'POST',
dataType: 'json',
data:{
lat: $('#latitude').val(),
lng: $('#longitude').val()
},
success: function(data){
// Here you need to parse the JSON data and put it in the data table rows by looping over it, see example code #E1
console.log();
}
});
});
PHP Code:
<?php require_once("connect.php"); $lat = isset($_POST['lat']) ? $_POST['lat'] : null; $lng = isset($_POST['lng']) ? $_POST['lng'] : null; if($lat && $lng){ $locations = array(); $stmt = "SELECT * FROM location LIMIT 500"; //Query data from table $stmt = $conn->prepare($stmt);$stmt->execute(); if($stmt->rowCount() > 0){ $result = $stmt->fetchAll(); foreach($result as $row){
$result[] = ['col1'=>$row['col1'],'col2'=>$row['col2']]; // here you need to add as many columns as you want to show in the data table } } print json_encode($result);die; } ?>
Example codes:-
_#E1_
console.log(JSON.stringify(json.topics)); $.each(json.topics, function(idx, topic){ $("#nav").html('' + topic.link_text + ""); });
Apply code as per your need and it will resolve your problem. Assuming you are getting proper data from the database query.
Hope it helps.
Thanks
I have the following scripts that displays database records via json. it works very fine.
My question is how do i create a secure API with it so that when users place the api say
http://www.waco.com/profile.php?id=0990999&security=xxxxxxxxx in their website,
it will pull the information from my server and display it on their site. below is the entire working code
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script>
$(document).ready(function(){
var formhtml = "logreq=1";
var postURL= 'profile.php';
$.ajax({
type: "POST",
url: postURL,
data: formhtml,
dataType: JSON,
success: function(html){
var output= '<table class="logtable"><tbody><thead><th>Log</th><th>Username</th><th>Date</th><th>Event</th></thead>';
var logsData = $.parseJSON(html);
for (var i in logsData.logs){
output+="<tr><td>" + logsData.logs[i].title + "</td><td>" + logsData.logs[i].user + "</td><td>" + logsData.logs[i].date+ "</td><td>" + logsData.logs[i].log+"</td></tr>";
}
//write to container div
$("#log_container").html(output);
},
error: function (html) {
alert('Oops...Something went terribly wrong');
}
});
});
</script>
</head>
<body>
<div id="log_container">
</div>
</body>
</html>
<?php
$db = mysqli_connect("localhost","root","","profile_database");
//MSG
$query = "SELECT * FROM logs LIMIT 20";
$result = mysqli_query($db, $query);
//Add all records to an array
$rows = array();
while($row = $result->fetch_array()){
$rows[] = $row;
}
//Return result to jTable
$qryResult = array();
$qryResult['logs'] = $rows;
echo json_encode($qryResult);
mysqli_close($db);
?>
please i need help.
I am assuming that your example is an oversimplification, and that you will be looking into preventing SQL injections as well as any additional validation to ensure that you are getting the data you are expecting.
With that said, I would place your PHP code in a separate file for the user to call and drop your code into it like so:
if(isset($GET['id']) && isset($GET['security'])){
$id = $GET['id']; $secure = $GET['security']; // TODO: escape these strings
$db = mysqli_connect("localhost","root","","profile_database");
//MSG
$query = "SELECT * FROM logs LIMIT 20 Where id = $id And security = $secure";
$result = mysqli_query($db, $query);
//Add all records to an array
$rows = array();
while($row = $result->fetch_array()){
$rows[] = $row;
}
//Return result to jTable
$qryResult = array();
$qryResult['logs'] = $rows;
echo json_encode($qryResult);
mysqli_close($db);
}
Hope that helps. This is good place to start. I would also look into PHP frameworks like CodeIgniter or Cake that will help you build your API properly.
at first I apologise for creating this topic. I did try to search the answer but I couldnt find the right solution.
I am reading data from mysql with ajax and everything is working with one div. The thing I can't get working is to load each variable into separate div.
I use this api.php for fetching the data from mysql.
<?php
$host = "localhost";
$user = "root";
$pass = "";
$databaseName = "skuska";
$tableName = "hodnoty";
//--------------------------------------------------------------------------
// 1) Connect to mysql database
//--------------------------------------------------------------------------
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
//--------------------------------------------------------------------------
// 2) Query database for data
//--------------------------------------------------------------------------
$result = mysql_query('SELECT t.hodnota FROM hodnoty t ORDER BY t.id DESC LIMIT 1') or die('Invalid query: ' . mysql_error()); //query
while ($row = mysql_fetch_assoc($result)) {
echo $row['hodnota'];
}
?>
This is the ajax script for updating the data.
$(document).ready(function() {
$("#gettable").load("api.php");
var refreshId = setInterval(function() {
$("#gettable").load('api.php?randval='+ Math.random());
}, 9000);
$.ajaxSetup({ cache: false });
});
Then in html I am using div for showing the data
<div id="gettable"></div>
I would like to use this but with more variables like data1, data2, data3
and then used div for each data so I could use more divs.
For example:
<div id="data1"></div>
<div id="data2"></div>
I understand html, a little bit of php but I am totally new in java.
Thank you for your help.
do this
take as many variables as you have div and store content in variables inside loops
/******* a short example **************/
$div1cnt="";
$div2cnt="";
while($SRC=mysqlii_fetch_object($link)){
$divid=$SRC->id;
if($divid==1){
$div1cnt.="add more stuff that you want here";
}
else if($divid==2){
$div2cnt.="add stuff to second div";
}
echo "<div id=\"div1\">{$div1cnt}</div>";
/************and so on ******************/
There is no JS requirement means it is mobile friendly and no double connection required to load second page.
Here is how you can solve the problem in Javascript ( watch out, not JAVA :) )
$(document).ready(function() {
var i = 1;
$.get("api.php", function(result) {
$("#gettable").append("<div id='data"+i+"'>"+result+"</div>");
i++;
});
var refreshId = setInterval(function() {
$.get("api.php?randval="+ Math.random(), function(result) {
$("#gettable").append("<div id='data"+i+"'>"+result+"</div>");
i++;
});
}, 9000);
$.ajaxSetup({ cache: false });
});