is it possible to get two different json output - php

is it possible to get two json output on a single page result set
I have to populate data-grid and chart by passing data to another page using ajax and get tow types of json result set from single mysql query, when I try to return json it fails to handle
here is my result.php code where json will be generated,
include('connection.php');
if (isset($_POST)) {
$rep_date1 = $_POST['date1'];
$date1 = date("Y-m-d", strtotime($rep_date1));
$rep_date2 = $_POST['date2'];
$date2 = date("Y-m-d", strtotime($rep_date2));
$sql = mysql_query("SELECT * FROM infra.prob_report WHERE prob_rept_date BETWEEN '$date1' AND '$date2'");
$rows = array();
while ($row = mysql_fetch_assoc($sql)) {
$nestedData = array();
$nestedData[] = $row["rep_id"];
$nestedData[] = $row["prob_rept_date"];
$nestedData[] = $row["prob_equip_name"];
$nestedData[] = $row["prob_rept_name"];
$nestedData[] = $row["prob_desc"];
$data[] = '<tr><td>'.$row["rep_id"].
'</td><td>'.$row["prob_rept_date"].
'</td><td>'.$row["prob_equip_name"].
'</td><td>'.$row["prob_rept_name"].
'</td><td>'.$row["prob_desc"].
'</td></tr>';
$point = array("label" => $row['prob_equip_name'], "y" => $row['rep_id']);
array_push($data_points, $point);
}
echo json_encode($data); //json output populating data-grid
echo json_encode($data_points); //json output populating chart
}
here is my handle.php where my handling script runs,
<script>
$(document).ready(function() {
$('#submit').click(function() {
var name = $("#name").val();
event.preventDefault();
$.ajax({
type: "POST",
url: "new_prob_submit.php",
data: {
'date1': $('#picker1').val(),
'date2': $('#picker2').val()
},
dataType: "json",
success: function(data) {
$('#tbdy').html(data);
$.getJSON("result.php", function(result) {
var chart = new CanvasJS.Chart("chartContainer", {
data: [{
dataPoints: result
}]
});
chart.render();
});
}
});
});
});
</script>

Just do one thing.
In php
echo json_encode(
array(
'data' => $data,
'dataPoints' => $data_points
)
); //json output populating data-grid and populating chart
In javascript
success:function(result){
result.data;
result.dataPoints;
}

Related

cannot display array values in ajax success function

$.ajax({
type: "GET",
url: 'http://localhost/abc/all-data.php',
data: {
data1: "1"},
success: function(response)
{
alert(response);
}
});
return false;
I want to display each element of array one by one in success function of the ajax currently i get all elements to gether
this is my php code
$i=0;
while($row = mysqli_fetch_assoc( $qry )){
$temp[$i]['c_n'] = $row['c_name'];
$temp[$i]['j_t'] = $row['Job_Title'];
$temp[$i]['des'] = $row['description'];
$temp[$i]['req'] = $row['requirments'];
$temp[$i]['dat'] = $row['posted'];
$i++;
}
$data = array('temp'=> $temp);
echo JSON_encode($temp);
I do appreciate your helps
you probably use something like this in your success function :
response.temp.forEach(function(element){
console.log(element.c_n) ;
console.log(element.j_t) ;
console.log(element.des) ;
console.log(element.req) ;
console.log(element.dat) ;
});
In your success function, you need to json parse your response
var data = JSON.parse(response);
You can access to your data:
data['temp']
If you want your response parsed to json automaticallym you can setup your ajax settings like this:
$.ajaxSetup ({
contentType: "application/json",
dataType: 'json'
});
Then you don't need to call JSON.parse anymore.
Your code:
$i=0; while($row = mysqli_fetch_assoc($qry)){
$temp[$i]['c_n'] = $row['c_name'];
$temp[$i]['j_t'] = $row['Job_Title'];
$temp[$i]['des'] = $row['description'];
$temp[$i]['req'] = $row['requirments'];
$temp[$i]['dat'] = $row['posted'];
$i++;
} $data = array('temp'=> $temp); echo JSON_encode($temp);
Please change the last line as
return JSON_encode($data);
Hope this helps you :)

json return value not plotting canvas.js bar chart in php

I'm trying to plot bar chart using canvas.js out of json return value, am getting the values in callback page but unable to plot the chart,
here is my handler.php page where json value is generated,
<?php
include('connection.php');
if(isset($_POST)) {
$rep_date1=$_POST['date1'];
$date1=date("Y-m-d",strtotime($rep_date1));
$rep_date2=$_POST['date2'];
$date2=date("Y-m-d",strtotime($rep_date2));
$sql=mysql_query("SELECT * FROM infra.prob_report WHERE prob_rept_date BETWEEN '$date1' AND '$date2'");
$rows = array();
while($row = mysql_fetch_assoc($sql)) {
$nestedData=array();
$nestedData[] = $row["rep_id"];
$nestedData[] = $row["prob_rept_date"];
$nestedData[] = $row["prob_equip_name"];
$nestedData[] = $row["prob_rept_name"];
$nestedData[] = $row["prob_desc"];
$data[]= '<tr><td>'. $row["rep_id"]. '</td><td>'. $row["prob_rept_date"]. '</td><td>'.$row["prob_equip_name"]. '</td><td>'. $row["prob_rept_name"]. '</td><td>'. $row["prob_desc"].'</td></tr>';
$data_points = array("label" => $row['prob_equip_name'] , "y" => $row['rep_id']);
}
echo json_encode(array('data' => $data, 'dataPoints' => $data_points)); //json output populating data-grid and populating chart
}
?>
here is my index.php where script resides,
<script>
$(document).ready(function() {
$("#picker1").datepick();
$("#picker2").datepick();
$('#picker1').datepick('setDate', 'today');
$('#picker2').datepick('setDate', 'today');
$('#submit').click(function() {
var name=$("#name").val();
event.preventDefault();
$.ajax({
type:"POST",
url: "new_prob_submit.php",
data: {
'date1': $('#picker1').val(),
'date2': $('#picker2').val()
},
dataType: "json",
success:function(result) {
$('#tbdy').html(result.data);
$.getJSON("handler.php", function (result) {
var chart = new CanvasJS.Chart("chartContainer", {
data: [
{
dataPoints: result.dataPoints
}
]
});
chart.render();
});
}
});
});
});
</script>
Thanks in advance!!

set json data array in function response

Here is my ajax function in response I am getting result but I don't know how to set that response in my page. Is it possible with json_decode or I have to try something else
JSON file is
<?php
$group_id = $_POST['group_id'];
$query = "SELECT *,group_id FROM contact JOIN addressgroup ON addressgroup.contact_id = contact.contact_id WHERE group_id IN (".$group_id.") GROUP BY contact.contact_id";
$res = mysql_query($query);
$data = array();
$k=0;
while($row = mysql_fetch_array($res))
{
$data[$k][0] = $row['user_id'];
$data[$k][1] = $row['first_name'];
$data[$k][2] = $row['middle_name'];
$data[$k][3] = $row['last_name'];
$k++;
}
echo json_encode(array($data));
?>
AJAX function
var myarray;
function getcon() {
myarray = [];
myarray.push($(".group_id").val());
$.ajax({
dataType: "json",
type: "POST",
url: "getcon.php",
data: 'group_id=' + myarray.join(),
success: function(data) {
totalRecords=data.length;
zone.fnClearTable();
for(var i=0; i < (data.length); i++) {
zone.fnAddData([
data[k][0],
data[k][1],
data[k][2],
data[k][3],
]);
}
return false;
}
});
return false;
}
As your Response is an JSON object..
you have to use it like this:-
replace
echo json_encode(array($data));
by
echo json_encode($data); /* because $data is already an array*/
and keep it same as it was earlier
while($row = mysql_fetch_array($res))
{
$data[] = $row['user_id'];
$data[] = $row['first_name'];
$data[] = $row['middle_name'];
$data[] = $row['last_name'];
$k++;
}
<script>
var myarray;
function getcon() {
myarray = [];
myarray.push($(".group_id").val());
$.ajax({
dataType: "json",
type: "POST",
url: "getcon.php",
data: 'group_id=' + myarray.join(),
success: function(data) {
console.log(data)/* check the structure of data here*/
zone.fnClearTable();
zone.fnAddData([
data.user_id.,
data.first_name,
data.middle_name,
data.last_name,
]);
return false;
}
});
return false;
}
</script>
JSON is an object! Your are getting object, so in your ajax function You must use some loop function like for or $.each JQuery functions.
`success : function (data) {
$.each (data,function(key,val){
$("#someId).html(key + " - " + val)
}
}`

How to display array of json data properly in html?

My Ajax
$("form").on("submit", function () {
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "ajax2.php", //Relative or absolute path to response.php file
data: data,
success: function (data) {
$("#main_content").slideUp("normal",function(){
$(".the-return").html("<br />JSON: " + data);
//how to alter this part to display data for each record in one div?
});
}
});
return false;
});
My query
$statement = $pdo->prepare("SELECT * FROM posts WHERE subid IN (:key2) AND Poscode=:postcode2");
$statement->execute(array(':key2' => $key2,':postcode2'=>$postcode));
// $row = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = array();
while( $row = $statement->fetch()) {
array_push($json, array($row['Name'], $row['PostUUID']));
}
header('Content-Type: application/json');
echo json_encode($json);
The result displayed currently in this form:
JSON: jack,55421894ab602,test,55439324cc43d
But I want to display like:
Name:jack,
Id:55421894ab602
.....and some other info-
Name:test
Id:55439324cc43d
.....and some other info-
This part:
$(".the-return").html("<br />JSON: " + data);
I tried: data[0];
But when I do this, only the first record displayed obviously.
What I'm trying is :
data[0] itself is an array. How to display that array together with other records fetched in nice html?
edited: WIth these edited code, i can only retrieve the last result, it's not looping through the array.
ajax
success: function (data) {
$("#main_content").slideUp("normal",function(){
//$(".the-return").html("<br />JSON: " + j_data);
for (i = 0; i < data.length; i++) {
$(".the-return").html("<div>Name:" + data[i].name + "<br/>Id:" + data[i].id);
}
console.log(data); // this shows nothing in console,I wonder why?
//alert(j_data);
});
}
php
$json = array();
while( $row = $statement->fetch()) {
//array_push($json, array($row['Name'], $row['PostUUID']));
array_push($json, array("name" => $row['Name'], "id" => $row['PostUUID']));
}
header('Content-Type: application/json');
echo json_encode($json);
First, to get the names of the fields in your template, you need store them in your array:
array_push($json, array("name" => $row['Name'], "id" => $row['PostUUID']));
Result after json_encode -> {"name":"TheName","id":"TheID"}
Next, in your js code, if the json that it receives is valid, you can do a loop:
success: function (data) {
$("#main_content").slideUp("normal",function(){
for (i = 0; i < data.length; i++) {
$(".the-return").html("<div>Name:" + data[i].name + "<br/>Id:" + data[i].id);
}
}
}
Of course, you can add style or class to the div.
I hope it helps.

How to pass mysql result as jSON via ajax

I'm not sure how to pass the result of mysql query into html page via ajax JSON.
ajax2.php
$statement = $pdo - > prepare("SELECT * FROM posts WHERE subid IN (:key2) AND Poscode=:postcode2");
$statement - > execute(array(':key2' => $key2, ':postcode2' => $postcode));
// $row = $statement->fetchAll(PDO::FETCH_ASSOC);
while ($row = $statement - > fetch()) {
echo $row['Name']; //How to show this in the html page?
echo $row['PostUUID']; //How to show this in the html page?
$row2[] = $row;
}
echo json_encode($row2);
How to pass the above query result to display in the html page via ajax below?
my ajax
$("form").on("submit", function () {
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "ajax2.php", //Relative or absolute path to response.php file
data: data,
success: function (data) {
//how to retrieve the php mysql result here?
console.log(data); // this shows nothing in console,I wonder why?
}
});
return false;
});
Your json encoding should be like that :
$json = array();
while( $row = $statement->fetch()) {
array_push($json, array($row['Name'], $row['PostUUID']));
}
header('Content-Type: application/json');
echo json_encode($json);
And in your javascript part, you don't have to do anything to get back your data, it is stored in data var from success function.
You can just display it and do whatever you want on your webpage with it
header('Content-Type: application/json');
$row2 = array();
$result = array();
$statement = $pdo->prepare("SELECT * FROM posts WHERE subid IN (:key2) AND Poscode=:postcode2");
$statement->execute(array(':key2' => $key2,':postcode2'=>$postcode));
// $row = $statement->fetchAll(PDO::FETCH_ASSOC);
while( $row = $statement->fetch())
{
echo $row['Name'];//How to show this in the html page?
echo $row['PostUUID'];//How to show this in the html page?
$row2[]=$row;
}
if(!empty($row2)){
$result['type'] = "success";
$result['data'] = $row2;
}else{
$result['type'] = "error";
$result['data'] = "No result found";
}
echo json_encode($row2);
and in your script:
$("form").on("submit",function() {
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "ajax2.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
console.log(data);
if(data.type == "success"){
for(var i=0;i<data.data.length;i++){
//// and here you can get your values //
var db_data = data.data[i];
console.log("name -- >" +db_data.Name );
console.log("name -- >" +db_data.PostUUID);
}
}
if(data.type == "error"){
alert(data.data);
}
}
});
return false;
});
In ajax success function you can use JSON.parse (data) to display JSON data.
Here is an example :
Parse JSON in JavaScript?
you can save json encoded string into array and then pass it's value to javascript.
Refer below code.
<?php
// your PHP code
$jsonData = json_encode($row2); ?>
Your JavaScript code
var data = '<?php echo $jsonData; ?>';
Now data variable has all JSON data, now you can move ahead with your code, just remove below line
data = $(this).serialize() + "&" + $.param(data);
it's not needed as data variable is string.
And in your ajax2.php file you can get this through
json_decode($_REQUEST['data'])
I would just..
$rows = $statement->fetchAll(FETCH_ASSOC);
header("content-type: application/json");
echo json_encode($rows);
then at javascript side:
xhr.addEventListener("readystatechange",function(ev){
//...
var data=JSON.parse(xhr.responseText);
var span=null;
var i=0;
for(;i<data.length;++i){span=document.createElement("span");span.textContent=data[i]["name"];div.appendChild(span);/*...*/}
}
(Don't rely on web browsers parsing it for you in .response because of the application/json header, it differs between browsers... do it manually with responseText);

Categories