Dynamically json value storing - javascript

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

Related

How to get an value from a php page with js

I am trying to capture a value that is calculated on a PHP page called "classes_day.php" at the same time as I pass a value per GET, "? Day = YYYY-mm-dd" to it. How do I do this with JS or JQuery?
<?php
// aulas_dia.php
include '../config.php';
$exped_duration = 14*60;
if (isset($_GET['data'])) {
$data = $_GET['data'];
$query = "SELECT * FROM `task` WHERE `dia` LIKE ".$data."";
$result = mysqli_query($link,$query);
$soma = 0;
while ($row = mysqli_fetch_assoc($result)) {
$soma = $soma+$row['duration'];
}
$aulas_free = floor(($exped_duration-$soma)/50);
echo $aulas_free;
}
?>
I already tried using an iframe and contentwindow, but iframe gets the value and the contentwindow is empty (weird isn't it?).
Following Barmar's tip, I'm using $ .get, but I don't know why this loop is not working, can anyone help me?
for (i = 0; i < num_days; i++) {
x = (first_day+i)%7;
y = (first_day+i-x)/7;
h_dia(String(y)+String(x),i+1);
data_c = ano+"-"+mes+"-"+String(i+1);
$.get("aulas_dia.php?data="+data_c, function(data){
console.log(String(y)+String(x)+" - "+data_c+" - "+data);
set_aulas_fun(String(y)+String(x),data);
});
}
Use $.get() to send an AJAX request.
$.get("classes_day.php?data=YYYY-MM-DD", function(response) {
console.log(response);
});
BTW, you can add up all the durations in the SQL query instead of using a PHP loop. And you should use a prepared statement to prevent SQL injection.
<?php
include '../config.php';
$exped_duration = 14*60;
if (isset($_GET['data'])) {
$data = $_GET['data'];
$query = "SELECT SUM(duration) AS total FROM `task` WHERE `dia` LIKE ?";
$stmt = $link->prepare($query);
$stmt->bind_param("s", $data);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$soma = $row['total'];
$aulas_free = floor(($exped_duration-$soma)/50);
echo $aulas_free;
}

How to use javascript if statements within function to populate table

I've created a search page that sends results to a table with the ability to click on a specific record which then opens another page in the desired format.
I'd like to do is be able to open different formatted pages based on the data returned in the search query but I'm having a bit of trouble pulling it all together.
Here's the PHP used to request and retrieve the data from the database, as well as populate it in a table where each record can be selected and used to populate a planner page with all the proper formatting:
$search = $_POST['search'].'%';
$ment = $_POST['ment'];
$stmt = $link->prepare("SELECT lname, fname, rank, reserve, ment1, pkey FROM planner WHERE lname LIKE ? AND ment1 LIKE ? ORDER BY lname, fname");
$stmt->bind_param('ss', $search, $ment);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
echo "<table><tr><th>Last Name</th><th>First Name</th><th>Rank</th><th>Mentor Group</th><th></th></tr>";
while($row = $result->fetch_assoc()) {
$rsv = $row['reserve'];
$pkey = $row['pkey'];
echo "<tr><td>".$row['lname']."</td><td>".$row['fname']."</td><td>".$row['rank']."</td><td>".$row['ment1']."</td><td><button onClick=getPlanner('".$pkey."');>Get Planner</button></td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
Now the fun part. I want to open different pages based on the information contained in the record. I've got it working for the pkey variable by itself with a single javascript function. However, if I want to open a differently formatted page using the same function using if, else statements, the table only populates with the link page based on the last record compared. Here is my attempt to get the JavaScript with the if, else statements working but it only uses the format of the last record that's compared.
var pkey = <?php echo json_encode($pkey); ?>;
var rsv = <?php echo $rsv ?>;
//var check = document.write(rsv);
function getPlanner(pkey) {
if(rsv != 0){
var plan = window.open("../php/plannerR.php?pln=" + pkey);
} else {
var plan = window.open("../php/planner.php?pln=" + pkey);
}
}
How do I get the 'Get Planner' button to open the correctly formatted planner page based on the users specific information?
To make things easier I'd suggest the following:
Do the logic already in php when generating the html-table (and the link).
while($row = $result->fetch_assoc()) {
$rsv = $row['reserve'];
$pkey = $row['pkey'];
if($rsv) { // thats basicly the same as !=0
$target='../php/plannerR.php'
} else {
$target='../php/planner.php'
}
echo "<tr><td>".$row['lname']."</td><td>".$row['fname']."</td>";
echo "<td>".$row['rank']."</td><td>".$row['ment1']."</td>";
echo "<td><a class='button styleIt' href='".$target."?pkey=".$pkey."&rsv=".$rsv."'>Get Planner</a></td></tr>";
}
If you wanna stick to your js solution (which is more hassle unless you really need it) you can of course go with the solution from my comments that you already successfully implemented (and posted as answer so others can see the implementetion).
Thanks to Jeff I played around a bit with bringing both variables into the function and got it to work. Final code below.
$search = $_POST['search'].'%';
$ment = $_POST['ment'];
$stmt = $link->prepare("SELECT lname, fname, rank, reserve, ment1, pkey FROM planner WHERE lname LIKE ? AND ment1 LIKE ? ORDER BY lname, fname");
$stmt->bind_param('ss', $search, $ment);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
echo "<table><tr><th>Last Name</th><th>First Name</th><th>Rank</th><th>Mentor Group</th><th></th></tr>";
while($row = $result->fetch_assoc()) {
$rsv = $row['reserve'];
$pkey = $row['pkey'];
echo "<tr><td>".$row['lname']."</td><td>".$row['fname']."</td><td>".$row['rank']."</td><td>".$row['ment1']."</td><td><button onClick=getPlanner('".$pkey."','".$rsv."');>Get Planner</button></td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
var pkey = <?php echo json_encode($pkey); ?>;
var rsv = <?php echo $rsv ?>;
//var check = document.write(rsv);
function getPlanner(pkey, rsv) {
if(rsv != 0){
var plan = window.open("../php/plannerR.php?pln=" + pkey);
}
else{
var plan = window.open("../php/planner.php?pln=" + pkey);
}
}

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

retrieving json data from mysql and php into jquery

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!

Categories

Resources