Output of my JSON result - javascript

This code is working fine my concern is its output
Javascript side
function AjaxRetrieve()
{
var rid = document.getElementById('trg').value;
$.get('includes/getChat.php?chat='+uid + '&rid=' + rid + '&name=' + user,function(data)
{
$("#clog").html(data);
});
}
PHP side
$sql6="SELECT msgid FROM thread WHERE combination1=:msgids OR combination2=:submsgids LIMIT 1";
$msg_id = $con4->prepare($sql6);
$msg_id->bindParam(':msgids', $comb, PDO::PARAM_STR);
$msg_id->bindParam(':submsgids', $comb, PDO::PARAM_STR);
$msg_id->execute();
$msgd = $msg_id->fetchColumn();
$tbpre = $msgd;
$sql7 = "SELECT * FROM ".$tbpre."chat_conversation WHERE msgid=:chat";
$stmt7=$con3->prepare($sql7);
$stmt7->bindValue( 'chat', $msgd, PDO::PARAM_STR);
$stmt7->execute();
$rows = $stmt7->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($rows);
the output looks like this:
[{"msgid":"1","message_content":"asd","username":"ab","message_time":"2014-04-02 13:58:03","recipient":"cd"}]
how can I display the JSON result similar to this:
1
asd
ab
2014-04-02
cs

You can use the json dataType in jQuery, then stringify the object with indentation using JSON.stringify and output it in pre tags to keep the spaces and newlines
function AjaxRetrieve(){
var rid = document.getElementById('trg').value,
data = {chat : uid, rid : rid, name : user};
$.get('includes/getChat.php', data, function(result) {
var pre = $('<pre />', {text : JSON.stringify(result, undefined, 4)})
$("#clog").html(pre);
}, 'json');
}
FIDDLE
or to just output a list of the values
function AjaxRetrieve() {
var rid = document.getElementById('trg').value,
data = {chat: uid, rid: rid, name: user};
$.get('includes/getChat.php', data, function (result) {
var res = $([]);
$.each(result[0], function(key, value) {
res = res.add($('<div />', {text : value}));
});
$("#clog").html(res);
}, 'json');
}

Parse response on client side, and display it.
$.get('includes/getChat.php?chat='+uid + '&rid=' + rid + '&name=' + user,function(data){
var obj = JSON.parse(data);
var temp = obj[0].msgid + "<br>"+ obj[0].message_content + "<br>"+ obj[0].username + "<br>"+ obj[0].message_time + "<br>"+ obj[0].recipient;
$("#clog").html(temp);
});

PHP 5.4 offers the JSON_PRETTY_PRINT option for use with the json_encode() call.
Below is the link:
http://php.net/manual/en/function.json-encode.php
<?php
$json_string = json_encode($data, JSON_PRETTY_PRINT);

Related

Converting JSON format string into a real object in Angular

I have an JSON format string which I want to add like a parameter to atach to a post request.
I'm trying to do the reques, when I do the request I get this error from my web service:
#0 /opt/assets/WS/ws.php(48): Slim\Slim::handleErrors(8, 'Trying to get p...', '/opt/assets/WS/...', 48, Array)
#1 [internal function]: {closure}()
#2 /opt/assets/WS/vendor/slim/slim/Slim/Route.php(468): call_user_func_array(Object(Closure), Array)
#3 /opt/assets/WS/vendor/slim/slim/Slim/Slim.php(1357): Slim\Route->dispatch()
#4 /opt/assets/WS/vendor/slim/slim/Slim/Middleware/Flash.php(85): Slim\Slim->call()
#5 /opt/assets/WS/vendor/slim/slim/Slim/Middleware/MethodOverride.php(92): Slim\Middleware\Flash->call()
#6 /opt/assets/WS/vendor/slim/slim/Slim/Middleware/PrettyExceptions.php(67): Slim\Middleware\MethodOverride->call()
#7 /opt/assets/WS/vendor/slim/slim/Slim/Slim.php(1302): Slim\Middleware\PrettyExceptions->call()
#8 /opt/assets/WS/ws.php(59): Slim\Slim->run()
#9 {main}
It's like the request doesn't contains a real JSON object. How can I transform it? I did some tricks but seems doesn't work.
That's my script:
assets.controller('AfegirTipusActiusCtrl', function ($scope, $http){
// Camps formulari text pla
/* $scope.nomAtribut = "<input type='text' name='firstname'>";
$scope.mida = "<input type='number' name='firstname'>";
$scope.obligatori = "<input type='checkbox' name='vehicle' value='yes'>"; */
// Construeix combo
$http.get('http://10.0.203.73/WS/ws.php/getCombo/1').success(function(data) {
$scope.options = data;
});
$scope.atributs = [];
$scope.addRow = function(){
var newRow = {
nomAtribut: "",
tipus: "",
mida: "",
prioritat: "",
obligatori: "",
observacions: ""
}
$scope.atributs.push(newRow);
}
/* $scope.addField = function() {
$scope.atributs.push(newRow);
};*/
$scope.prioritat = $scope.atributs.length;
// Envia atributs a WS
$scope.sendRow = function(){
var d = "{'nomAtribut': 'marca','tipus': 'String','mida': '15','prioritat': '1','obligatori': 'No'}";
$http.post("http://10.0.203.73/WS/ws.php/tipusactius/alta", angular.toJson(d)).success(function(data){
$scope.status = data;
})
}
});
Edit:
Also I add the php Slim function which parse the request:
$app->post('/tipusactius/alta', function () use ($app) {
$json = $app->request->getBody();
header("Content-Type: application/json");
$json_decode = json_decode($json); // $json_decode conte l'bjecte format a partir del json del request
echo $json_decode->{'tipus'};
// $sql = "INSERt INTO atributs_actiu (nomAtribut, midaAtribut, tipus_actius_idtipus_actius, atributObligatori, ordre, tipusAtributs_idTipus, observacions
// , combo_idcombo, combo_codi) values ('".$json_decode->{'nomAtribut'}."', '".$json_decode->{'mida'}."', 1, '0', 1, 1, 'atribut de prova', 1, 1)";
$sql = "INSERt INTO atributs_actiu (nomAtribut, midaAtribut, tipus_actius_idtipus_actius, atributObligatori, ordre, tipusAtributs_idTipus, observacions
, combo_idcombo, combo_codi) values ('".$json_decode->{'nomAtribut'}."', '3', 1, '0', 1, 1, 'atribut de prova', 1, 1)";
$mysqli=getDB();
$result = $mysqli->query($sql);
});
Solved:
Like #vidriduch told:
$scope.sendRow = function() {
var d = {
'nomAtribut': 'marca',
'tipus': 'String',
'mida': '15',
'prioritat': '1',
'obligatori': 'No'
};
$http.post("http://10.0.203.73/WS/ws.php/tipusactius/alta", angular.toJson(d)).success(function(data) {
$scope.status = data;
})};
angular.toJson Serializes input into a JSON-formatted string
https://docs.angularjs.org/api/ng/function/angular.toJson
in your case you are serializing string ...
your code could look like this:
$scope.sendRow = function() {
var d = {
'nomAtribut': 'marca',
'tipus': 'String',
'mida': '15',
'prioritat': '1',
'obligatori': 'No'
};
$http.post("http://10.0.203.73/WS/ws.php/tipusactius/alta", angular.toJson(d)).success(function(data) {
$scope.status = data;
})};
If you want to convert a JSON string to JavaScript object, you should use the angular.fromJson() method.
Also, make sure to convert your single quotes ' to double quotes " in your JSON:
// ' becomes " in your string
var d = '{"nomAtribut": "marca","tipus": "String","mida": "15","prioritat": "1","obligatori": "No"}';
$http.post("http://10.0.203.73/WS/ws.php/tipusactius/alta", angular.fromJson(d))
.success(function(data){
$scope.status = data;
}
Make sure your JSON argument not locked by arbitrary reference.
Assigning a JSON string to a variable and passing it directly will work here.

How to send array in Ajax and get it in PHP as array

I want to send in ajax array in js, get it in php as an array and insert into with sql.
My ajax call looks like:
jQuery("#Save").click(function () {
$(".linesView").each(function () {
var action_name = "";
if (window.current_category === "Expenses") {
action_name = "Save_Expenses"
} else if(window.current_category === "Incomes") {
action_name = "Save_Incomes"
}
var line_id = $(this).attr("id").substring(5);
var category = $("#CategoryValue_" + line_id).html();
var date = $("#DateValue_" + line_id).html();
var amount = $("#AmountValue_" + line_id).val();
var repeated = $("#RepeatedValue_" + line_id).html();
var note = $("#NoteValue_" + line_id).val();
var data = json_encode([category,date,amount,repeated,note]);
$.post("AjaxHandler.php", { "action_name": action_name, "data": data }, function () {
//$("#ExpensesId_" + id).css('display', 'none');
});
});
});
The PHP code that needs to get the ajax call and add the data (by sql insert) looks like:
if(isset($_POST['action_name','data'])) {
$action_name = $_POST['action_name'];
$data=json_decode($_POST['data']);
$query = mysql_query("INSERT INTO Expenses (accountid, category, date, amount, repeated) VALUES ('$accountid', '$data[0]', '$data[1]', '$data[2]', '0')");
}
The accountid coming from the top of the page, I already do delete action and it works fine, so the accountid is ok. All others, I don't know.
I tried to do encode and then decode. I am not sure if the syntax is right. Anyway if I didn't write elegant code, please show me how it needs to look. Maybe i need to take each param from the data and not to call data[x]?
Use JSON.stringify()
var data = ([category,date,amount,repeated,note]);
$.post("AjaxHandler.php", { "action_name": action_name, "data": JSON.stringify(data) }, function () {
//$("#ExpensesId_" + id).css('display', 'none');
});
Encode the data array to JSON string using JSON.stringify() in javascript. At server side use json_decode() to decode the data.
jQuery:
jQuery("#Save").click(function() {
$(".linesView").each(function() {
var action_name = "";
if (window.current_category === "Expenses") {
action_name = "Save_Expenses"
} else if (window.current_category === "Incomes") {
action_name = "Save_Incomes"
}
var line_id = $(this).attr("id").substring(5);
var category = $("#CategoryValue_" + line_id).html();
var date = $("#DateValue_" + line_id).html();
var amount = $("#AmountValue_" + line_id).val();
var repeated = $("#RepeatedValue_" + line_id).html();
var note = $("#NoteValue_" + line_id).val();
var data = JSON.stringify([category, date, amount, repeated, note]);
//-----------------^--- Array to JSON string
$.post("AjaxHandler.php", {
"action_name": action_name,
"data": data
}, function() {
//$("#ExpensesId_" + id).css('display', 'none');
});
});
});
PHP :
if(isset($_POST['action_name','data'])){
$action_name = $_POST['action_name'];
$data=json_decode(json_decode($_POST['data']));
//-----^--- decoding JSON string
$query = mysql_query("INSERT INTO Expenses (accountid, category, date, amount, repeated) VALUES ('$accountid', '$data[0]', '$data[1]', '$data[2]', '0')");
}

jquery post form and variables together

I used this Code to send a form + a variable to a php-script.
function upload() {
var test = "test";
var infos = $('form').serialize() + '&' + test;
$.post("ajax.php", { infos: infos }).done(function (data) {
alert(data);
});
}
now the PHP-Code:
$data = $_POST['infos'];
echo $data;
returns: formfield1=value1&formfield2=value2&formfield3=value3&test
All values are in this variable...
But how i can use them seperatly with PHP?
For example:
$data = $_POST['formfield1'];
didn't worked :(
Use jQuery's serializeArray(). It will return you with array of objects that contain 2 properties: name and value. You can then parse it and pass it as data.
It could look like this
var formdata = = $('form').serializeArray();
var infos = { };
for (var i = 0; i < formdata.length; i++) {
infos[formdata[i].name] = formdata[i].value;
}
// To add separate values, simply add them to the `infos`
infos.newItem = "new value";
$.post("ajax.php", infos).done(function (data) {
alert(data);
});
Then in PHP, you'll retrieve values using $_POST["formfield1"].
Try to explode them with -
$data = $_POST['infos'];
$form_data = explode('&', $data);
$posted_data = array();
foreach ($form_data as $value) {
list($key, $val) = explode('=', $value);
$posted_data[$key] = $val;
}
var_dump($posted_data);
You can use the parse_str method to convert the query string into an array.
In your case, you can do something like this:
parse_str($_POST['infos'], $data); // $data['formfield1'], $data['formfield2'], $data['formfield3'] have the values you need
More details here: http://php.net/manual/en/function.parse-str.php
// here is the jquery part
function upload() {
var test = "test";
var infos = $('form').serialize() + '&' + test;
$.post("ajax.php", { infos: infos },function (data) {
alert(data); // the fetched values are alerted here.
});
}
//the php part is here
$data = $_POST['infos'];
$field_seperator='&';
$val_seperator='=';
$form_data_val=explode($field_seperator,$data);
foreach($form_data_val AS $form_vals){
$vals=explode($val_seperator,$form_vals);
echo $vals[1];// here the value fields of every form field and the test is fetched.
}
try this .

Convert string coming from web service to JSON

I have a connection to remote DB and I have get some statistical data from the DB. So I have decided to create a web service and get the desired data through it. DB server is SQL Server on Windows and I need to display data in my PHP web page.
First I have written the web service which returns string like
"[
{
"name" : "John",
"Age":"54"
},
{
"name":"Jack",
"Age":"33"
}
]"
I have got that string using PHP's file_get_contents() method.
$json = file_get_contents('http://myurl.org/services.asmx/namelistJson');
But there are some unwanted tags return, in the beginning
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://myurl.org/services.asmx?op=namelistJson">
in at the end
</string>
I clean them using
$json = strip_tags(file_get_contents('http://myurl.org/services.asmx/namelistJson'));
Now I have a json string.
I want to use this string as JSON for javascript in order to create a table.
<?php
$json = strip_tags(file_get_contents('http://myurl.org/services.asmx/namelistJson'));
?>
<script>
var response = $.parse(<?php echo $json; ?>);
$.each(response, function(i, item) {
$('<tr>')
.html("<td>" + response[i].name + "</td>"
+ "<td>" + response[i].Age + "</td>"
)
.appendTo('#nameList');
});
</script>
?>
<table id="nameList" class="table">
</table>
I am getting error about missing ] symbol. FireBug says that
SyntaxError: missing ] after element list
How can I convert string to json properly in order to use it on javascript?
EDIT:
If I modify the line
var response = $.parse(<?php echo $json; ?>);
to
var response = <?php echo $json; ?>;
I get ] error still.
HTML output is as the following:
<script>
...
var response = [{"name" : "John", "Age" : "14"}, {"name" : "40"}, ... ];
...
</script>
No need to create a string and then again convert it to json object, you can directly send json object from webservice and directly use it in the scripts(jquery) as below:
Below is the code in my webservice
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
public static object GetGridData()
{
DataTable dt = GetRecords(); // Fetch the data from sql in form of a datatable
var returnData = from row in dt.AsEnumerable()
select new
{
Id = row["Id"] // Here the Id in row["Id"] specifies the column in database
name = row["name"],
age = row["age"]
};
return returnData;
}
To access it as object in jquery, use the below code:
$.ajax({
url: 'url of webservice along with method',
dataType: 'json',
contentType: 'application/json; charset=utf-8;',
tyep: 'GET',
success: function (datas) {
var data = datas.d;
$.each(data, function (index, value) {
$('<tr>').html("<td>" + value.name + "</td>"+ "<td>" + value.Age + "</td>"
).appendTo('#nameList');
});
},
error: function (error) {
alert('error occured');
}
});
But if you really want to send it using string and parsing it into json then you can use
var jsonObject = JSON.parse(jsonstring);
or else you can verify if your json string is valid or not by just pasting your json string in jsonlint.com
Hope this helps :)

How to access an object's contents in javascript?

When I do
$.each(result, function(i, n){
alert("key: " + i + ", Value: " + n );
});
then for each iteration I see
key: 276, Value: {"owners":["he"],"users":["he","m"],"end":"07/06-2011","groups":[],"type":"in"}
How do I access the values of owners, users, end, groups, and type for each iteration?
In Perl would I have done
foreach my $key (keys %result) {
print $result{$key}{owners};
print $result{$key}{users};
...
}
Update
I get result from JSON like so
$.ajax({
type: "GET",
url: "/cgi-bin/ajax.pl",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { "cwis" : id },
// ...
success: function(result){
if (result.error) {
alert('result.error: ' + result.error);
} else {
$.each(result, function(i, n){
alert( "key: " + i + ", Value: " + n );
});
}
}
});
Update 2
It seams that the problem is the server side is not sending prober JSON.
This is the server side script that generate the JSON string.
!/usr/bin/perl -T
use CGI;
use CGI::Carp qw(fatalsToBrowser);
use CGI qw(:standard);
use JSON;
use utf8;
use strict;
use warnings;
my $cgi = CGI->new;
$cgi->charset('UTF-8');
my $json_string = qq{{"error" : "The user do not have any activities."}};
my $json = JSON->new->allow_nonref;
$json = $json->utf8;
# #a and $act is now available
my $data;
foreach my $id (#a) {
$data->{$id} = $json->encode(\%{$act->{$id}});
}
$json_string = to_json($data);
print $cgi->header(-type => "application/json", -charset => "utf-8");
print $json_string;
document.write(result[key].owners);
document.write(result[key].users);
UPDATE:
Apparently my comment on the question was the answer:
I'm no CGI expert but it looks like
you are double encoding your data into
JSON. Once with
my $json = JSON->new->allow_nonref; $json = $json->utf8;
and then again with
$data->{$id} = $json->encode(\%{$act->{$id}}) .
in $.each callbacks, this points to the current element, so
$.each(result, function(i, n){
alert(this.users);
});
n.owners or n['owners']
n.users or n['users']
etc.
In a loop...
$.each(result, function(k,v) {
console.log("key: " + k + ", value: " + v );
$.each(v, function(k,v)) {
console.log("key: " + k + ", value: " + v );
});
});
you can access them like this:
n.owners
or
n['owners']
or you can use another cycle :
$.each(result, function(i, n){
if (typeof(n)=='object') {
$.each(n, function(k, v){
alert('n.'+k+' = ' + v);
});
}
});
edit:
jsFiddle Example
Example 2
edit2: to avoid getting undefined make a simple check whether the key i is equal to "Value", so it's value will be an object

Categories