How to send multidimensional array from JavaScript to PHP in query string - javascript

I am using following code:
window.location.assign("index.php?module=pengu_dispatch&action=cover_letter&value="+list);
Here I want to send multidimensional array in query string to the PHP file.
Using JSON stringify function I converted array into string and send, but on PHP side after decoding I am not getting the complete array.
Please let me know what I could be doing wrong

You can put json in a GET param by url encoding it.
url = 'http://whatever/some.php?param='+encodeURIComponent(JSON.stringify(list))
And then in php read it like this
$list = json_decode($_GET['param']);
Be careful about the size of your list because URL's have a size limit of about 1~2kb. If you want to send a large amount of data you have to use POST.

Related

How to convert a textfile containing json data to a json file with all json payloads ordered?

Suppose I have textfile file that has json data in it that looks like the following:
1.5405E+13,{2021-02-16T16:40:34.269Z},"{"id":"1234567890","ts":"2021-02-16T11:41:27.517Z",...}"
1.5405E+13,2021-02-17T16:38:04.258Z,"{"id":"1234567890","ts":"2021-02-17T11:48:13.854Z",...}"
1.5405E+13,{2021-02-16T16:38:02.661Z},"{"id":"1234567890","ts":"2021-02-16T03:05:54.714Z",...}"
Each json payload has an id field, a timestamp field and several other fields as too. The extra fields aren't really significant here so I'm keeping them as "...". I want to create a script to read from the textfile, convert all data to json and then order that data based on the timestamp field. It's important to note that the prefix of the json data will not always be the same, so I can't use the fact that after say the 38th character I'll have a json in a string.
If I had all the data already in json form this wouldn't be too bad and in fact, I've created a Python script to read from a json file, order the data and write that ordered data, with each payload on a newline, to a textfile. That script is below. I'm just not sure how to do the initial conversion from a textfile that looks like the one above, to json data because of the extra characters before the json data. From there, I can just apply the script below:
import json
payloads = open('./ordered_data.json',)
data = json.load(payloads)
data.sort(key=lambda s: s['ts'])
with open('ordered_data.txt', 'w') as f:
for payload in data:
json.dump(payload, f)
f.write("\n")
The output of this script is, as required:
{"id":"1234567890","ts":"2021-02-16T03:05:54.714Z",...}
{"id":"1234567890","ts":"2021-02-16T11:41:27.517Z",...}
{"id":"1234567890","ts":"2021-02-17T11:48:13.854Z",...}
Any advice to do the initial conversation textfile -> json data in this script would be much appreciated!
Thanks in advance! Also, the script also doesn't necessarily have to be in Python. I chose that arbitrarily, I could also do this in node.js.

Receiving php data via ajax as an array instead of responseText in my javascript

Currently I have an ajax setup where my page with javascript calls a php file which then returns data via xhttp.responseText. This works great for strings but when I pass it a json encoded array, it still views that results as text. I get a string formatted version of my array that looks like this [1,2,3,4,5,6,7]
Which sort of works, but it's inconvenient because it's text representing an array and not an actual array.
How can I receive the data as an array instead of an array in text format? Currently I can still get the data using split(), but that seems sloppy. Is there an alternative to xhttp.responseText that would work better?
You can try sending your data as a JSON, which will give you all the flexibility in the kind of structure you want the data to have. PHP has the function json_encode which will convert your PHP variable into a JSON and you can receive this on the client side.
First, make sure your PHP encodes the JSON as I said and that you have the proper header set too, i.e.
header('Content-Type: application/json');
Next, in your AJAX code, do JSON.parse(xhttp.responseText) to retrieve the JSON data as JavaScript object.
Then you can do whatever you want with this object. Also, you can check your PHP is sending a JSON via xhttp.getResponseHeader("Content-type") which should return "application/json" if you are sending a JSON object.
You need to set header, smth like following
$data = array('1', '2', '3');
header('Content-Type: application/json');
echo json_encode($data);

Converting JS object to json string using JSON.stringify

I have four textboxes which contain json string which I create by calling json.stringify on various js objects..
eg. '["users.name","users.username"]' (This is the value of one textbox)
What I want to do is create a single json string from these four json strings and send them to the backend using POST..
So I create a object and add them like this
tmp = {}
tmp["columns"] = $("#sc").val();
/*adding more data....*/
$.ajax("/api/backend", {
data: JSON.stringify(tmp),
/* more ajax code...*/
});
The data that gets sent is of the following format..
{"columns":"[\"users.name\",\"users.username\"]"}
This is not a string but a json object...
Now when I do the following..
tmp1= JSON.stringify(tmp)
and Post using..
$.ajax("/api/backend", {
data: JSON.stringify(tmp1),
/*more code below..*/
The data that gets sent is of the following format and is string..
"{\"columns\":\"[\\\"users.name\\\",\\\"users.username\\\"]\"}"
This string has a lot of '\' characters which needs to be taken into account in the backend.
Is this the right way of handling my problem or am I doing something wrong?
Thanks
It depends on what you are trying to achieve.
If you want to send to the server a JSON that combines all JSON in your inputs, you'd better parse the JSON in your inputs, prior to adding them to you tmp object. That way, you get an object containing objects, rather than an object containing JSON strings.
Retrieving JSON from inputs would be like this:
tmp["columns"] = JSON.parse($("#sc").val());
See that you are storing objects within your tmp object, rather than JSON strings. Then, you can just send that object as JSON to your server.
Thus, your server would receive this:
"{\"columns\":\"[\"users.name\",\"users.username\"]\"}"
Which, I believe, looks much better. I hope that helps.

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.

Passing JavaScript array to input in PHP

I'm trying to pass an array from JavaScript to a PHP input. I want to pass my array as an array inside my input, not a string.
My array is this:
["0_1","0_2"]
And this is how I pass my array to my input:
$('#movefile_id').val(JSON.stringify(allfiledata));
Can I pass the array to the input file without making it a string?
read this:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
you can convert your array to JSON
var arrayJavascript = JSON.stringify(["0_1","0_2"]);
and with PHP, read this:
http://php.net/manual/es/function.json-decode.php
$arrayPHP = json_decode($_POST["arrayJavascript"]);
Here is the step by step process given below
1- Covert the Javascript Array to JSON
2- Post that JSON string to PHP using jquery post or jquery get
This is possible through only using Ajax. Because javscript is a Client side language and PHP is a server side language.We can only connect both using Ajax.

Categories

Resources