retrieving json data from mysql and php into jquery - javascript

I am trying to bring mysql data into jquery by using php, I get the data into a JSON format like this.
{"uid":"33","title":"Apple, Peach, Grapefruit","ing1":"apple","qty1":"1","meas1":"whole","ing2":"peaches \/ halved and","qty2":"2","meas2":"each","ing3":"grapefruit \/ peeled","qty3":"2","meas3":"each","ing4":"","qty4":"0","meas4":"each","ing5":"","qty5":"0","meas5":"each","ing6":"","qty6":"0","meas6":"each","ing7":"","qty7":"0","meas7":"each","ing8":"","qty8":"0","meas8":"each","ing9":"","qty9":"0","meas9":"each","ing10":"","qty10":"0","meas10":"each","servings":"2","benefits":""}
using this following code:
require_once'connect.php';
$uid = $_GET['uid'];
$sql = "SELECT * FROM recipes WHERE uid = '$uid'";
$result = mysqli_query($conn, $sql);
$num_rows = mysqli_affected_rows($conn);
while($row = mysqli_fetch_assoc($result)) {
$data = json_encode($row);
echo $data;
}
I am using jquery .get to pull it into the web page with this code.
$(document).ready(function(e) {
var id = location.search;
uid=id.substring(4);
$.get('../jqm_juicing/data/get_json.php?uid=' + uid,function(data, status){
$("#display").append(data);
});
});
It displays the json data as above. I would like to be able to access the different elements individually, how do I do that?

If you wrap it with <script> tags, and declare it as a variable, you will have it.
require_once'connect.php';
$uid = $_GET['uid'];
$sql = "SELECT * FROM recipes WHERE uid = '$uid'";
$result = mysqli_query($conn, $sql);
$num_rows = mysqli_affected_rows($conn);
echo "<script>";
while($row = mysqli_fetch_assoc($result)) {
$data = json_encode($row);
echo "var myJson=" . $data;
}
echo "</script>";
Now in your main page scripts, you can access this JSON like any other normal JSON.
Here is an interval that you can place anywhere in your main page scripts:
It is just to test this ;)
var checkJson = setInterval(function(){
if(typeof(myJson.uid)!="undefined"){
clearInterval(checkJson);
console.log("myJson uid: " + myJson.uid);
console.log("myJson title: " + myJson.title);
// etc...
}else{
console.log("JSON not loaded yet.");
}
},500);

Retrieve the json data to use json response jquery parse function. json data using this function
jQuery.parseJSON()
http://api.jquery.com/jquery.parsejson/

In your jQuery, add JSON.parse() before you append (data).
$(document).ready(function(e) {
var id = location.search;
uid=id.substring(4);
$.get('../jqm_juicing/data/get_json.php?uid=' + uid,function(data, status){
$("#display").append(JSON.parse(data));
});
});
I just changed this line:
$("#display").append(JSON.parse(data));
Hope this helps!

Related

Dynamically Create JavaScript Object From MySQL Table

Lets say I have this table mytable
id | name | x | y
I pull the the rows from mytable and create JavaScript objects with it like so:
PHP
$sql = "SELECT * FROM mytable";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo '<script type="text/javascript">';
echo "new Object({$row["id"]}, '{$row["name"]}', {$row["desk_x"]}, {$row["desk_y"]});";
echo '</script>';
}
}
JS
function Object(id, name, x, y) {
var obj = {
id:id,
name:name,
x:x,
y:y
};
}
At the moment this is fine but lets say I want to add another column color to mytable
Basically I'm asking what do I write in PHP and JS to make this object dynamically, so you can have any columns and the Object object will just add a new property with the name of the column?
You can use AJAX to send data from serverside to clientside. Lets say you have a PHP file called script.php with your code:
if(isset($_GET['action']) && $_GET['action'] == 'testing'){
$sql = "SELECT * FROM mytable";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo json_encode($result);
}
}
And lets say you have a JS file called script.js. Here you will do your AJAX call towards the PHP script file like this:
$.ajax({
type: 'GET',
url: 'script.php',
data: { action: 'testing' },
success: function(response){
console.log(response); //here you will have access to the object returned from the PHP script
}
})
I guess what you're looking for is how to do this without AJAX (which you don't really need here).
Put the objects in an array, then output your JS variable:
PHP:
$rows = [];
if ($result->num_rows)
while($row = $result->fetch_assoc()) $rows[] = $row; // append to array
echo "<script> var objArray = " . json_encode($rows) . "; </script>";

Javascript inside PHP MYSQL query

I know that using php inside js is a bad practice, but unfortunately for now my skill is not enough to come up with something else.
$(document).ready(function() {
$("#type").change(function() {
var val = $(this).val();
valSize = "<?php $sql = "SELECT model FROM cars WHERE brand = 'val'";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)){
echo '<option>'.$row['model'].'</option>';
}
?>";
$("#size").html(valSize);
});
});
Is there any way how I could add val variable inside php code?
Your best bet would be to use a JavaScript AJAX call to send a request to another php file on your server.
First, create a separate PHP file on your server, I'll label it query.php (ONLY for the purposes of this explanation, I'd recommend choosing something more meaningful to your application).
<?php
if ($_POST['brand']) {
// Be sure to set up your SQL $conn variable here
$conn = ...;
$sql = "SELECT model FROM cars WHERE brand = '" . $_POST['brand'] . "'";
$result = mysqli_query($conn, $sql);
$data = []; // Save the data into an arbitrary array.
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
echo json_encode($data); // This will encode the data into a variable that JavaScript can decode.
}
Then in your JavaScript, perform the AJAX request:
$(document).ready(function() {
$("#type").change(function() {
var val = $(this).val();
$.post('query.php', {'brand' : val}, function(data){
var jsonData = JSON.parse(data); // turn the data string into JSON
var newHtml = ""; // Initialize the var outside of the .each function
$.each(jsonData, function(item) {
newHtml += "<option>" + item['model'] + "</option>";
})
$("#size").html(newHtml);
});
});
});
You can't execute the php code once the page has loaded. You're going to have to make a ajax call to a php file, that queries the data you need and echos that back to the original file. I would also recommend encoding it using echo json_encode($queryResults); Then you can JSON.parse($data);the return data in the success function of the ajax call.

JQuery GET request won't get correct data from php echo

I am trying to fill a table using a jquery .get request, the url being a php file. The php gets data from a database, then it should return a json array back to the jquery, array which will fill the table. While the length of the array is returned as it should, the table cells are empty.
Here is my get.php function:
<?php
$mysqli=new mysqli("localhost:3306","root","","leagues");
if (mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$return_arr = array();
$query = "SELECT * FROM league";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_row())
{
$return_arr[] = $row;
}
}
$mysqli->close();
header('Content-Type: application/json');
echo json_encode($return_arr);
?>
And here is my jquery get function
$.get('php/get.php',function(responseJson)
{
if(responseJson!=null)
{
$("#tableleague").find("tr:gt(0)").remove();
var table1 = $("#tableleague");
$.each(responseJson, function(key,value) {
var rowNew = $("<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>");
rowNew.children().eq(0).text(value['teams']);
rowNew.children().eq(1).text(value['playedgames']);
rowNew.children().eq(2).text(value['wongames']);
rowNew.children().eq(3).text(value['tiegames']);
rowNew.children().eq(4).text(value['lostgames']);
rowNew.children().eq(5).text(value['scoredgoal']);
rowNew.children().eq(6).text(value['receivedgoal']);
rowNew.children().eq(7).text(value['points']);
rowNew.appendTo(table1);
});
}
});
Here is how my webpage looks, with the php file response shown.
Since the response is ok, what am I doing wrong that the cells aren't filled? Thank you.
If you look at your JSON data, you can see that there are no keys such as teams or playedgames. This is because you used fetch_row() in the PHP. Change that to fetch_assoc():
while ($row = $result->fetch_assoc())
This will give you $row with the field names as keys instead of using numerical keys that fetch_row() provides.
You can turn the php json into javascript object
obj = JSON.parse(json);
es:
var json='{"ex1":"test","ex2":[{"sub1":"test"},{"sub2":""s2test}],"ex3":true}';
var obj = JSON.parse(json);
after you can acces to data with :
obj.ex1 // test
obj.ex2[0].sub2 //s2test

javascript: verify if entered data exists in db and return data

I have a table:
DB
city
-------
cityID
cityname
store
I have then a form HTML:
<input type="text" class="store">
GOAL:
I would like javascript, after I enter the store, (if the entered value is already in the DB) displays an alert like:
"Store is already entered for the following cities: New York (ID#), Boston(ID#), Springfield(ID#)"
I've tried with a Json file:
<?php include ('connectionlink.php');
$word = $_GET['word'];
$search = "SELECT
store as value,
cityID,
cityname,
FROM city
WHERE store LIKE '%".$word."%'";
$result = mysqli_query($connection, $search);
while ($row = mysqli_fetch_array($result, MYSQL_ASSOC))
{
$row['value']=htmlentities(stripslashes($row['value']));
$row['cityID']=$row['cityID'];
$row['cityname']=$row['cityname'];
$row_set[] = $row;
}
echo json_encode($row_set);
?>
And javascript
$(document).ready(function (){
$('.store').on('change', function(){
var storeValue = $('.store').val();
$.post('stores.php',{'word' : storeValue}, function(data) {
alert("Data: " + data);
});
});
});
I feel I'm almost there, because after typing the store I get an alert of Undefined index word error and then the alert displays all the data in my table with the Json format. It's like if it doesn't search just for my word, but just returns everything. Thanks for your help!
You are doing a post request, so read the parameter with $_POST
$word = $_POST['word']
Also make sure that you handle sql injection How can I prevent SQL injection in PHP?
<?php include ('connectionlink.php');
//as you are doing a post request...
$word = $_POST['word'];
$search = "SELECT
store as value,
cityID,
cityname,
FROM city
WHERE store LIKE '%".$word."%'";
$result = mysqli_query($connection, $search);
while ($row = mysqli_fetch_array($result, MYSQL_ASSOC))
{
$row['value']=htmlentities(stripslashes($row['value']));
$row['cityID']=$row['cityID'];
$row['cityname']=$row['cityname'];
$row_set[] = $row;
}
echo json_encode($row_set);
?>

Dynamically json value storing

Form a php page I am sending some value using json.
$result = mysql_query("SELECT * FROM user_info");
$i=1;
while($row = mysql_fetch_array($result, MYSQL_NUM)) {
if(is_array($row) && count($row)>0)
{
$res['user_name'.$i] = $row[1];
$res['user_email'.$i] = $row[2];
$res['gender'.$i] = $row[4];
$res['i'] = $i;
$i++;
}
}
echo json_encode($res);
I have no problem with this code.But in another page I want to get that data code follows
$.post(urlName, function(data) {
var obj = jQuery.parseJSON ( data );
$noOfUser = obj.i;
alert("No of user- "+$noOfUser);
for($i=0;$i<=$noOfUser;$i++)
{
$user_name = obj.user_name+$i;
$user_emai = obj.user_email+$i;
$gender = obj.gender+$i;
alert("User Name- "+$user_name);
alert("User Email- "+$user_emai);
alert("User Gender- "+$gender);
}
});
But the problem is when I am adding this obj.user_name+$i instead of simple obj.user_name it can't retrieve the data properly but I need to get those value how to do that?
What you are trying to do attempts to get the user_name member of obj and appending the value of $i. Since user_name is not defined, the script fails.
This is because in javascript to access a member of an object using a dynamically generated key you must use the [] accessor, so in your case, the following example should work.
$user_name = obj['user_name' + $i];

Categories

Resources