Related
im using php to send a push but my json object isent getting the way i want...
i need my json to be like this :
{
"to": ["xxx"],
"data": {
"title": "dw",
"body": "dw",
"actions": [
{ "icon": "emailGuests", "title": "Candidatar-me", "callback": "app.emailGuests", "foreground": true},
]
}
}
but im getting this instead :
{
"to": "xxx",
"data": {
"title": "dw",
"body": "dw",
"actions": {
"icon": "send.ico",
"title": "EMAIL GUESTS",
"callback": "app.callbackName",
"foreground": true
}
}
}
i am building my json like this :
$fields = array ( 'to' => $row1['fcm_registered_id'] ,
'priority' => "high",
'data' => array("title" =>$titlepost,
"body"=> $msg,
"actions" => array('icon' => 'send.ico',
'title' => 'EMAIL GUESTS',
'callback' => 'app.callbackName',
'foreground' => true
)
),
);
Remember that json_encodeconverts non-numeric indexed arrays to objects. There is why you gets objects instead of array of objects. It's enough to wrap this array by another array. Here is fixed code:
$fields = array (
'to' => array( $row1['fcm_registered_id'] ),
'data' => array(
"title" =>$titlepost,
"body"=> $msg,
"actions" => array(
array(
'icon' => 'send.ico',
'title' => 'EMAIL GUESTS',
'callback' => 'app.callbackName',
'foreground' => true
)
)
)
);
And here is working example: http://phpio.net/s/1n0e
Little note: try to use new array syntax: [] than old array()
Please help me on this issue!! .. Providing auto suggest using twitter bootstrap typeahead based on the value typed in the text box.. based on the item selected from the suggestions shown in bootstrap an label dynamically shows the address and phone number(already in array ) below the text box and an drop down is loaded based on company_id.
The main thing is I am struct with fetching array associative id's and values's
my html is
<input class=" half" type="text" name="company_name" id="company_name" size="30" />
jscript is
$('#company_name').typeahead({
source: function(typeahead, query) {
$.ajax({
url: 'includes/get_company_details.php',
type: 'GET',
datatype: 'JSON',
async: false,
data: 'q=' + query,
success: function(result) {
console.log(result);
var convert = JSON.parse(result);
typeahead.process(convert);
}
});
}
});
my php file
while($row = mysql_fetch_array( $rsd )) {
$arr[] =array(
'company_name' => $row[1],
'company_id' => $row[0],
'company_reg_addr_line1' => $row[2],
'company_reg_addr_line2' => $row[3],
'company_reg_city' => $row[4],
'company_reg_city_id' => $row[10],
'company_reg_pincode' => $row[5],
'company_billing_addr_line1' => $row[6],
'company_billing_addr_line2' => $row[7],
'company_billing_city' => $row[8],
'company_billing_city_id' => $row[11],
'company_billing_pincode' => $row[9],
'company_phone_number' => $row[12]
);
}
$convert_name = json_encode($arr);
echo $convert_name;
The array iam getting is
[
{
"company_name": "vinod company ",
"company_id": "2",
"company_reg_addr_line1": "first line",
"company_reg_addr_line2": "second line",
"company_reg_city": "66",
"company_reg_city_id": "www.vinodproduction.com",
"company_reg_pincode": "122122",
"company_billing_addr_line1": "third line",
"company_billing_addr_line2": "fourth line",
"company_billing_city": "67",
"company_billing_city_id": "909099009",
"company_billing_pincode": "121212",
"company_phone_number": "1"
},
{
"company_name": "Vignesh",
"company_id": "4",
"company_reg_addr_line1": "iji",
"company_reg_addr_line2": "ij",
"company_reg_city": "83",
"company_reg_city_id": "j",
"company_reg_pincode": "0",
"company_billing_addr_line1": "ji",
"company_billing_addr_line2": "j",
"company_billing_city": "83",
"company_billing_city_id": "hjh",
"company_billing_pincode": "0",
"company_phone_number": "1"
}
]
iF I change the array like ["kumar productions","vinod company"," vignesh merchant"] the typeahead is working fine
but I need to send the address through the array itself!!!
so I changed the array which i mentioned below.the type ahead itself not working.
[{"company_name":"vinod company ","company_id":"2","company_reg_addr_line1":"first line","company_reg_addr_line2":"second line","company_reg_city":"66","company_reg_city_id":"www.vinodproduction.com","company_reg_pincode":"122122","company_billing_addr_line1":"third line","company_billing_addr_line2":"fourth line","company_billing_city":"67","company_billing_city_id":"909099009","company_billing_pincode":"121212","company_phone_number":"1"},{"company_name":"Vignesh","company_id":"4","company_reg_addr_line1":"iji","company_reg_addr_line2":"ij","company_reg_city":"83","company_reg_city_id":"j","company_reg_pincode":"0","company_billing_addr_line1":"ji","company_billing_addr_line2":"j","company_billing_city":"83","company_billing_city_id":"hjh","company_billing_pincode":"0","company_phone_number":"1"}]
Hi try your typeahead array like this:
Source:
[
{ ID: 1, Name: 'Toronto' }, { ID: 2, Name: 'Montreal' },
{ ID: 3, Name: 'New York' }, {ID: 4,Name: 'Buffalo' },
{ ID: 5, Name: 'Boston' }, { ID: 6, Name: 'Columbus' },
{ ID: 7, Name: 'Dallas' }, { ID: 8, Name: 'Vancouver'},
{ ID:9, Name: 'Seattle' },{ID: 10, Name:'Los Angeles' }
]
display:'Name', val:'ID'
After choosing the particular company you can get the respective company id from the textbox and do the logic of fetching the company details using the selected company id.
i have php var same this in index.php file :
<?php
$aoData = '
{ "name": "count", "value": "5" } ,
{ "name": "tbl", "value": "member" } ,
{ "name": "0", "value": "id" } ,
{ "name": "1", "value": "fname" } ,
{ "name": "2", "value": "lname" } ,
{ "name": "3", "value": "username" } ,
{ "name": "4", "value": "mail" }
';
include("main.php");
?>
i need send this php var as js function parameters in main.php and i use json like this:
<input type="button" onClick="run(<?php echo htmlentities(json_encode($aoData)); ?>)"
and i need use this var in load.js as a parameters. my load.js is like this :
function run(data1){
var oTable =$('#example').dataTable( {
aoData.push(**data1**)},
"onblur" : "disable",
"select" : true })}
but this way doesn't work.
It looks like your data is already json_encode()ed in your main PHP file. You should just be able to echo is using htmlentities() to make sure it is attribute-safe.
So run( <?php echo htmlentities( $aoData ); ?> )
Just as a note, what you're doing with json_encode() would work if $aoData looked like:
$aoData = array(
array( 'name' => '', 'value' => '' ),
array( 'name' => '', 'value' => '' ),
array( 'name' => '', 'value' => '' ),
);
json_encode() takes an array/object and turns it into JSON, which is a string that is formatted similarly to how your $aoData is currently.
You shouldn't be hand-coding json in PHP. There are too many potential encoding issues that can develop from this. Make a PHP array and then encode that.
$aoData = array();
$aoData[] = array('name' => 'count', 'value => 5);
...
echo json_encode($aoData);
The data table function needs two parameters. But you are pass one variable to that function.
Look through the documentation of datatable and their input types.
You can use php variable directly on your javascript function its on a same page.
Try to alert the javascript params for check yourself
Your json.encode not handled correctly. Already you have a json string. Then why you need encode
I actually agree with Tyler Carter
you should encode your JSON from a PHP array.
The following example is completely independent and you can see the result in your console
<?php
$aoData = json_encode(array(
array("name" => "count", "value" => "5"),
array("tbl" => "count", "value" => "member"),
array("0" => "count", "value" => "id"),
array("1" => "count", "value" => "fname"),
array("2" => "count", "value" => "lname"),
array("3" => "count", "value" => "username"),
array("4" => "count", "value" => "mail"),
));
?>
<html>
<body>
<input type="button" onclick="console.log(<?=htmlentities($aoData);?>)" value="run"/>;
</body>
</html>
i have project to show a text area inside the extjs grid panel. the form success full become text area and save to database. but when i load the value from database it shown syntax error
in google console shown error like this
Ext.data.JsonP.callback8({"totalItems": 2,"items": [{ "no": "1","kegiatan": "Target 12345 - 5432
asd
asd
asd
", "target": "harus sesuai target" },{ "no": "2","kegiatan": "Target 12 revisi error lagi", "target": "78.00" }]});
here the form created by request_form.js
function test(v){
return v === undefined || v === null ? '' : v.replace(/\n/g, '<br>');
}
.......
xtype: 'gridpanel',
id: 'frm_request_form_gridpanel',
title: 'Rencana Target dan Pencapaian Kerja',
width: 750,
height: 300,
border: 1,
margin: '10 5 10 10',
store: Ext.data.StoreManager.lookup('DetailTargetStore'),
columns: [
{header:'No', dataIndex: 'no', width: 40},
{header:'Jenis Kegiatan', dataIndex: 'kegiatan',
width: 350,
//type: 'textarea',
//grow:true,
//renderer:columnWrap
// field: {type: 'textarea',maxLength: 1024,renderer:columnWrap,grow:true}
renderer:test,
editor:'textarea',
flex: 1
....
handler: function(){
var dataObj = [];
var dataEmployee = EmployeReqStore.data.items;
var editedRecords = DetailTargetStore.getModifiedRecords();
for (var i=0; i<editedRecords.length; i++) {
dataObj.push(
{
tag_id:'edited',
emp_id:Ext.getCmp('nik').getValue(),
periode: Ext.getCmp('frm_request_form-periode').getValue(),
ccgroup : dataEmployee[0].data.ccgroup_id,
costcenter : dataEmployee[0].data.costcenter_id,
location : dataEmployee[0].data.location_id,
targetno: editedRecords[i].data.no,
targetket: editedRecords[i].data.kegiatan,
targetnilai: editedRecords[i].data.target,
//targettipe: editedRecords[i].data.target_tipe,
status: 'DRAFT'
}
);
}
.....
id: 'SubmitBtn',
text: 'Submit',
handler: function(){
var dataObj = [];
var dataEmployee = EmployeReqStore.data.items;
var editedRecords = DetailTargetStore.getModifiedRecords();
for (var i=0; i<editedRecords.length; i++) {
dataObj.push(
{
tag_id:'edited',
emp_id:Ext.getCmp('nik').getValue(),
periode: Ext.getCmp('frm_request_form-periode').getValue(),
ccgroup : dataEmployee[0].data.ccgroup_id,
costcenter : dataEmployee[0].data.costcenter_id,
location : dataEmployee[0].data.location_id,
targetno: editedRecords[i].data.no,
targetket: editedRecords[i].data.kegiatan,
targetnilai: editedRecords[i].data.target,
//targettipe: editedRecords[i].data.target_tipe,
status: 'NEW'
}
);
}
here save php with json object
foreach ($dataObj as $object) {
...
$stmtupdt = $db->prepare($sqlupdt);
$stmtupdt->execute(array(
':docno_id' => $doc_no,
':target_ket' => $object->targetket,
//':target_tipe' => $object->targettipe,
':target_nilai' => $object->targetnilai,
':target_no' => $object->targetno,
':target_status' => $object->status,
':periode_id' => $object->periode)
...
here load php with json object
$result = mysql_query($sql);
$totalitem = mysql_num_rows($result);
$count = 0;
echo '"totalItems": ' . $totalitem. ',';
echo '"items": [';
if ($result) {
if ($totalitem>0){
while($row = mysql_fetch_array($result)){
if(++$count == $totalitem) {
echo '{ "no": "'.$row['target_no'].'","kegiatan": "'. htmlentities($row['target_ket']).'", "target": "'.$row['target_nilai'].'" }';
}
else {
echo '{ "no": "'.$row['target_no'].'","kegiatan": "'. htmlentities($row['target_ket']).'", "target": "'.$row['target_nilai'].'" },';
}
}
i assume it some problem with json passing object but i dont know how to fix the json. please give me solution
thank you
Build a PHP array, and use json_encode:
$items = array();
while ($row = mysql_fetch_array($result)) {
$items[] = array(
'no' => $row['target_no'],
'kegiatan' => htmlentities($row['target_ket']),
'target' => $row['target_nilai'],
);
}
echo json_encode(array(
'totalItems' => $totalItems,
'item' => $items,
));
The error message Uncaught SyntaxError: Unexpected token ILLEGAL means usually a string that isn't closed on the same line, or in other words an unescaped new line in a string.
I want to retrieve data from mysql in the form of graph with the following code. But, nothing is shown. Can anybody help me?
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "graphdata.php",
dataType:"json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
var options = {'title':'Ticket Sales','width':500,'height':400};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data,options);
}
</script>
<?php
echo("<div id='chart_div'></div>");
?>
Here is my getdata.php:
$sql = "SELECT count(`booth_number`),`sold_by` FROM `registration1` where week(`Date`) = week(curdate()) GROUP BY `sold_by`";
$result = mysql_query($sql, $conn) or die(mysql_error());
//start the json data in the format Google Chart js/API expects to recieve it
$data = array(
'cols' => array(
array('label' => 'Month', 'type' => 'string'),
array('label' => 'Ticket Sales', 'type' => 'string')
),
'rows' => array()
);
while($row = mysql_fetch_row($result)) {
$data['rows'][] = array('c' => array(array('v' => $row[0]), array('v' => $row[1])));
}
echo json_encode($data);
As mentioned, I think you need to move your code inside the success callback:
function drawChart() {
$.ajax({
url: "graphdata.php",
type: "GET",
dataType:"json",
success: function(jsonData, textStatus, jqXHR) {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
var options = {'title':'Ticket Sales','width':500,'height':400};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data,options);
}
});
}
[edit] A working example (with some mocked data) can be found on jsBin.
[edit2] Update the example on jsBin with the output provided in the duplicate question:
{
"cols": [
{
"label":"Month",
"type":"string"
},{
"label":"Weekly Sales",
"type":"string"
}
],
"rows": [
{
"c":[
{"v":"3"},
{"v":"jaspreet singh "}
]
},{
"c":[
{"v":"3"},
{"v":"joseph swanson"}
]
}
]
}
The JSON returned by the server is wrong, the object should look like this:
"cols": [
{
"label":"Month",
"type":"string"
},{
"label":"Weekly Sales",
"type":"number"
}
],
"rows": [
{
"c":[
{"v":"jaspreet singh "},
{"v":"3"}
]
},{
"c":[
{"v":"joseph swanson"},
{"v":"3"}
]
}
]
};
The changes needed should now be obvious. Hope this helps.
[edit3] getdata.php should contain the following snippet imho:
$data = array(
'cols' => array(
array('label' => 'Month', 'type' => 'string'),
array('label' => 'Ticket Sales', 'type' => 'number')
),
'rows' => array()
);
while($row = mysql_fetch_row($result)) {
$data['rows'][] = array(
'c' => array(
array('v' => $row[1]),
array('v' => $row[0])
)
);
}