working with PHP array in javascript - javascript

building a countdown to a date that is based on a variable integer that will indicate how many days are left. Im trying to return the result as the difference in unix time between the current time and the future time in an array including days, hours, minutes, seconds. All seems to work fine however instead of an array it seems to return the results as a string.
Can anyone see what is wrong with my markup here? Or do i need to do another conversion within javascript?
PHP
$zTimeCombined = array($days_remaining, $hours_remaining, $minutes_remaining, $seconds_remaining);
echo json_encode($zTimeCombined);
How im accessing the "array" in JS (within a GET success function)
var zDays = results[0];
var zHours = results[1];
var zMinutes = results[2];
var zSeconds = results[3];
edit:
possible duplicate of this question (use php array in javascript?), however the answers were not as succinct and were not as simple as was needed here. Id say this question is really very basic but will be handy for non PHP users like myself

The response you're getting from the AJAX is in string format, not in JSON.
To convert it to json format use JSON.parse()
The JSON.parse() method parses a string as JSON, optionally transforming the value produced by parsing.
var result = JSON.parse(response);

Related

How can a linq query be converted to JavaScript array containing only values?

I have a JavaScript grid library (it creates a table on the page) that accepts a JavaScript array as input, for rendering in the grid. I'm not certain, however, how to convert a Linq-to-SQL query (against a SQL Server database) to a JavaScript array containing only values.
I tried this, but it included the table column names in the JSON key (and I don't want JSON anyway, I want a JavaScript string array, unless this can be converted to an array?):
JsonConvert.SerializeObject(query)
Example of the format I need to produce:
[1,2,3],[4,5,6]
Environment: .NET Core 3.1
edit: Here is a sample of what I've currently got, this returns the less than desirable JSON (due to the query results being so large, having a JSON key for very element is going to literally double the size of the query):
Devices Table
ID Name
1 iPhone7
2 iPhone8
3 iPhone9
Needed Array (Note: no column names)
[1, "iPhone7"],[2, "iPhone8"],[3, "iPhone9"]
Current C# code in the controller method (returns undesirable key for every element currently)
var query = db.Devices;
var formattedResult = JsonConvert.SerializeObject(query);
return Ok(formattedResult);
Technically, you could do this:
var query = db.Devices.AsEnumerable()
.Select(d => new object[]{d.ID, d.Name});
var formattedResult = JsonConvert.SerializeObject(query);
return Ok(formattedResult);
But then the code on the other end of your request is going to have to translate all those arrays back into objects.
It's rarely worthwhile to complicate your model like this in order to optimize the size of your network traffic. If you're pulling enough items over the wire to make this a performance issue, you're likely to encounter a variety of other performance issues. I would first consider other options, like implementing paging.
Did you try
var query = db.Devices.ToList();
var array = JArray.FromObject(query);
return Ok(formattedResult)

Suitescript, nlapiRequestURL, can't turn a JSON from a URL into an object/array

In netsuite i'm using the nlapiRequestURL to retrieve a JSON data from flexport, an overseas shipping company. I have have the data as a string(to my knowledge retrieving json data makes it a string) and want to turn it into an array of objects, but everything I have tried has resulted in various errors.
trying...
`var output = nlapiRequestURL(url,null,headers,"GET");
var split = JSON.parse(output.getBody());
response.write(split);`
gave me
{records=[Ljava.lang.Object;#7220fad}
and trying to show any element of split gave me undefined or that it cant read element from index.
I've ran the string through a JSON checker and it said it was a valid JSON file. I've done various variations of JSON.parse and looked tried Tostring. I've been working on this for a while and have no idea why I can't parse this information properly. Any help is appreciated.
You have parsed the result but then you are writing the parsed object which just gets you the object’s implementation dependent toString() output.
If you are just trying to echo the response re-stringify the parsed payload.

getting last element in JSON not working

I am trying to take the last element in a JSON. I know order is not preserved, but the keys are unix timestamps so I can just sort. I am working from this question:
get last element of a json object in javascript
But I get nothing logged to the console and no errors.
my code:
var mydata = {"1509937402379":"7348.01","1509937412486":"7348.01","1509937422253":"7348.01","1509937426286":"7348.01","1509937430066":"7345.54"}
console.log(mydata[Object.keys(obj).sort().pop()]);
https://jsfiddle.net/Lmb5sd1m/1/
You missed.. .You require to use Object.keys(mydata).
var mydata = {"1509937402379":"7348.01","1509937412486":"7348.01","1509937422253":"7348.01","1509937426286":"7348.01","1509937430066":"7345.54"}
Review same fiddle https://jsfiddle.net/Lmb5sd1m/1/

What's an easy way to compare a javascript time string in an sql query

I am using Moment JS to create a date to compare to a field in SQL.
My MaxEditDate variable
var MaxEditDate = moment().subtract(3,'years').format("YYYY-MM-DD H:m:ss");
Is being compared as is without any success of course in an MS SQL query.
tblLabReport.dtCreated >= ${locMaxEditDate}
Is there an easy way of comparing sql dates to a javascript string date object ?
Thanks.

JSON.parse & JSON.stringify handling long integers as strings

I have the problem, that I need to parse long integers in my API. Since I don't do anything arithmetically, it is the easiest to handle them as Strings. I tried Bignumber.js, but it starts complaining if numbers are longer than 15 characters. Unfortunately I have to handle them as well.
Since I don't do anything arithmetically with it and actually even store those numbers as String I would like a JSON Parser that parses too big numbers as Strings and is capable of also treat them as numbers in JSON.stringify.
I tried the stringify with a replacer function, but I could not get rid of the quotes around my number.
I also did not find a library, that just takes care of this issue.
Edit / Clarification
I want my big number to be a String in javascript, but a number in JSON (after JSON.stringify)
e.g. Object in Javascript
var myObj = {
id: "89074987798719283473" // <-- String within javascript
}
var objString = JSON.stringify(myObj)
Now my objString should be
{id: 89074987798719283473}
And NOT
{id: "89074987798719283473"}
If you absolutely must do this and really can't find a better place to handle this, then remember that JSON is just a string, and all the tools for string manipulation can be brought to bear on this problem. So you could do something like:
var myObj = {
id: "89074987798719283473" // <-- String within javascript
}
var json = JSON.stringify(myObj); // this is {"id":"89074987798719283473"}
var numberJson = json.replace(/"id":"(\d+)"/,'"id":$1'); // this is now {"id":89074987798719283473}
console.log(numberJson);
Of course this is hacky and error prone as you have to be very careful about what you are matching (you might have other properties called id nested in your json that you don't want manipulated). If you wanted to make it a little more robust, you could append something the end of your id before you stringify to make it easier to find and replace it in the string.

Categories