Replace JSON array quotes with brackets [ - javascript

I have a JSON array being passed form PHP and it looks like this:
[{from: "2019,09,14", to: "2019,09,14"}]
and I need it to look like this:
[{from: [2019, 9, 14], to: [2019, 9, 17]}]
here is my code thus far:
function getPricingDateRanges() {
var city = document.getElementById("pricingcityselect").value;
$.ajax({
url: 'getpricingdaterangepicker.php?city=' + city, // Change this to the uri of your file
method: 'GET', // Use the GET method
dataType: 'json', // Expect a JSON response
success: function(response) { // What will happen when the request succeeds
var darray = [{from:[2019,9,14], to:[2019,9,17]}];
console.log(response);
console.log(darray);
}
});
}
Added code from my PHP:
<?php
include 'dbconfig.php';
$city = ($_GET['city']);
$sql="SELECT start_date, end_date FROM date_ranges WHERE city='" . $city . "'";
$result = mysqli_query($conn,$sql);
// Create empty array.
$date_ranges = array();
// Add every row to array;
while($row = mysqli_fetch_array($result)) {
// Create an associative array to store the values in.
// This will later be a JavaScript Object.
$from = new DateTime($row['start_date']);
$ffrom = $from->format('Y,m,d');
$to = new DateTime($row['end_date']);
$fto = $from->format('Y,m,d');
array_push($date_ranges, array(
'from' => $ffrom,
'to' => $fto
));
}
// Send the $date_ranges as JSON.
$json = json_encode($date_ranges); // '[{"start": "2019-08-18", "end": "2019-08-19"}]'
echo $json;
?>

First, it's important to point out that the "JSON" you've included is not JSON. It is neither a string, nor are the property names quoted.
However, if this is actually the input you're dealing with, you can loop through the items, split the from and to values on ,, and use .map(Number) to convert them to integers.
const arr = [{from: "2019,09,14", to: "2019,09,14"}];
//Helper function to split on comma, convert items to numbers
const toIntegerArray = str => str.split(",").map(Number);
const result = arr.map(({from,to}) => ({
from: toIntegerArray(from),
to: toIntegerArray(to)
}));
console.log(result);

Parse JSON till the point with "2019,09,14".
then "2019,09,14" convert to array of numbers by:
"2019,09,14".split(',').map(el => parseInt(el, 10))

Related

Get JSON data from ajax call to PHP page through POST

I want to get some data from a form making AJAX call. I am getting the data as a string in my PHP page. The string looks like
'fname':'abc','lname':'xyz','email':'','pass':'','phone':'','gender':'','dob':''
Now I want to convert this entire string into array which would look like
["fname"] => "abc",
["lname"] => "xyz"... and so on
The ajax call is like below:
fname = $("#form-fname").val();
lname = $("#form-lname").val();
email = $("#form-username").val();
pwd = $("#form-password").val();
phone = $("#form-phone").val();
gender = $("#form-gender").val();
dob = $("#form-dob").val();
var user = {"fname":fname,"lname":lname,"email":email,"pass":pwd,"phone":phone,"gender":gender,"dob":dob};
$.ajax({
type: "POST",
url: "doRegistration.php",
data: user
})
.done(function( msg ) {
window.location.href = "../profile.php";
})
.fail(function(msg) {
sessionStorage.setItem("success","0");
window.location.reload();
});
And here is my PHP code:
$content = file_get_contents("php://input");
file_put_contents("log1.txt",$content); //This produces the string I get above
Now I try to convert the string into array as above
$dec = explode(",",$content);
$dec1 = array();
for($i=0;$i<count($dec);$i++)
{
$dec1[i] = substr($dec[i],strpos($dec[i],":"));
}
//After this $dec1 is empty and count($dec1) gives 0.
But this does not give me the required array. I have checked several answers here, but they do not solve my issue. I tried to google but did not find any resolution. Is there something wrong in the code? Kindly help. Thanks in advance.
Change quotes and add braces. Then you can decode resulting json
$string = "'fname':'abc','lname':'xyz','email':'','pass':'','phone':'','gender':'','dob':''";
print_r(json_decode('{' . str_replace("'", '"', $string) . '}', true));
result
Array
(
[fname] => abc
[lname] => xyz
[email] =>
[pass] =>
[phone] =>
[gender] =>
[dob] =>
)
In your code above, you are using the index of the for loop for the key of the array. If you are trying to archive (I believe it is called dictionary in Java). You can try the following code:
<?php
$string = "'fname':'abc','lname':'xyz','email':'','pass':'','phone':'','gender':'','dob':''";
$pieces=explode(',',$string);
foreach($pieces as $array_format){
list($key,$value) = explode(':',$array_format);
$array[$key]=$value;
}

PHP to JSON Array Output is Wrong

What I am trying to do doesn't feel difficult, but for some reason I can't seem to find the correct way to ouput this JSON array, from php.
PHP code:
$a = array();
$i=0;
while($row = mysqli_fetch_array($result))
{
$i++;
$a = array();
$epoch = $row['time'];
$dt = new DateTime("#$epoch"); // convert UNIX timestamp to PHP DateTime
$a = array(
"time" => $dt->format('Y-m-d H:i:s'),
"signal" => $row['signal'],
"symbol" => $row['symbol'],
"price" => $row['price'],
"timeframe" => $row['timeframe'],
"epoch" => $row['time']);
echo json_encode($a, JSON_UNESCAPED_SLASHES);
}
Output:
{
"time":"2016-11-14 17:23:00",
"signal":"Sell",
"symbol":"XAUUSDecn",
"price":"1221.64000",
"timeframe":"M1",
"epoch":"1479144180"
}
{
"time":"2016-11-14 17:07:59",
"signal":"Sell",
"symbol":"GBPJPYecn",
"price":"135.13200",
"timeframe":"M1",
"epoch":"1479143279"
}
The correct output should have },{ NOT }{ between each object.
What I am ultimately trying to do:
function getTrades(a) {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "core/engine.php",
data: "q=data&account="+a,
dataType: "html", //expect html to be returned
success: function(response){
if(response=="nologin") {
alert("Sorry, but either your account is not activated or your login is incorrect!");
} else {
var j = $.parseJSON(response);
$.each(j, function (k, v) {
$("#trades").html('<span class="tradesignal"><!-- span class="signalarrowup"></span-->'+v.time+'<span style="color:#2DC14E;"> '+v.signal+'</span>   <button class="tsym" id="sym_'+v.epoch+'">'+v.symbol+'</button>  '+v.price+'  '+v.timeframe+'</span>');
});
}
//alert(response);
console.log(response);
}
});
}
Each {json},{json} object will have its data printed into a span on an html page.
Appreciate the guidance!
Try creating a results array and push each one of the objects there, then after the loop finishes, convert the array to json and print it.
example:
$results = array();
$i = 0;
while($row = mysqli_fetch_array($result)){
//your code here
$a = array("time" => ....);
$results[] = $a; //this will add $a to $results
}
echo json_encode($results, JSON_UNESCAPED_SLASHES);
Just to add a little more explanation in addition to the code the other answers are suggesting. The problem is, you aren't outputting a JSON array. Each time you do
echo json_encode($a, JSON_UNESCAPED_SLASHES);
inside your loop, you output a valid JSON object like:
{
"time":"2016-11-14 17:23:00",
"signal":"Sell",
"symbol":"XAUUSDecn",
"price":"1221.64000",
"timeframe":"M1",
"epoch":"1479144180"
}
However, when you output the subsequent objects, getting a result like
{
"time": ...
}
{
"time": ...
}
You no longer have valid JSON. Even though each of the individual objects is valid, concatenating them together isn't. Simply adding a comma between the objects will still not make it valid. In order to produce an actual JSON array, the comma separated objects will need to be enclosed in square brackets like this:
[
{
"time": ...
},
{
"time": ...
}
]
That's why you need to add each of the arrays you're creating in the loop to an outer array and then json_encode the whole thing after the loop. The outer PHP array will become the outer JSON array you need.
As Xorifelse said, you want to put the data in an array, and then call json_encode on the array. Here is a code that should work:
$a = array();
$i=0;
while($row = mysqli_fetch_array($result))
{
$i++;
$epoch = $row['time'];
$dt = new DateTime("#$epoch"); // convert UNIX timestamp to PHP Date
$a[] = array("time" => $dt->format('Y-m-d H:i:s'), "signal" => $row['signal'], "symbol" => $row['symbol'], "price" => $row['price'], "timeframe" => $row['timeframe'],"epoch" => $row['time']);
}
echo json_encode($a, JSON_UNESCAPED_SLASHES);

Preserving order of an associative PHP array while passing it to javascript through ajax

So Here is my php file code
GetUserArray.php
$Users = array('7'=>'samei', '4'=>"chaya", '10'=>'abetterchutia');
echo json_encode($Users);
and this is my ajax request
$.ajax({
url: './GetUserArray.php',
type: 'POST',
dataType: "json",
success: function(users) {
console.log(users);
$.each( users, function( key, value ) {
console.log(key, value);
});
}
});
now what it gives me is in the console is an object sorted by the keys of that array while i want the orignal order which was 7 4 10 in my php file
Object {4: "chaya", 7: "samei", 10: "abetterchutia"}
4 chutiya
7 sali
10 abetterchutia
The problem with using hashmaps is that they don't actually specify order. Though, in PHP, an array is actually an ordered hashmap, so it does. Once you translate that into an object in Javascript, the order is no longer preserved. The only way to guarantee order in Javascript is to use an array.
So in PHP this works as expected and preserves order.
$arr = [4 => "I'm first", 1 => "I'm second", 3 => "I'm third"];
foreach($arr as $value) {
echo $value, "\n";
}
Which gives us
I'm first
I'm second
I'm third
But encode that to Javascript Object Notation (i.e. JSON) and you get an object, because in Javascript arrays don't have keys, they have indexes.
echo json_encode($arr);
Gives us...
{"4":"I'm first","1":"I'm second","3":"I'm third"}
If you tried to do the same in Javascript with this object you might not get the same order
var obj = {"4":"I'm first","1":"I'm second","3":"I'm third"};
var s = "";
for(var x in obj) {
s += + obj[x] + "\n";
}
document.write("<pre>" + s + "</pre>");
This might give you something more like...
I'm second
I'm third
I'm first
So the only way to fix that is to use an array...
json_encode(array_values($arr));
Now this gives us...
["I'm first","I'm second","I'm third"]
And the order is maintained.
However, if you want to preserve the keys as well, you'll have to create an array of objects.
$json = [];
foreach($arr as $key => $value) {
$json[] = [$key => $value];
}
echo json_encode($json);
Now you get...
[{"4":"I'm first"},{"1":"I'm second"},{"3":"I'm third"}]
Which in javascript, works perfectly as expected...
for(var x in obj) {
for(var n in obj[x]) {
obj[x][n]; // now you can both maintain order and have access to the key
}
}

How to sort json type data using javascript?

I have 3 dropdowns with list of places that I wanted to sort in ascending order. The first dropdown of places is sorted using codeigniter active record order_by function and the places were successfully sorted in ascending order.However,using onchange javascript function,when I choose a place in the first dropdown then populate the second dropdown of places excluding the place I have chosen in the first dropdown, the places returned were not sorted in ascending order even though there is order_by function I have in my query. I suspect that this is because of the json formatted data returned in onchange. Here are my codes. Thanks for the help.
This code sorts the data properly in ascending order
function get_dropdown_barangay(){
$query = $this->db->select('ID,brgy_name')
->from('tbl_barangay')
->order_by('brgy_name','asc')
->get()
->result_array();
$dropdown = array('0'=>'Select Barangay');
foreach($query as $value){
$dropdown[$value['ID']] = $value['brgy_name'];
}
return $dropdown;
}
Output Image:
Onchange code, the returned places are not sorted in ascending order
$('#brgy_id_1').change(function(){
var brgy_id = $("#brgy_id_1").val();
alert(brgy_id);
var data_val = {'brgy_id':brgy_id};
$.ajax({
type: "POST",
url:"<?php echo base_url();?>admin/get_barangay_list",
data:data_val,
dataType:'json',
success: function(data)
{
$('#brgy_id_2').empty();
$.each(data,function(id,val)
{
var opt = $('<option />'); // here we're creating a new select option for each group
opt.val(id);
opt.text(val);
$('#brgy_id_2').append(opt);
});
}
});
}); //end change
admin.php
function get_barangay_list(){
if(isset($_POST['brgy_id2'])){
$brgy_array_id = array('0'=>$_POST['brgy_id'],'1'=>$_POST['brgy_id2']);
} else{
$brgy_array_id = array('0'=>$_POST['brgy_id']);
}
$result=$this->core_model->get_barangay_list($brgy_array_id);
$this->output->set_header('Content-Type: application/json',true);
echo json_encode($result);
}
model.php
function get_barangay_list($brgy_array_id){
$query = $this->db->select('ID,brgy_name')
->from('tbl_barangay')
->where_not_in('ID',$brgy_array_id)
->order_by('brgy_name','asc')
->get()
->result_array();
$dropdown = array('0'=>'Select Barangay');
foreach($query as $value){
$dropdown[$value['ID']] = $value['brgy_name'];
}
return $dropdown;
}
Output Image showing data are not sorted in ascending order
One way to implement kinghfb's comment :
On the server side : build an array
$dropdown = array();
$dropdown[] = array('id' => 0, 'label' => 'Select city');
for ($query as $value) {
$dropdown[] = array('id' => $value['ID'], 'label' => $value['brgy_name']);
}
On the client side (javascript) : change your loop code :
$.each(data,function(id,val) {
var opt = $('<option />'); // here we're creating a new select option for each group
opt.val(val.id);
opt.text(val.label);
$('#brgy_id_2').append(opt);
});
You are losing your order here, because you are setting new keys (problem is described here Change array key without changing order).
So you have to keep the keys and due this you have to change the js part as well, because you can´t access the data using key-value anymore.
function get_dropdown_barangay(){
$query = $this->db->select('ID,brgy_name')
->from('tbl_barangay')
->order_by('brgy_name','asc')
->get()
->result_array();
$dropdown = array('0'=>'Select Barangay');
foreach($query as $value){
$dropdown[] = array("id" => $value["ID"], "name" => $value['brgy_name']); // setting new value and keep an numeric key which represents the order
}
return $dropdown;
}
and the js has to be like:
$('#brgy_id_1').change(function(){
var brgy_id = $("#brgy_id_1").val();
alert(brgy_id);
var data_val = {'brgy_id':brgy_id};
$.ajax({
type: "POST",
url:"<?php echo base_url();?>admin/get_barangay_list",
data:data_val,
dataType:'json',
success: function(data)
{
$('#brgy_id_2').empty();
$.each(data,function(object)
{
var opt = $('<option />'); // here we're creating a new select option for each group
opt.val(object.id);
opt.text(object.value);
$('#brgy_id_2').append(opt);
});
}
});
});
I had highlighted the changes, but I don´t know hot to use bold in code at SO....
You could sort your JSON using underscore
Just pass in your JSON and a sort function. Like so:
var cityJSON = [{city: 'San Vinente'}, {city: 'Pequnio'}, {city: 'Pili Drive'}, {city: 'Jc Aquino'}, {city: 'Banza'}];
console.log(cityJSON); // unsorted
cityJSON = _.sortBy(cityJSON, function(item){return item.city});
console.log(cityJSON); // sorted

JSON for jqPlot

I would like to use jqPlot usinge data from server side coming in JSON, like described in this example: http://www.jqplot.com/tests/data-renderers.php
My code is nearly the same like the example:
function myGraph(jsonurl) {
var ajaxDataRenderer = function(url, plot, options) {
var ret = null;
$.ajax({
// have to use synchronous here, else the function
// will return before the data is fetched
async: false,
url: url,
dataType:"json",
success: function(data) {
ret=data;
console.warn(data);
}
});
return ret;
};
var plot1 = $.jqplot('chartdiv', jsonurl, {
title: 'myTitle',
dataRenderer: ajaxDataRenderer,
dataRendererOptions: { unusedOptionalUrl: jsonurl },
series: [{
label: 'myLabel',
neighborThreshold: -1
}],
axes: {
xaxis: {
renderer: $.jqplot.DateAxisRenderer,
// min:'August 1, 2010 16:00:00',
tickInterval: '2 months',
tickOptions:{formatString:'%Y-%m-%d.%H:%M:%S'}
},
yaxis: {
tickOptions:{formatString:'$%.2f'}
}
},
});
On server side i'm using PHP (and Yii). The webpage returns an array, which is encoded to JSON by using CJSON::encode($resultArray); (this Yii function passed trough to the PHP JSON encode function).
The Results from the PHP script lookes like that:
{"2011-04-25 14:46:40":2,"2011-04-26 14:46:40":3,"2011-04-27 14:46:40":5}
The Ajax request on client side resolved something like this (output from console.info(); )
Object { 2011-04-25 14:46:40=2, 2011-04-26 14:46:40=3, ...}
Probably, jqPlot expect the following format:
[[["2011-04-25 14:46:40":0],["2011-04-26 14:46:40",3],["2011-04-27 14:46:40",0]]]
All the time i get the error uncaught exception: [object Object]
What is wrong?
Is there a way to convert the object for to the typical array form?
Thank you
I have something like this . I had 2 arrays for values,labels .You should construct string as below from arrays .
$size = count($labels);
for ($i = 0; $i < $size; $i++) {
$result = $result . "['" . $labels[$i] . "'," . $values[$i] . "]";
if($i != $size -1 ){
$result = $result . ",";
}
}
OR if you dont have 2 arrays and just have this string {"2011-04-25 14:46:40":2,"2011-04-26 14:46:40":3,"2011-04-27 14:46:40":5} you can replace { with [ , } with ] and , with ],[ . A dirty but quick solution .
After above code you might need to append '[' and ']' on both sides and return value.
Do not parse the result on the client side, jquery will do much better. Actually, the array you need for jqplot is in fact valid json. All you have to do is prepare your data and create the appropriate array structure in PHP:
$pairs = array(1=>2, 3=>5, 4=>7, 5=>12, 7=>23); // simple example
$result = array();
foreach ($pairs as $label => $value) {
$result[] = array($label,$value); // make a "small" array for each pair
}
echo json_encode(array($result)); // wrap the result into another array; multiple plot data go like "array($result, $result2, ...)"
The result looks like this:
[[[1,2],[3,5],[4,7],[5,12],[7,23]]]
and is excatly what you need.
From http://www.jqplot.com/tests/date-axes.php
Note, although jqPlot will parse most any human readable date, it is safest to use javascript time stamps when possible. Also, it is best to specify a date and time and not just a date alone. This is due to inconsistent browser handling of local time vs. UTC with bare dates.
And example data from site:
var line1=[['2008-09-30 4:00PM',4], ['2008-10-30 4:00PM',6.5], ['2008-11-30 4:00PM',5.7], ['2008-12-30 4:00PM',9], ['2009-01-30 4:00PM',8.2]];
So you need array filled with 2 element arrays. First string with date (use timestamp if can) and X value. I've tried to find input format for datetime parsing or something like that but with no result.
You generated
{"2011-04-25 14:46:40":2,"2011-04-26 14:46:40":3,"2011-04-27 14:46:40":5}
which is object with 3 fields. First field name is "2011-04-25 14:46:40" and it's value set to 2. You need to generate array like this:
[["2011-04-25 14:46:40", 0],["2011-04-26 14:46:40", 3],["2011-04-27 14:46:40", 0]]
JSFiddle with your data seems to work - so don't need timestamps ;)
http://jsfiddle.net/zpygcvps/1/
sine curve with PHP json_encode function
server side
<?php
$y = array();
$index = 0 ;
for($x = 0 ; $x< 13 ; $x += 0.5) {
$y[$index] = sin($x);
$index++ ;
}
$series = array();
$series[0] = $y ;
$data = json_encode($series);
echo $data;
?>
client side
<script type="text/javascript">
$(document).ready(function(){
var ajaxDataRenderer = function(url, plot, options) {
var ret = null;
$.ajax({
async: false,
url: url,
dataType:"json",
success: function(data) {
ret = data;
}
});
return ret;
};
// The url for our json data
var jsonurl = "/test/chart/jqplot-data.php";
var plot2 = $.jqplot('chartdiv', jsonurl,{
title: "AJAX JSON Data Renderer",
dataRenderer: ajaxDataRenderer,
dataRendererOptions: {
unusedOptionalUrl: jsonurl
}
});
});
</script>

Categories