I have tried to add a php file as the source of data for a jquery calendar that uses json as below:
<script>
$(document).ready(function() {
$("#eventCalendarHumanDate").eventCalendar({
eventsjson: 'modules/events/json/event.humanDate.json.php',
jsonDateFormat: 'human'
});
});
</script>
The php file works when i echo variables only but when i connected to the database and looped, it fails and i get the error "error getting json" But running my code separately i get no error from the php file itself.
<?php
$hostname_app_conn = "localhost";
$database_app_conn = "xx";
$username_app_conn = "xx";
$password_app_conn = "";
$app_conn = mysql_pconnect($hostname_app_conn, $username_app_conn, $password_app_conn) or trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_app_conn, $app_conn );
$query_rs_content = "SELECT * FROM `mod_events_events` WHERE `active`=1 ORDER BY `Id` LIMIT 365";
$rs_content = mysql_query($query_rs_content, $app_conn) or die(mysql_error());
$totalRows_rs_content = mysql_num_rows($rs_content);
header('Content-type: text/json');
echo '[';
$separator = "";
$days = 16;
$i = 1;
echo $separator;
while($row_rs_content = mysql_fetch_assoc($rs_content))
{
echo ' { "date": "'.$row_rs_content['eventday'].'", "type": "'.$row_rs_content['type'].'", "title": "'.$row_rs_content['Title'].'", "description": "'.$row_rs_content['teasertext'].'", "url": "" },';
}
$separator = ",";
echo ']';
?>
thanks in advance.
You should use the json_encode() function, something like this:
//more code above
$array = new array();
while($row_rs_content = mysql_fetch_assoc($rs_content))
{
$array[] = array(
'date' => $row_rs_content['eventday'],
'type' => $row_rs_content['type'],
'title' => $row_rs_content['Title'],
'description' => $row_rs_content['teasertext'],
'url' => '',
);
}
header('Content-type: application/json');
echo json_encode($array);
die();
Most likely you had some character not being escaped properly or something else that was causing it not to be a valid json array so Javascript is dying trying to parse it.
Related
I'm trying to pass an array with ajax with a post to a php page.
My code js is :
function funzione5(){
var aux2=document.getElementById('f1').value;
$.ajax({type: "POST",
url: "AddMeeting.php",
data: {
'aux':aux,
'aux2':aux2,
'k':k
},
success: {function(data){
console.log(data);
}
},
error: {function(){alert("Error");}}
});
$('#modalMeeting').modal('hide');
}
and the php page is :
<?php
if(strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest')
{
header("Location: Meetings.php");
exit();
}
if(!isset($_COOKIE["id"]))
{
$json_data = array(
'draw' => 0,
'recordsTotal' => 0,
'recordsFiltered' => 0,
'data' => [],
'error' => 'Laravel Error Handler',
);
$json = json_encode($json_data);
echo $json;
exit();
}
include("DB.php"); //dati configurazione del database
$cont = mysqli_real_escape_string($connessione, $_POST["k"]);
$title = mysqli_real_escape_string($connessione,
$_POST["aux[0]"]);
$date = mysqli_real_escape_string($connessione,
$_POST["aux[1]"]);
$place = mysqli_real_escape_string($connessione, $_POST["aux[2]"]);
$topic = mysqli_real_escape_string($connessione, $_POST["aux[3]"]);
$lat = mysqli_real_escape_string($connessione, $_POST["aux[4]"]);
$lng = mysqli_real_escape_string($connessione, $_POST["aux[5]"]);
for($i=6;$i<$cont;$i++)
{ $part_id+$i = mysqli_real_escape_string($connessione,
$_POST["aux[".$i."]"]); }
$card_id = mysqli_real_escape_string($connessione, $_POST["aux2"]);
$id2=$_COOKIE['id'];
echo mysqli_error($connessione);
$sql1=mysqli_query($connessione,"insert into meeting
(card_id,user_id,title,place,date,topic,lat,lng) values
('$card_id','$id2','$title','$place','$date','$topic','$lat','$lng');");
echo mysqli_error($connessione);
$json_data = array(
"result" => 1
);
$json = json_encode($json_data);
echo $json;
?>
Is it correct to pass an array in this way? I checked that in the function "funzione5" the values of the array are set correctly. What could be the problem? Can you explain me how to pass the array? I searched on the web but i didn't find anything.
Currently your params are being passed as "aux" and "aux2", not "aux[0]" as you have it set in PHP. If it's a simple array I suggest simply using a delimiter, so separate the inputs with whatever symbol and then explode it, it seems like that indeed could be done in your example.
I'm setting up a chatbot (dialogflow) with a PHP webhook
What I want to do is to take the user input to query a MySQL table and pass the result back to the dialogflow API
So far I succeeded with passing a text string back to the API, but I don't understand how to query the database and pass the result back to the dialogflow API
I'll appreciate your help with this
I've used the API format from the dialogflow docs here
This is what I have
<?php
$method = $_SERVER['REQUEST_METHOD'];
if($method == 'POST') {
$requestBody = file_get_contents('php://input');
$json = json_decode($requestBody);
$text = $json->result->parameters->cities;
$conn = mysqli_connect("xxx", "xxx", "xxx", "xxx");
$sql = "SELECT * FROM exampletable LIKE '%".$_POST["cities"]."%'";
$result = mysqli_query($conn, $sql);
$emparray = array();
while($row =mysqli_fetch_assoc($result)) {
$emparray[] = $row;
}
$speech = $emparray;
$response->speech = $speech;
$response->displayText = $speech;
$response->source = "webhook";
echo json_encode(array($response,$emparray));
else
{
echo "Method not allowed";
}
?>
Thankyou
whenever the webhook gets triggered you need to listen to actions from JSON responses,
from the action made the switch case of actions
index.php
<?php
require 'get_enews.php';
function processMessage($input) {
$action = $input["result"]["action"];
switch($action){
case 'getNews':
$param = $input["result"]["parameters"]["number"];
getNews($param);
break;
default :
sendMessage(array(
"source" => "RMC",
"speech" => "I am not able to understand. what do you want ?",
"displayText" => "I am not able to understand. what do you want ?",
"contextOut" => array()
));
}
}
function sendMessage($parameters) {
header('Content-Type: application/json');
$data = str_replace('\/','/',json_encode($parameters));
echo $data;
}
$input = json_decode(file_get_contents('php://input'), true);
if (isset($input["result"]["action"])) {
processMessage($input);
}
?>
get_enews.php
<?php
function getNews($param){
require 'config.php';
$getNews="";
$Query="SELECT link FROM public.news WHERE year='$param'";
$Result=pg_query($con,$Query);
if(isset($Result) && !empty($Result) && pg_num_rows($Result) > 0){
$row=pg_fetch_assoc($Result);
$getNews= "Here is details that you require - Link: " . $row["link"];
$arr=array(
"source" => "RMC",
"speech" => $getNews,
"displayText" => $getNews,
);
sendMessage($arr);
}else{
$arr=array(
"source" => "RMC",
"speech" => "No year matched in database.",
"displayText" => "No year matched in database.",
);
sendMessage($arr);
}
}
?>
So when the action gets caught it will get executed and goes in the getNews($param); function here I am getting year as a response from the user in my case and I am executing the query in the database and giving back a response from the database.
I am trying to build a JSON response from my server side, but it is not working as expected.
It is probably something simple but, I am not so good at PHP...
The basic expected response is a JSON with a single JsonArray and some other fields, for that, the relevant piece of code is shown here:
Sample of expected JSON response:
{
"pageNr": 2
"totalPages":28
"products":[
{
"user_name":"testUser001",
"product_ID":"4756373abdhg"
},
{
"user_name":"testUser002",
"product_ID":"475ggdfghghg"
},
{
"user_name":"testUser003",
"product_ID":"47466gdgbdhg"
},
{
"user_name":"testUser004",
"product_ID":"4000nfaergeb"
},
{
"user_name":"testUser005",
"product_ID":"adfer73abdhg"
}
]
}
Basic PHP code used to generate desired JSON (among sql query and other things):
$res = array();
$res2 = array();
while($r = mysqli_fetch_assoc($query2)) {
$res["user_name"] = $r["user_name"];
$res["product_ID"] = $r["prod_ID"];
array_push($res2,$res);
}
$response = ['pageNr' => $page];
$response = ['totalPages' => $totalPages];
$response = ['products' => $res2];
Response that this code is generating on Postman:
{
"products":[
{
"user_name":"testUser001",
"product_ID":"4756373abdhg"
},
{
"user_name":"testUser002",
"product_ID":"475ggdfghghg"
},
{
"user_name":"testUser003",
"product_ID":"47466gdgbdhg"
},
{
"user_name":"testUser004",
"product_ID":"4000nfaergeb"
},
{
"user_name":"testUser005",
"product_ID":"adfer73abdhg"
}
]
}
So, for some reason the JSON response is not accepting more fields pageNrand totalPages.
What is wrong here?.
Each assignment overwrites your array. You need to update it instead:
$res = array();
$res2 = array();
while($r = mysqli_fetch_assoc($query2)) {
$res["user_name"] = $r["user_name"];
$res["product_ID"] = $r["prod_ID"];
array_push($res2,$res);
}
$response = [];
$response['pageNr'] = $page;
$response['totalPages'] = $totalPages;
$response['products'] = $res2;
Try;
$res = array();
$res2 = array();
while($r = mysqli_fetch_assoc($query2)) {
$res["user_name"] = $r["user_name"];
$res["product_ID"] = $r["prod_ID"];
array_push($res2,$res);
}
$response .= ['pageNr' => $page];
$response .= ['totalPages' => $totalPages];
$response .= ['products' => $res2];
I am trying to display all records using jason in php.
but display all filed with null value.
I'm using postman for testing purpose.
I don't know what is the problem with that code. I getting null value only.
here is my code :
<?php
header('Content-Type: application/json');
$checkFields = "";
$REQUEST = $_SERVER['REQUEST_METHOD'];
if ($REQUEST == "POST")
{
include "DB/db.php";
$userlist = mysql_query("SELECT * FROM reg_services");
if(mysql_num_rows($userlist) > 0)
{
$p = 0;
$ph = array();
while($userlistdata = mysql_fetch_row($userlist))
{
$ph[$p]["UserId"] = $userlistdata['id'];
$ph[$p]["FirstName"] = $userlistdata['fname'];
$ph[$p]["LastName"] = $userlistdata['lname'];
$ph[$p]["Email"] = $userlistdata['email'];
$ph[$p]["Mobile"] = $userlistdata['mobile'];
$ph[$p]["Password"] = $userlistdata['password'];
$p++;
}
$json = array("success" => 1, "All_User_List" => $ph);
$jsonarray = json_encode($json);
}
}
else
{
$json = array("success" => 0, "message" => "Invalid Request Type(Use POST Method)");
$jsonarray = json_encode($json);
}
echo $jsonarray;
?>
please help me if you are know what is the error in code.
just replace this code with old one
$p = 0;
$ph = array();
while($userlistdata = mysql_fetch_array($userlist))
{
$ph[$p] = array();
$ph[$p]["UserId"] = $userlistdata['id'];
$ph[$p]["FirstName"] = $userlistdata['fname'];
$ph[$p]["LastName"] = $userlistdata['lname'];
$ph[$p]["Email"] = $userlistdata['email'];
$ph[$p]["Mobile"] = $userlistdata['mobile'];
$ph[$p]["Password"] = $userlistdata['password'];
$p++;
}
You need to tell PHP about arrays
while($userlistdata = mysql_fetch_row($userlist))
{
$ph[$p] = array(); // let PHP know it is an array
$ph[$p]["UserId"] = $userlistdata['id'];
$ph[$p]["FirstName"] = $userlistdata['fname'];
$ph[$p]["LastName"] = $userlistdata['lname'];
$ph[$p]["Email"] = $userlistdata['email'];
$ph[$p]["Mobile"] = $userlistdata['mobile'];
$ph[$p]["Password"] = $userlistdata['password'];
$p++;
}
just replace this while loop condition with olde one.
while($userlistdata = mysql_fetch_array($userlist))
now it's work
<?php
$username = "root";
$password = "pw";
$host = "localhost";
$database="dbname";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$myquery = "
SELECT `name`, `useTime`, `e_usage` FROM `electric_usage`
";
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
mysql_close($server);
?>
I use upper php source to load mysql to JSON
the result of php page is
[{"name":"LED STAND","useTime":"2015-09-10 14:17:33","e_usage":"0.0599970581514709"},
{"name":"LED STAND","useTime":"2015-09-10 14:20:33","e_usage":"1.10919825898689"},
{"name":"LED STAND","useTime":"2015-09-10 14:23:33","e_usage":"1.9208018439918"}]
how to change this format to like this(for nvd3 line graph)?
function cumulativeTestData() {
return [
{
key: "LED STAND",
values: [ [ 2015-09-10 14:17:33 , 2.974623048543] ,
[ 2015-09-10 14:20:33 , 1.7740300785979]]
}
}
or theres easy way to make NVD3 line graph from mySql DB?
edit :
d3.json("./mysqljson/dbread.php", function(data) {
var dataLoad = d3.nest()
.key(function(d){return d.name})
.rollup(function(u){
return u.map(function(x){return [x.useTime,x.e_usage]})})
.entries(data);
nv.addGraph(function() {
var chart = nv.models.multiBarChart()
.x(function(d) {return d[0]})
.y(function(d) {return d[1]})
.margin({top: 50, bottom: 30, left: 40, right: 10});
chart.xAxis
.tickFormat(function(d) {
return d3.time.format('%x')(new Date(d))
});
d3.select('#mainExample')
.datum(dataLoad)
.transition().duration(500)
.call(chart);
nv.utils.windowResize(chart.update);
});
working code to use d3.json and d3.nest function
You can achieve that by using d3's d3.nest() method as follows:
Assuming your data structure as you received it using d3.json is data, then if you do:
x=d3.nest()
.key(function(d){return d.name})
.rollup(function(u){
return u.map(function(x){return [x.useTime,x.e_usage]})})
.entries(data);
Then the result would be:
{
key = "LED STAND"
values = [
["2015-09-10 14:17:33", "0.0599970581514709"],
["2015-09-10 14:20:33", "1.10919825898689"],
["2015-09-10 14:23:33", "1.9208018439918"]
]
}
I hope this helps.