I create a json object from mysqli query (db class).
class db
public function Json() {
$result = $this->db->mysqli->query
("SELECT * FROM table");
$data = array();
while($row = $result->fetch_array()) {
$data[]= array('id' => "" .$row[0]. "", 'text' => "" .$row[1]. "");
}
echo json_encode($data);
}
In my php page I set a data-variable getting the json object from my php class
index.php
$db = new db();
<input type="hidden" id="jsonObject" data-json='<?php $db->Json();?>'/>
and get the data with jquery in this way
<script>
var data = $.parseJSON($('#jsonObject').attr("data-items"));
</script>
This work well, but if I have a php json data with apostrophe like
[{"id":"1","text":"I don't know"},{etc..}]
I've this error
SyntaxError: missing ) after argument list
I tried to use addslashes function in php when I create the associative array but with no success.
$data[]= array('id' => "" .$row[0]. "", 'text' => "" .addslashes($row[1]). "");
The json object is displayed correctly in the html source, so I guess it's a problem with jquery.
How can I solve my problem? Thank you
Related
I Have written the following function in the Categories Controller. which check the categories in the database and returns a response. Now if the parent_cat_id: "1" then I want to show the select2 field from the Form
public function parent_categories(){
$table = "store_categories";
$selectData = "id AS ID, cat_title AS TEXT,parent_cat_id";
$search = $this->input->get('q');
$where = array('status' => "enabled");
if(isset($search) && !empty($search)){
$field = "Title";
$Result = $this->Common_model->select_fields_where_like_join($table,$selectData,"",$where,FALSE,$field,$search);
}else{
$Result = $this->Common_model->select_fields_where_like_join($table,$selectData,"",$where);
}
if(empty($Result)){
$emptyArray = array(
array(
'ID' => 0,
'TEXT' => "No Record Found"
)
);
print json_encode($emptyArray);
return;
}
print json_encode($Result);
}
This is the select2 Field in form
I have tried something like this but I am sure this not works. I have write this <?php if(parent_cat_id == "1"){?> for you people to understand what i am saying that how to perform action like this on JSON response
<?php if(parent_cat_id == "1"){?>
<div class="col-md-4">
<div class="form-group">
<label for="Header Text" class="control-label">Parent Category</i>
</label>
<select name="parent_categories" id="parent_categories" class="form-control select2" ></select>
</div>
<!-- /.form-group -->
</div>
<?php } ?>
This is the JSON Response
{
ID:"2",
TEXT:"waqas",
parent_cat_id:"1"
}
$emptyArray = array(
array(
'ID' => 0,
'TEXT' => "No Record Found"
)
);
$json = json_decode(json_encode($emptyArray));
echo $json->parent_cat_id;
First off you need to use json_decode instead of encode in order to be able to work with the json data. Json decode will turn it into a object or an associative array for you which you can then use as you please.
I have a file that contains the following HL7 Information :
{
MESSAGE_HEADER: {
SENDING_APPLICATION: 'IQCARE',
SENDING_FACILITY: '10829',
RECEIVING_APPLICATION: 'IL',
RECEIVING_FACILITY: '10829',
MESSAGE_DATETIME: '20170713110000',
SECURITY: '',
MESSAGE_TYPE: 'ADT^A04',
PROCESSING_ID: 'P'
},
PATIENT_IDENTIFICATION: {
EXTERNAL_PATIENT_ID: {
ID: '110ec58a-a0f2-4ac4-8393-c866d813b8d1',
IDENTIFIER_TYPE: 'GODS_NUMBER',
ASSIGNING_AUTHORITY: 'MPI'
}}}
I want to convert this message to a json object and I did the following :
// copy file content into a string var
$json_file = file_get_contents("" . getcwd() . "\integration_layer\ADT^A04 - Patient Registration.json");
echo gettype($json_file);
// convert the string to a json object
$jfo = json_decode($json_file);
// read the title value
$title = $jfo->MESSAGE_HEADER->SENDING_APPLICATION;
// copy the posts array to a php var
$posts = $jfo->PATIENT_IDENTIFICATION->EXTERNAL_PATIENT_ID;
// listing posts
foreach ($posts as $post) {
echo $post->ID;
}
But I get the following error :
Severity: Notice
Message: Trying to get property of non-object
When I user the getype function of PHP on the $json_file , it is a string file.
How can I convert the message to an object for my own system consumption ?
Please validate your JSON code.
JSON rules
Data is in name/value pairs
Data is separated by commas
Curly braces hold objects - Your file contains no parent object
Square brackets hold arrays
A name/value pair consists of a field name (in double quotes). -
Your name fields are not in double quotes
Valid JSON code:
{
"MESSAGE_HEADER": {
"SENDING_APPLICATION": "IQCARE",
"SENDING_FACILITY": 10829,
"RECEIVING_APPLICATION": "IL",
"RECEIVING_FACILITY": 10829,
"MESSAGE_DATETIME": "20170713110000",
"SECURITY": "",
"MESSAGE_TYPE": "ADT^A04",
"PROCESSING_ID": "P"
},
"PATIENT_IDENTIFICATION": {
"EXTERNAL_PATIENT_ID": {
"ID": "110ec58a-a0f2-4ac4-8393-c866d813b8d1",
"IDENTIFIER_TYPE": "GODS_NUMBER",
"ASSIGNING_AUTHORITY": "MPI"
}
}
}
Working PHP example with valid JSON code:
<?php
$json = '
{
"MESSAGE_HEADER": {
"SENDING_APPLICATION": "IQCARE",
"SENDING_FACILITY": 10829,
"RECEIVING_APPLICATION": "IL",
"RECEIVING_FACILITY": 10829,
"MESSAGE_DATETIME": "20170713110000",
"SECURITY": "",
"MESSAGE_TYPE": "ADT^A04",
"PROCESSING_ID": "P"
},
"PATIENT_IDENTIFICATION": {
"EXTERNAL_PATIENT_ID": {
"ID": "110ec58a-a0f2-4ac4-8393-c866d813b8d1",
"IDENTIFIER_TYPE": "GODS_NUMBER",
"ASSIGNING_AUTHORITY": "MPI"
}
}
}
';
$object = json_decode($json);
echo $object->MESSAGE_HEADER->SENDING_APPLICATION;
?>
This is the HTML/PHP before being stored in the database:<li><?= $item->item['Manufacturer']; ?> <span class="divider">|</span></li>
This is the HTML/PHP after being stored in the database:
<li><a href="<?= dots('duo/'); ?>"><?= $item->item['Manufacturer']; ?></a> <span class="divider">|</span></li>
I assign this result to a variable:
$crumbles = $details['Crumbs'];
I echo the result like so:
<?php echo html_entity_decode($crumbles); ?>
But it returns this when I view source. It's not evaluating any of the PHP in the string.
<li><?= $item->item['Manufacturer']; ?> <span class="divider">|</span></li>
It shows in the browser as <?= $item->item['Manufacturer']; ?> |
How can I get it to evaluate the PHP as well as display the html correctly?
EDIT: Here is the code that handles the input into the DB. It serializes the form data (url, crumbs, meta info, etc) and adds it to an ajax queue.
$("form#seo_add").submit(function(e) {
console.log(this);
var data = $(this).serializeArray(),
$commitBtn = $(this).find("button"),
form_incomplete = false,
queueData = ['seo_add', data];
When fired, the queue controller runs $this->seo->add($seo_add, $user);
Which is modeled like this:
function add($data = null, $username = null) {
if (!is_array($data) || is_null($username)) die("Expecting new pageinfo");
//if a single item is being inserted, add it to a parent array so iteration works
if (!is_array($data[0]))
{
$data = array($data);
}
foreach ($data as $key => $page)
{
if (isset($page['section'])) unset($page['section']);
if (isset($page['action'])) unset($page['action']);
$add = $this->db->insert('pageinfo', $page);
$page = array_merge(array('id'=>$this->db->insert_id()), $page);
$last_queries[$key]['type'] = 'seo_add';
$last_queries[$key]['html'] = "New page: <b>" . $page['page'] . "</b>";
$last_queries[$key]['data'] = $page;
}
if ($this->db->_error_message())
$this->db_error('Unable to insert page');
return log_changes($last_queries, $username, $this->site);
}
Your PHP tags are being double encoded at your PHP tags < so you can run html_entity_decode over it twice.
Even if your php tags were decoded they would never be interpreted by PHP since you're echoing them out straight away, the way around this is to run what your database returns through eval like so:
$crumbles = html_entity_decode(html_entity_decode($crumbles), ENT_QUOTES);
eval("?>{$crumbles}<?");
I suggest using placeholders.
$html = '<li>[item] <span class="divider">|</span></li>';
I suggest not saving the html encoded. This would do the trick for you I guess:
$html = str_replace(['href','item'],[dots('duo/'),$crumbles],$html);
Probably you've to encode the $crumbles or dots('duo/') if that is user input.
this is how am using the ajax
$.get('checkanswer.php',{'clickedvalue':clickedvalue,'qid':qid},function(data){
$this.find(".report").html(data);
and this is my PHP code from where data is coming
<?php
$countresult=0;
$questionid=$_GET['qid'];
$answer=$_GET['clickedvalue'];
$dbconnect=mysqli_connect('localhost','root','','quiz')or die("Error Connecting to database");
$query="select answer from question_answer where id=$questionid";
$result=mysqli_query($dbconnect,$query);
while($rows=mysqli_fetch_array($result))
{
$dbanswer=$rows['answer'];
}
if($dbanswer==$answer)
{
echo "Correct";
$countresult=$countresult+1;
}
else{
echo "Incorrect";
$countresult=$countresult-1;
}
?>
Now previously i was just checking the result is correct or not and displaying tha result but now i want the PHP page to return even the variable that store the counts that is stored in $countresult. I know I have to use json but how to use it in PHP page ,pass the value and get access to that value from another page ,
In your php:
$data = array('countresult' => $countresult);
$str = json_encode($data);
echo $str;
In your js:
$.get('checkanswer.php',{'clickedvalue':clickedvalue,'qid':qid},function(data){
alert(data['countresult']);
}, "json");
Document about jQuery.get()
Use json_encode in php
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
Put messages in an array normally:
$server_response['error'] = "something";
$server_response['Success'] = "some other thing";
$sever_response['vars'] = "blah blah";
echo json_encode($server_response);
Then from js if your response variable is ServerResponse, you can access as
ServerResponse.error or
ServerResponse.Success or
ServerResponse.vars
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to generate .json file with PHP?
I want to use php to create a json like below. it will return a string json as a response from result sql query. How do I do?
{"Orders":[
{"DeliveryId":"DeliveryId","CustomerName":"CustomerName","PhoneNumber":"PhoneNumber","Address":"Address"},
{"DeliveryId":"DeliveryId","CustomerName":"CustomerName","PhoneNumber":"PhoneNumber","Address":"Address"}
]
}
my code
<?php
mysql_connect("mysql12.000webhost.com","a4602996_longvan","longvan2012");
mysql_select_db("a4602996_lv");
$id=$_POST[user];
$sql=mysql_query("select * from testlongvan where Status = 'PACKED'" );
$json = array();
if(mysql_num_rows($sql)){
while($row=mysql_fetch_row($sql)){
$json['Orders'][]=$row;
}
}
//while($row=mysql_fetch_assoc($sql))
//$output[]=$row;
print(json_encode($json));
mysql_close();
?>
But when use my code i recieve result, don't result i want:
{"Orders":[
["longvan","10/12/2012","Be34433jh","Long Van","115 Pham Viet Chanh, quan Binh Thanh","http://longvansolution.tk/image/sample.jpg","PACKED","0909056788"],
["takeshi","24/12/2012","BF6464633","Vn-zoom","16 nguyen cuu van, quan binh thanh","http://longvansolution.tk/image/hoadon3.jpg","PACKED","098897657"]
]}
Can you help me!
You may use json_encode() function to do that.
And your JSON format is invalid. Use : instead of =
// SERVER SIDE
<?php
//... create array
//....Obviously you would use your own SQL link and query
$animals = array();
$result = #mysqli_query('YOUR DB LINK', 'YOUR QUERY');
while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
array_push($animals, array(
'animal' => $row['animal'],
'sound' => $row['sound']
));
}
?>
// CLIENT SIDE
<html>
<script>
// RETURN FROM PHP PAGE ECHO VIA AJAX PERHAPS //
var animals = <?php echo json_encode($animals) ?>;
$.each(animals, function (i, elem) {
console.log(elem.animal + " makes a " + elem.sound);
});
</script>
</html>