pass array in javascript .send function - javascript

This is regarding passing an array to a php page.Is it possible to send an array like this(code below)? if its not possible , what changes should i bring about to my code?
function ajax_post(){
var hr = new XMLHttpRequest();
hr.open("POST", "get_numbers.php", true);
hr.setRequestHeader("Content-type", "application/json");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var data = JSON.parse(hr.responseText);
var results=document.getElementById("ace");
//results.innerHTML=data.u1.port;
for (var obj in data)
{
results.innerHTML+=data[obj].port;
}
}
}
var cards= new Array();
cards[0]="hearts";
cards[1]="spades";
hr.send(cards);
results.innerHTML = "processing...";
}

.send() doesn't take a javascript array. There are a number of forms of data you could send and you will have to decide which form is appropriate, but an array is not one of them. The simplest would be to turn the array into a JSON string and send that.
var cards = [
"hearts",
"spades"
];
hr.send(JSON.stringify(cards));
Then, on the receiving end of things, you would parse the JSON back into whatever language form you are using on the server end. If it's PHP, then you can use the PHP functions for parsing the JSON which will put the data into a PHP array on your server.
Per the MDN doc page for the XMLHttpRequest object, .send() can take the following types of data:
void send();
void send(ArrayBufferView data);
void send(Blob data);
void send(Document data);
void send(DOMString? data);
void send(FormData data);
Using JSON would be using the string type.

Related

ASP.NET JavaScript - Invalid JSON primitive

I am trying to use "contentTools" with ASP.NET C# Website. I am trying to send the modified json to server side to store within database.
I have validated the JSON though external web but here is my code. For test purpose, I am trying to invoke an alert with a string sent back from my ASP.NET method.
window.onload = function () {
//ShowCurrentTime();
var FIXTURE_TOOLS, IMAGE_FIXTURE_TOOLS, LINK_FIXTURE_TOOLS, editor;
ContentTools.IMAGE_UPLOADER = ImageUploader.createImageUploader;
ContentTools.StylePalette.add([new ContentTools.Style('By-line', 'article__by-line', ['p']), new ContentTools.Style('Caption', 'article__caption', ['p']), new ContentTools.Style('Example', 'example', ['pre']), new ContentTools.Style('Example + Good', 'example--good', ['pre']), new ContentTools.Style('Example + Bad', 'example--bad', ['pre'])]);
editor = ContentTools.EditorApp.get();
editor.init('[data-editable], [data-fixture]', 'data-name');
editor.addEventListener('saved', function (ev) {
var name, payload, regions, xhr;
// Check that something changed
regions = ev.detail().regions;
if (Object.keys(regions).length == 0) {
return;
}
// Set the editor as busy while we save our changes
this.busy(true);
// Collect the contents of each region into a FormData instance
payload = new FormData();
payload.append('regions', JSON.stringify(regions));
xhr = new XMLHttpRequest();
xhr.open('POST', 'Default.aspx/getJSONHTMLResponse');
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
};
xhr.send(payload);
});
Here is my server-side:
[System.Web.Services.WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string getJSONHTMLResponse(string name)
{
return "Success";
}
And here is what I see in Developers tool in chrome as Request Payload:
------WebKitFormBoundaryilrxnMxm7ANdiYMp
Content-Disposition: form-data; name="regions"
{"para-1":"<p>\n testestest\n</p>","para-2":"<p>\n testestestestest.\n</p>"}
------WebKitFormBoundaryilrxnMxm7ANdiYMp--
And the error:
{"Message":"Invalid JSON primitive: ------WebKitFormBoundaryilrxnMxm7ANdiYMp.","StackTrace":" at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()\r\n at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)\r\n at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)\r\n at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)\r\n at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input)\r\n at System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext context, JavaScriptSerializer serializer)\r\n at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context)\r\n at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.ArgumentException"}
Just because you are accepting a string as a parameter from you api endpoint, send it as a string. No need to append into a FormData. That will send your payload as an object.
xhr.send(JSON.stringify(regions));
So I want to report back on how I resolved this issue.
Apparently I found out the hard way, form-data is tricky to be read. What I did instead:
Create a proper Web-service controller to accept a JToken response.
Parse the response in Key, Value pair.
Add it to a Session object and database as required.
Thanks!!

Referencing a Java list from a Servlet in JavaScript

I have a list which is pulled from a Postgres database and I need to be able to reference/manipulate it with JavaScript.
I have updated the code as shown below:
Here is the Servlet's doGet method:
protected void doGet(HttpServletRequest req, HttpServletResponse json)
throws ServletException, IOException {
List<Employee> employees = uds.findAll();
req.setAttribute("employees", employees);
json.setContentType("application/json");
json.getWriter().write(String.valueOf(employees));
}
And here is what I currently have in JavaScript:
var ajax = new XMLHttpRequest();
ajax.open("GET", "http://localhost:8080/project1attempt/servlet", true);
// send request
ajax.send();
// event to get response
ajax.onreadystatechange = function() {
// Case state is 4 e o http.status for 200, your request is OK.
if (ajax.readyState == 4 && ajax.status == 200) {
var data = ajax.responseText;
// the return
console.log(data);
}
}
}
The issue I am having at this point is that the client is not receiving data in JSON format. If I log the data as shown above, the log will produce something along the lines of the following:
[Employee{, employee_id='123456', email='lt#gmail.com', firstName='Juan',
lastName='Terri'}, Employee{, employee_id='2', email='sstark#mail.com',
firstName='Sansa', lastName='Stark'}]
This is the correct data, but not in a useful format.
However, if I try to do console.log(JSON.parse(data)), then I receive Uncaught SyntaxError: Unexpected token E in JSON at position 1.
I believe this is a simple syntax error on my part in the servlet, but am unsure of how to fix it.
You should use request.getAttribute():
<%
List<Employee> theEmployees = request.getAttribute("employees");
%>
But if you want to effectively use it in your javascript , it is recommended to convert it to json .
Try change your servlet response to json and get your data with Ajax
This is a sample to do it!
var ajax = new XMLHttpRequest();
ajax.open("GET", "your_url_here", true);
// send request
ajax.send();
// event to get response
ajax.onreadystatechange = function() {
// Case state is 4 e o http.status for 200, your request is OK.
if (ajax.readyState == 4 && ajax.status == 200) {
var data = ajax.responseText;
// the return
console.log(data);
}
}
For other noobs like me, I've compiled the following complete solution for this issue:
The Servlet should look something like this:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
resp.setContentType("application/json");
List<Employee> employees = uds.findAll();
String json = new ObjectMapper().writeValueAsString(employees);
resp.getWriter().write(json);
uds.findAll() is a method which returns a list of objects. ObjectMapper is a Jackson utility (Gson is another option, I believe). This puts the list into JSON format.
The HTML or JSP should look like this:
var ajax = new XMLHttpRequest();
ajax.open("GET", "http://localhost:8080/project1attempt/servlet", true);
// send request
ajax.send();
// event to get response
ajax.onreadystatechange = function() {
// Case state is 4 e o http.status for 200, your request is OK.
if (ajax.readyState == 4 && ajax.status == 200) {
var data = ajax.responseText;
// the return
console.log(JSON.parse(data));
}
}
This will get the list of objects in a usable format which you can then manipulate with JavaScript to do whatever you'd like. Hopefully this will help someone!

Django/Ajax/Javasdript JSON.parse convert string to JavaScript object

I am using Ajax to to send a get request from the sever, i am querying and getting a particular product from the product model, i want to return result as JavaScript objects but its return this '{' as i try to access the first value from the responseText[0]. How can i convert data return to js object.
here is my code
views.py
def edit_product(request):
product_id = request.GET.get('product_id')
print('THIS IS PRODUCT ID ', product_id)
product = Product.objects.get(pk=product_id)
data = [
{
'name':product.name,
'brand':product.brand,
'price':product.price,
'description':product.description
}
]
return HttpResponse(data)
ajax.js
function getProductEditId(product_id){
//alert(id)
document.getElementById('gridSystemModalLabel').innerHTML='<b> Edit product </b>';
//change modal header from Add product to Edit product
var request = new XMLHttpRequest();
request.open('GET', '/edit_product/?product_id=' + product_id, true);
request.onload = function(){
console.log('hello world', product_id)
//var data = request.responseText
var data = JSON.parse(JSON.stringify(request.responseText));
console.log(data[0])
}
request.send();
}
A HTTP response can not contain a dictionary, you can pass data through a specific format, like for example JSON. Django offers some convenience for that with the JsonResponse [Django-doc]:
from django.http import JsonResponse
def edit_product(request):
product_id = request.GET.get('product_id')
print('THIS IS PRODUCT ID ', product_id)
product = Product.objects.get(pk=product_id)
data = [
{
'name':product.name,
'brand':product.brand,
'price':product.price,
'description':product.description
}
]
return JsonResponse(data, safe=False)
But as the code hints, this is not safe, since an array at the root level was a famous JSON hijacking exploit.
It is typically better to just pass a dictionary (so no list), and then the safe=False parameter can be removed. Although it is not really "safe" to then just assume that all security exploits are gone.
Alternatively, you can use json.dumps [Python-doc] (which is more or less what JsonResponse does internally), but then you thus will probably end with duplicate code.
At the JavaScript side, you then only need to parse the JSON blob to a JavaScript object:
//change modal header from Add product to Edit product
var request = new XMLHttpRequest();
request.open('GET', '/edit_product/?product_id=' + product_id, true);
request.onreadystatechange = function() {
console.log('hello world', product_id)
if(this.status == 200 && this.readyState == 4) {
var data = JSON.parse(this.responseText);
console.log(data[0])
}
}
It is also not very clear to me why you encapsulate the data in a list here: if the response always contains one element, it makes more sense to just pass the dictionary.

XMLHttpRequest send JS Object

I'm trying to send an JS Object with an (POST) XMLHttpRequest, but I get no POST data in PHP.
This code worked before with an Ajax request, but i'm trying to get feedback from the server for an progressbar ( whitch is working fine now). That's why i've chagend to XMLHttpRequest.
The code:
var dataRows = {
'bewaarnaam': bewaarNaam,
rows: {}
};
$(".rows").each(function (i, obj) {
var row = $(obj);
var rowName = $(row).attr('name');
var chests = {};
$(".cv_chest", row).each(function (i2, obj2) {
chests[$(obj2).attr('id')] = {
'counter': $(obj2).attr('chest_counter'),
'height': $(obj2).attr('chest_height'),
'db_id': $(obj2).attr('db_id')
};
});
var top = $(row).css('top').replace("px", "");
var left = $(row).css('left').replace("px", "");
var rowData = {
'name': $(row).attr('name'),
'x': parseInt(left),
'y': (parseInt(top - 100)),
'rotation': rotation[$(row).attr('dir')],
'db_id': $(row).attr("db_id"),
'chests': chests
};
dataRows.rows[$(row).attr('id')] = rowData;
});
...
var xhr = new XMLHttpRequest();
xhr.open("POST", "{{ url('bewaarplaatsen/xhrTest/') }}", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(dataRows);
So my question is rather simple... How can i send an object with an post through the XmlHttpRequest function?
Use JSON:
var xhr = new XMLHttpRequest();
xhr.open("POST", "{{ url('bewaarplaatsen/xhrTest/') }}", true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.send(JSON.stringify(dataRows));
EDIT:
You can also use newer fetch API, see Fetch: POST JSON data.
You can't. "An object" is a data structure that exists in memory and only makes sense to the program it is dealing with it.
You need to serialise the data (e.g. using the application/x-www-form-urlencoded format, or JSON, or XML, or a host of other choices) and send that instead.
If you are trying to send entire DOM elements (and it isn't clear what the data you are trying to send actually is) then serialising them would involve converting them to HTML or (and this would usually be the better option) a data structure that they represent.

How to pass all the params as a single object while making ajax call

I have the below js code:
xmlhttp = GetXmlHttpObject();
if (xmlhttp != null) {
var url = "/support/residential/outage/serviceOutage?cbrnum=" + cbrnum + "&btn=" + btn + "&outagetkt=" + outagetkt;
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("thankyoucontent").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", url, true);
xmlhttp.send(null);
}
This calls a servlet by passing certain params in query string. Now my question is , can we bind all the params into a single object , send that object alone in query string and use the object in the servlet to retrieve the param values? Is it possible?
Yes, you can send the data as JSON to the server:
var data = {cbrnum: cbrnum, btn: btn};
var url = "...?data=" + encodeURIComponent(JSON.stringify(data));
Then on the server side, retrieve the value of data and parse the JSON into native data types (Converting JSON to Java).
Note though that browsers often impose a length limit on the URL. If you have a lot of data, do a POST request instead.

Categories

Resources