send array of Javascript constructors from PHP to Javascript - javascript

I am trying to send an array back to Javascript from PHP. I'm using Ajax to do this. I know how to send arrays to Javascript, but this time I'm trying to send an array that contains some Javascript constructors. For example I want to be able to send this: [new Date(2017,06,03), 25, 33] Is there a way to send this array to Javascript? If so, how will Javascript be able to use this array in a way where a new Date is created in the first index of the array?

Can not you just simply send value of new Date() instead of constructor? Will be more effective i assume.

Short answer: No, there is no direct way.
Long answer: When you say that you send arrays to Javascript from PHP, you need to understand that PHP is a server side language, and Javascript is what runs in the browser.
So, in between them, u have the network layer and all the things that transfers on that layer should be serializable, usually means strings.
So the data that you pass to the browser via Ajax usually is JSON.
It can contain only primitive values, like: string, number, boolean, null.
new Date(2017,06,03) is an javascript object, that is not part of JSON spec.
You can serialize the Date with some PHP func like date, send it via Ajax, and then deserialize it on Javascript world.
Something like that:
<?php
/* your Ajax return */
echo json_encode(array(date('c', mktime(0, 0, 0, 7, 1, 2000)), 25, 33)); // will return ["2000-07-01T00:00:00-07:00",25,33]
?>
Then on the JavaScript part u can parse it with Date constructor.
// Javascript
const response = ...
const myData = new Data(response[0]); // Will be Date obj.

Related

Assign data from LocalStorage to a block of data (Angular2)

So, I used data declared by myself, but now i switch the code to LocalStorage, and I'd like to know, how to get the data from one element of LocalStorage, and insert it to a block of data from my program.
Here's a part of code which shows the procedure which i use for inserting data
let l = this.lists;
localStorage.setItem('lists', JSON.stringify(l));
l is of type string, and lists is an array with data block.
I wanted to use this command
this.lists = localStorage.getItem('lists');
but unfortunately,it wants a string element, and doesn't want to work with my lists element...
Info time:
LocalStorage is implementation of Storage interface and it accepts and
returns plain strings so every time you want to store there something
a little bit more complex you have to serialize when inserting
(JSON.stringify) and deserialize when retrieving (JSON.parse)
You can use JSON.parse()
The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string.
this.lists = JSON.parse(localStorage.getItem('lists'));
localStorage is implementation of Storage interface, It works on plain strings. When you want to work with complex object serialize it using JSON.stringify() and deserialize using JSON.parse()

Pass javascript variable to PHP array using AJAX

I have a variable named var abc=5 and I want to pass that variable via AJAX so each time AJAX runs it I want to store that variable's value in a PHP array variable. Something like this:
$abc=$_request['abc'];
$xyz=array();
array_push($xyz,$abc);
when AJAX runs then I want output something like this:
$xyz[0]=1;
$xyz[1]=2;
.
.
.
.
$xyz[9]=10;
So I can use that array in JPGraph?
Instead of thinking about passing javascript "variables", think about passing modulus data that can be interpreted by Javascript and stored into whatever variables the client side script cares to use.
One easy and popular way to pass data between client and server is to use JSON. The JSON can be created on the PHP side and then sent to the client in response to the request which passes each individual number via Ajax.
It's easy enough to pass numeric data as delimited values, but when you start wanting to pass back and forth more complex data structures, JSON makes the most sense - it closely mirrors the basic data structures of Javascript as well as most modern languages: key/value pairs, arrays (lists of data), true, false, null, modulus strings and numbers.
Your JSON response payload might look like:
"[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]"
You can easily parse it in Javascript like so:
var data = JSON.parse( ajax_response )
See the Fiddle for a mock-up
Don't use multiple AJAX-requests. Just use 1 after you're done. Build the array you want to use in PHP in JSON format.
var string_to_send_with_ajax = JSON.stringify(['1','4','8']);
in php you can then use this in your PHP:
$array = JSON_decode($_POST['string_to_send_with_ajax']);
If you are positive you want to save the variables on the server with PHP, You define an array the first time. Make it a session variable so it will be on the server as long as the browser isn't closed by the user.
$_SESSION['plotArray'] = array();
use array_push to add a value to the array:
array_push( $_SESSION['plotArray'],$_POST['string_to_send_with_ajax']);

how to send string array as a response to ajax call from servlet

I made a ajax call from my jsp to servlet. when I want to return string then it is working fine. But I want to send response as a String array then its not working. Is it possible that I can send string array from servlet as a ajax response.
String[] roleAccess=null;
response.setContentType("text/html");
try{
roleAccess=new String[23];
roleAccess[0]="";
roleAccess[1]="checked";
roleAccess[2]="";
response.getWriter().write(roleAccess.toString());---this part I need to change.
Send the ajax response in json format by encoding the array in json and return it.
You can use Gson and then encode your array like:
String jsonRoleAccess = new Gson().toJson(roleAccess, roleAccess.class);
response.getWriter().write(jsonRoleAccess);
// OR do a one liner:
response.getWriter().write(new Gson().toJson(roleAccess, roleAccess.class));
And on the Javascript end, you can access it as a json object
// Assuming you've read the ajax response into var roleAccess
var checked = roleAccess[1];
You want to marshall the array as a JSON data type. The format returned by Java's array class is not in a format that JavaScript understands.
You should also wrap your array inside of an Object because of a security issue of passing top-level arrays back as JSON.
See Why are top level json arrays a security risk
Write it out to JSON instead. Javascript can't understand the result of a Java array's toString() method ([Ljava.lang.String;#5527f4f9), but I know it can understand JSON.
If you're only ever going to be using a string array and you don't want to use any more libraries:
public static String toJSON(String[] array)
{
String json = "[\"";
for (String s : array)
{
json += s + "\",\"";
}
return json.substring(0, json.length() - 2) + "]";
}
Depending on what Javascript framework you're using on your client-side, your JSON will be available as the xmlHttpRequestObject.responseText. AngularJS stores it in the $http.get().success method's first data parameter. jQuery stores it in the $.ajax({success}) method's first data parameter. Angular and jQuery automatically validate and eval it to an [object Object] for you, but xmlHttpRequestObject.responseText doesn't.

How to convert a JSON string to a JSON string with a different structure

I am building an application where data is retrieved from a third party system as a JSON string. I need to convert this JSON string to another JSON string with a different structure such that it can be used with pre-existing functions defined in a internal Javascript library.
Ideally I want to be able to perform this conversion on the client machine using Javascript.
I have looked at JSONT as a means of achieving this but that project does not appear to be actively maintained:
http://goessner.net/articles/jsont/
Is there a de facto way of achieving this? Or do I have to roll my own mapping code?
You shouldn't be passing JSON into an internal JavaScript library. You should parse the JSON into a JS object, then iterate over it, transforming it into the new format
Example
var json = '[{"a": 1:, "b": 2}, {"a": 4:, "b": 5}]';
var jsObj = JSON.parse(json);
// Transform property a into aa and property b into bb
var transformed = jsObj.map(function(obj){
return {
aa: obj.a,
bb: obj.b
}
});
// transformed = [{aa:1, bb:2},{aa:4, bb:5}]
If you really want JSON you'd just call JSON.stringify(transformed)
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/map
Here's another answer with an even more complicated transformation How to make a jquery Datatable array out of standard json?
From what I can tell from the home page, the JSONT project is about transforming JSON into entirely different formats anyway (i.e. JSON => HTML).
It's going to be a lot simpler to write your own mapping code, possibly just as a from_json() method on the object you're creating (so YourSpecialObject.from_json(input); returns an instance of that object generated from the JSON data).
From your question, I'm not sure if this fits your use case, but hopefully someone else will have a better answer soon.
Another option is using XSLT. As there are SAX readers and writers for JSON, you can write happily use XSLT with JSON. There's no horrific JSON to XML and back conversion needs to go on. See: http://www.gerixsoft.com/blog/json/xslt4json
I can definitely see the irony in using a XML based language to tranform JSON - but it seems like a good option.
Otherwise you're probably best of writing your own mapping code.

Saving javascript objects as strings

This is for a gaming application.
In my game I want to save special effects on a player in a single field of my database. I know I could just put a refrence Id and do another table and I haven't taken that option off the table.
Edit: (added information) This is for my server in node not the browser.
The way I was thinking about storing the data is as a javascript object as follows:
effects={
shieldSpell:0,
breatheWater:0,
featherFall:0,
nightVision:0,
poisonResistance:0,
stunResistance:0,
deathResistance:0,
fearResistance:0,
blindResistance:0,
lightningResistance:0,
fireResistance:0,
iceResistance:0,
windResistance:0}
It seems easy to store it as a string and use it using effects=eval(effectsString)
Is there an easy way to make it a string or do I have to do it like:
effectsString=..."nightVision:"+effects.nightVision.toString+",poisonResistance:"+...
Serialize like that:
JSON.stringify(effects);
Deserialize like that:
JSON.parse(effects);
Use JSON.stringify
That converts a JS object into JSON. You can then easily deserialize it with JSON.parse. Do not use the eval method since that is inviting cross-site scripting
//Make a JSON string out of a JS object
var serializedEffects = JSON.stringify(effects);
//Make a JS object from a JSON string
var deserialized = JSON.parse(serializedEffects);
JSON parse and stringify is what I use for this type of storatge
var storeValue = JSON.stringify(effects); //stringify your value for storage
// "{"shieldSpell":0,"breatheWater":0,"featherFall":0,"nightVision":0,"poisonResistance":0,"stunResistance":0,"deathResistance":0,"fearResistance":0,"blindResistance":0,"lightningResistance":0,"fireResistance":0,"iceResistance":0,"windResistance":0}"
var effects = JSON.parse(storeValue); //parse back from your string
Here was what I've come up with so far just wonering what the downside of this solution is.
effectsString="effects={"
for (i in effects){
effectsString=effectsString+i+":"+effects[i]+","
}
effectsString=effectsString.slice(0,effectsString.length-1);
effectsString=effectsString+"}"
Then to make the object just
eval(effectsString)

Categories

Resources