Below are a couple of queries that ultimately build an array.
if(isset($_POST['getarray'])){
try{
$ret = array();
$stmt = $db->prepare('SELECT groupdate, groupid
FROM participationtemp
WHERE memberid = :memberid
AND groupid = :groupid
ORDER BY groupdate, groupid DESC');
$stmt->bindValue(':groupid', $_POST['groupid'], PDO::PARAM_INT);
$stmt->bindValue(':memberid', $_SESSION['memberid'], PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetchAll();
foreach($result as $row){
$attenddate = $row[0];
$stmt = $db->prepare('SELECT h.clientid, attend, attend_date
FROM history AS h
INNER JOIN suspended AS s on s.clientid = h.clientid
WHERE h.memberid = :memberid
AND h.groupid = :groupid
AND attend_date = :attenddate
AND suspend = "N"');
$stmt->bindValue(':memberid', $_SESSION["memberid"], PDO::PARAM_INT);
$stmt->bindValue(':groupid', $_POST['groupid'], PDO::PARAM_INT);
$stmt->bindValue(':attenddate', $attenddate, PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetchAll();
foreach($result as $row ) {
array_push($ret, ['id' => $row[0], 'gdate' => $row[2]]);
}
}
echo json_encode($ret);
exit();
} catch (PDOException $ex){
mail_error($ex);
}
}
After returning to JQuery, alert(re); shows I successfully created the array.
success:function(re){
alert(re);
But I'm having trouble accessing the array data. Without success, this is what i've tried:
data = $.parseJSON(re);
$.each(data, function(i, val) {
alert(i + "=" + val);
});
and this:
data = $.parseJSON(re);
$.each(data, function(i, val) {
if(i == "id"){
alert(i + "=" + val);
}
if(i == "gdate"){
alert(i + "=" + val);
}
});
I've also tried dot notation.
$.each(re.id, function(i, val) {
alert(i + "=" + val);
}
});
$.each(re.gdate, function(i, val) {
alert(i + "=" + val);
});
I've never used JSON before and don't understand why I can't retrieve the array data. Any help will be appreciated. Thanks.
The following code checks whether re is a string, or an object. The latter is possible if jQuery.ajax() method is used with "json" dataType. Also, jQuery is capable of parsing JSON automatically, if the response MIME type is application/json (the Content-Type HTTP header), particularly. So it is a good idea to check if re has been parsed by jQuery.
var d = typeof re === 'string' ? JSON.parse(re) : re;
var i;
for (i = 0; i < d.length; i++) {
console.log("id = ", d[i].id,
"gdate = ", d[i].gdate);
}
I'd recommend returning the appropriate content type from PHP:
header ('Content-Type: application/json');
echo json_encode($ret);
exit();
$.each(re, function(i, val) {
alert(val.id + "=" + val.gdate);
});
Try this code :)
// Json in string format
var jsonString = '[{"id":"1", "gdate":"2016-10-13"},{"id":"2", "gdate":"2016-10-13"},{"id":"3", "gdate":"2016-10-13"},{"id":"4", "gdate":"2016-10-13"},{"id":"5", "gdate":"2016-10-13"},{"id":"6", "gdate":"2016-10-13"}]';
// Convert string to json object
var json = JSON.parse(jsonString);
// Iterate over json object
jQuery.each(json, function(index, value) {
console.log(index, value);
});
// Simple access to attribute in json object
console.log('json[1][\'id\'] = ', json[1]['id']);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Related
Javascript Object to a PHP Object
I was searching for the tutorial how to pass associative array from JavaScript to PHP object and found this video. I think it is a little bit old it was added in 2010. I tried it and had error. I ask you to help me to correct it or help me to to get php object from js object.
index.php
<script>
let ar = new Array();
ar["name"] = "name1";
ar["name1"] = "name2";
console.log(ar);
function convertOb(object){
var json = "{";
for (property in object) {
var value = object[property];
if (typeof(value) == "string") {
json += '"' + property + '":"' + value +'",';
} else{
if (!value[0]) {
json += '"' + property + '":"' + convertOb(value) + ',';
} else{
json+= '"'+ property +'":[';
for (prop in value) json+= '"' + value[prop] + '",';
json = json.substr(0,json.length-1) + "],";
}
}
} return json.substr(0,json.length-1) + "}";
}
let json = convertOb(ar);
$.post("main.php", {json:json}, function(data){
console.log(data);
});
</script>
main.php
<?php
function jsonstring2obj($str){
return json_decode(stripslashes($str));
}
$ar = jsonstring2obj($_POST['json']); //error1
echo $ar->name; //error2
?>
My errors:
Undefined index: json //error1
Trying to get property 'name' of non-object //error2
How can i check which JSON value exist in JSON Array? Here are my solution:
var jsonArr = "[{"F_1":"c4024087","F_2":"9a565962","F_3":"23026","F_4":"John","F_5":"Doe"},{"F_1":"dbb88908","F_2":"bc6fd3bb","F_3":"19727","F_4":"Mike","F_5":"Long"}]"
Find the value:
var toFind = "9a565962";
var checkObj = jsonArr.find(o => o.F_2 == toFind );
if (typeof checkObj === "undefined") {
console.log("Value " + toFind + " not exists in Array. Do something!");
} else (Object.keys(checkObj).length > 0) {
console.log("Value " + toFind + " exists in Array. Do something else");
}
Is this the best way to find a value in a array?
$jsondata = file_get_contents("/json/API.php");
$array = json_decode($jsondata,true);
foreach($array as $k=>$val):
if($id =! $val){
echo '<b>id: '.$k.'</b></br>';
$keys = array_keys($val);
foreach($keys as $key):
echo ' '.ucfirst($key).' = '.$val[$key].'</br>';
endforeach;
endforeach;
}
Probably it will solve your problem Best Regards
I am new in php . I have the following code to retrieve categorytype data from database?. I want to add them into php object for temporary using while loading page. First, I want to load all predefined data, then i will use it when i click function. Could you enlighten me how to create it
categoryDao.php
namespace category;
use Exception;
use PDO;
class categoryDao{
public function categorytype(PDO $connection){
$conn = $connection;
try {
$conn = $connection;
$sql="SELECT * FROM `tb_category` WHERE id != parent_id;";
$categorytype = $conn->prepare($sql);
$categorytype->execute();
$data1 = array();
while (
$result = $categorytype->fetch(PDO::FETCH_ASSOC)) {
$data1[] = $result['id'];
$data1[] = $result['c_name'];
}
return $data1;
} catch (Exception $e) {
echo $e;
throw $e;
}
}
}
categoryservice.php
use category\categoryDao;
require '../dao/categoryDao.php';
require 'Dao.php';
class categoryService{
public function categorytype(){
$dao = new Dao();
$conn= $dao->connect();
$conn->beginTransaction();
$categoryDao = new categoryDao();
//$data1 = array();
$data1=$categoryDao->categorytype($conn);
return $data1;
$dao->disconnect($conn);
}
}
categorytypecontroller.php
<?php
require '../service/categoryService.php';
require '../service/categoryService.php';
$categoryname = #trim(stripslashes($_POST['category']));
$category = new categoryService();
//$ctype = array();
$ctype = $category->categorytype();
$return["json"] = json_encode($ctype);
echo $return["json"];
Head.php
function categorytype() {
//var hosname =window.location.protocol + "//" + window.location.hostname + window.location.pathname;
var hosname1 = window.location.protocol + "//" + window.location.hostname+ "/servicegateway/sgw/modules/controller/categorytypecontroller.php";
alert (hosname1);
//var ur = hosname + "/modules/controller/categorycontroller.php";
$.ajax({
url:hosname1 , //the page containing php script
type: "POST", //request type,
dataType: 'json',
data: '',
success:function(data1){
alert(data1);
var obj =data1;
// var leng = Object.keys(obj).length;
var areaOption = "<option value=''>Select Category </option>";
for (var i = 0; i < obj.length; i++) {
areaOption += '<option value="' + obj[i] + '">' + obj[i] + '</option>'
}
$("#c_type").html(areaOption);
}
});
}
A couple of things. If you want the data to be an array of records, you'll probably want to change this part:
while ($result = $categorytype->fetch(PDO::FETCH_ASSOC)) {
$data1[] = $result['id'];
$data1[] = $result['c_name'];
}
as that is putting all the fields, one after the other, into a normal array.
while ($result = $categorytype->fetch(PDO::FETCH_ASSOC)) {
$data1[] = array(
'id' => $result['id'],
'c_name' => $result['c_name']
);
}
That will create a small associative array of the id and name fields and put it into another array, with the other records. PHP associative arrays will turn into Javascript objects when sent via ajax.
Then, in Javascript, you'll want to make use of those objects to create your options, so:
areaOption += '<option value="' + obj[i].id + '">' + obj[i].c_name + '</option>'
This code tries to populate a dropdown list in a form with values. I have tested the PHP separately and the query is ok (small wonder !). I have a similar form whith 3 connected dropdown lists and they work flawlessly. Debugging this in Mozilla, I notice that the success function of JSON is not executed. I cannot understand why.
JavaScript
$(document).ready(function()
{
$.getJSON("/scripts/033A_GetJudet.php", success = function(data)
{
var str_options = "";
for (var i=0; i < data.length; i++)
{
str_options += "<option value='" + data[i] + "'>" + data[i] + "</option>";
}
$("#selJudet").append(str_options);
// var selOption = document.getElementById("selJudet");
// selOption.selectedIndex = localStorage.getItem("selJudIndex") || 0;
// document.getElementById("selJudet").selectedIndex = selOption.selectedIndex;
$("#selJudet").change();
});
$("#selJudet").change(function()
{
var selText = document.getElementById("selText");
// selText.value = selText.defaultValue;
selText.value = "Abcgcfkjsdhfsjkdh";
// $("#selText").change();
});
});
PHP (I skipped the database connection code)
$query = '(SELECT 1 AS sc, nume_judet FROM sa_Judet ';
$query .= 'WHERE nume_judet <> "N/A" ) UNION ';
$query .= '(SELECT 2 AS sc, "N/A" FROM sa_Judet) ';
$query .= 'ORDER BY sc, nume_judet';
//print $query;
$result = mysqli_query($db_conn, $query);
$judet = array();
if ($result == FALSE)
{
array_push($judet, 'QUERY_ERROR');
goto _adr1;
}
$rows = mysqli_num_rows($result);
if ($rows == 0)
{
array_push($judet, 'TBD_');
goto _adr1;
}
while ($row = mysqli_fetch_array($result))
{
array_push($judet, $row['nume_judet']);
}
_adr1:
print json_encode($judet);
mysqli_free_result($result);
mysqli_close($db_conn);
?>
Ajax variant of my original Javascript
$(document).ready(function()
{
$.ajax({
url: "/scripts/033A_GetJudet.php",
dataType: 'json',
success: function(data)
{console.log('SUCCESS: ', data);},
error: function(data)
{console.log('ERROR: ', data);}
var str_options = "";
for (var i=0; i < data.length; i++)
{
str_options += "<option value='" + data[i] + "'>" + data[i] + "</option>";
}
$("#selJudet").append(str_options);
var selOption = document.getElementById("selJudet");
selOption.selectedIndex = localStorage.getItem("selJudIndex") || 0;
document.getElementById("selJudet").selectedIndex = selOption.selectedIndex;
$("#selJudet").change();
});
$("#selJudet").change(function()
{
var selText = document.getElementById("selText");
selText.value = selText.defaultValue;
// $("#selText").change();
});
});
It is possibly an error in parsing the data received. HTTP 304 is the same as HTTP 200, only the contents is pulled from cache, not serverside.
$.ajax({
url: url,
data: data,
success: function(response, textStatus, jsqxhr) {
var obj; try { obj = eval(response); } catch(e) { console.error(e); }
// -- do something with obj --
},
fail: function(jqxhr, textStatus, error) {
console.log( "error", textStatus, error);
}
});
Use this function instead and look closer at the data. If data is returned through success, we try to evaluate the json string into an object. Should it fail, an exception is thrown (possibly SyntaxError) and log should show this.
Replace this line
$.getJSON("/scripts/033A_GetJudet.php", success = function(data)
with this one
$.getJSON("/scripts/033A_GetJudet.php", function(data)
To start i'm using jquery,php,sql,html & css.
I am facing a issue that is giving me serious problem. I am trying to run a $.post function to retrieve values from my database of a party group(4 members value stored in 4 columns in the database. After retrieving the value, i run a while loop and append each value of the party onto a listview.
Then i send the current while loop value over to another $.post function to check for the rating score for the member i'm currently checking, and retrieve the result to display onto the li that i am currently appending.
This is what i have
$('body').on("pagebeforeshow","#p-partyDetail",function(){
var teamID = globalIndex;
var currentMem = "";
$.post("retrieveMemDetails.php",
{
teamID:teamID, // data to pass into php
username:globalUsername,
}, // data to pass into php
function(response)
{
var x = 1; // define value as 1
while(x<=4){ // if loop is below or equal to 4, run loop
//member = response.mem + x;
member = response['mem' + x]; // define member1 in variable,
currentMem = member;
console.log("current x value is " + x);
if(member !=""){
var y = x.toString();
console.log("y is " + y);
$.post("retrieveRatingDetails.php",
{
username:currentMem, // data to pass into php
}, // data to pass into php
function(response2)
{
$("p#" +y).html(response2.rating);
console.log("full name is " + response2.name + " rating is " + response2.rating);
console.log("retrieve rating valued:"+response2.rating+" to p#"+y);
console.log("end of loop cycle" + y);
}, 'json'
);
$("#partyDetail-listview").append('<li> <img src="images/final-fantasy-7-final-fantasy-vii-6973833-1024-768.jpg"> <h2>'+ member + '</h2> <p id="'+ x +'"></p> </li>').listview("refresh");
console.log("appended count:" + x);
}
x++;
}
}, 'json'
);
});
my php for retrieving member detail
include_once('db.php');
session_start();
$teamID = ($_POST['teamID']);
$username = ($_POST['username']);
$result = $db->query("SELECT * FROM `studentparty` WHERE `id` = '".$teamID."'");
$result3 = $db->query("SELECT *` FROM `userdetails` WHERE `username` = '".$username."'");
if(mysqli_num_rows($result)>0)
{
$row = mysqli_fetch_array($result);
$mem1 = $row["mem1"];
$mem2 = $row["mem2"];
$mem3 = $row["mem3"];
$mem4 = $row["mem4"];
$result2 = json_encode(array("mem1"=>$mem1, "mem2"=>$mem2, "mem3"=>$mem3, "mem4"=>$mem4));
echo $result2;
}
my php for retrieving rating scores
include_once('db.php');
session_start();
$username = ($_POST['username']);
$result4 = $db->query("SELECT * FROM `userdetails` WHERE `username` = '".$username."'");
if(mysqli_num_rows($result4)>0)
{
$row = mysqli_fetch_array($result4);
$rating = $row["Rating"];
$name = $row["FullName"];
$result5 = json_encode(array("rating"=>$rating, "name"=>$name));
echo $result5;
}
my member & rating are under different table so i called $.post twice.
Apparently after debugging for hours, i found out that it will loop through
console.log("current x value is " + x);
then
console.log("y is " + y);
then
console.log("appended count:" + x);
running through a total loop count of 4 before it run
console.log("full name is " + response2.name + " rating is " + response2.rating);
console.log("retrieve rating valued:"+response2.rating+" to p#"+y);
console.log("end of loop cycle" + y);
this caused the rating to only keep updating on the value y, as the flow of the function are already wrong.
My ideal flow is
-retrieve party member details from php
-while displaying mem1 from php using while loop, append a li only my ul.
-send the current mem1 data into my next $.post function to retrieve rating data
-update the li with the rating data
-end of loop and begin with member2
Can someone point out to me what wrong with my script? Thanks!
I strongly recommend that one ajax request is enough to get requested data. If you make inner ajax request, you have to wait other lines to be executed. Because it is asynchronous functions. You can also set your ajax call synchronously with the code as in below:
$.ajax({
...
async: false,
...
});
But then you have to wait until your callback function is executed. So, sometimes it is dangerous for your performance.
If you change your php side as in below, you will get an array with objects which have member and member's detail.
include_once('db.php');
session_start();
$teamID = ($_POST['teamID']);
$result_detail = $db->query("SELECT * FROM `studentparty` WHERE `id` = '".$teamID."'");
if(mysqli_num_rows($result_detail) > 0)
{
$data = array();
$mem = array();
$row = mysqli_fetch_array($result);
$mem[0] = $row["mem1"];
$mem[1] = $row["mem2"];
$mem[2] = $row["mem3"];
$mem[3] = $row["mem4"];
for($i = 0; $i < count($mem); $i++) {
$result_rating = $db->query("SELECT *` FROM `userdetails` WHERE `username` = '".$mem[$i]."'");
$rating_array = array();
if(mysqli_num_rows($result_rating) > 0)
{
$row2 = mysqli_fetch_array($result_rating);
$rating = $row2["Rating"];
$name = $row2["FullName"];
$rating_array = array("rating"=>$rating, "name"=>$name));
}
$data[$i] = array_merge(array("member" => $mem[$i]), $rating_array);
}
$result_json = json_encode($data);
echo $result_json;
}
I also adopted your javascript code to new response. I couldn't test both. I hope it will work well.
$('body').on("pagebeforeshow","#p-partyDetail",function(){
var
teamID = globalIndex,
currentMem = "",
callback = function(response) {
var member, id;
$.each(response, funciton(i, obj) {
member = obj['member'];
id = (i+1); // if you have ids for members, you can send in php additionally. it would be better than (i+1)
$("#partyDetail-listview").append('<li> <img src="images/final-fantasy-7-final-fantasy-vii-6973833-1024-768.jpg"> <h2>'+ member + '</h2> <p id="'+ id +'"></p> </li>').listview("refresh");
console.log("appended count:" + id);
if (member) {
$("p#" + id).html(obj['rating']);
console.log("full name is " + obj['name'] + " rating is " + obj['rating']);
console.log("retrieve rating valued:"+obj['rating']+" to p#" + id);
console.log("end of loop cycle" + id);
}
});
};
$.post("retrieveMemDetails.php",
{
teamID:teamID, // data to pass into php
username:globalUsername,
}, // data to pass into php
callback, 'json');
});