How to Parse JSON Object/Array in Ajax - ajax

How will I be able to get the value of updated in this json that is from my web service:
{"listener":{"id":"1","updated":"false"}}
Here's what I've tried:
$.ajax({
...
success : function(data) {
console.log("received listener: " + data);
var received = JSON.parse(JSON.stringify(data));
var listener = received.listener;
var length = listener.length;
//alert('returned json' + data + ' no. of products received: ' + length);
console.log('returned json' + listener + ' no. of listener received: ' + length); //it says undefined for the length
var updated = listener[0].updated;
}
});
Thanks.

Firstly, this line doesn't make sense:
var received = JSON.parse(JSON.stringify(data));
JSON.stringify converts a JSON structure to a string, and JSON.parse does the opposite. In other words:
var received = data.listener; // is equivalent.
Secondly, received is an object:
{"id":"1","updated":"false"}
It's not an array, so it does not have a length property. If you were looking to get the id of the received object then you'd obviously use:
var updated = listener.id;
For your code to work data would have to look like this:
{"listener":[{"id":"1","updated":"false"}]}

Related

Why the array will not send through the ajax call?

In my ajax code I'm sending an associative array to the go lang api but go lang would not receiving any array. Why?
for (var i = 1; i <= optionsArr; i++) {
span_arr.push({
day : valueSelected,
time_slug : i,
timing : $("#"+i).text(),
count : $('#select_count'+i).val()
});
}
console.log(span_arr[1].time_slug);
$.ajax({
url:"/api/v1/provider_spot",
type:"POST",
data:{span_arr:span_arr},
dataType:"json",
success:function(response){
console.log(response);
}
});
Why this ajax will not sending the array to the go api?
Here in go lang following mvc structure I want to receiving this data:
Route{"SaveProviderSpot", "POST", "/provider_spot", controller.SaveProviderSpot},
func SaveProviderSpot(c *gin.Context) {
fmt.Println(c.PostForm("span_arr"))
}
You can not send an array directly from client to server,due to the array definition may not be the same in both sides.
Two ways to solve it:
a. You can convert the array into a json string in the clinet,then send it to server as a string parameter,in the server side,you can parse it and convert it to array
b. Iterate the array,and convert it to a string using some special characters,also pass to server as string parameter,an example is as below:
var dataStr = "";
for (var i = 1; i <= optionsArr; i++) {
//each array element split with 3 semicolons,and each property in element split with 2 semicolons
dataStr += valueSelected + ";;" + i + ";;" + $("#"+i).text()
+ ";;" + $('#select_count'+i).val() + ";;;";
}
$.ajax({
url:"/api/v1/provider_spot",
type:"POST",
data:{dataStr:dataStr},
dataType:"json",
success:function(response){
console.log(response);
}
});
//now it is correct

How to passing array values from ajax to spring xml controller

I am creating survey page which has the following ajax to pass answer values
if(check==0)
{
var surveyVal="";
var len=answers.length;
for(i=0;i<=len-1;i++)
{
if(i!=len-1)
surveyVal+="val"+i+"="+answers[i]+"&";
else
surveyVal+="val"+i+"="+answers[i];
}
var ajaxUrl = "survey.do";
var data = surveyVal;
alert(data);
var returnValue = false;
tinymce.util.XHR.send({
url : ajaxUrl,
content_type : "application/x-www-form-urlencoded",
type : "POST",
data : {values: data.toString() },
success : function(data) {
alert("Done! Content Saved")
// Do anything you need to do if save successful
ed.setProgressState(false); // cancel showing progress
},
error : function( type, req, o ){
alert("Save Failed\n Error: " + type + "\n HTTP Status: " + req.status);
}
});
//the alert gives
val0=0,val1=2
etc as per the options I have chosen at the browser . how can I take these val to my controller as it is so that I can capture in logs and save in my database as individual answers . (please note I cant use annotation)
currently controller is like this which is not working
String val0 = request.getParameter("val0");
String val1 = request.getParameter("val1");
String val2 = request.getParameter("val2");
String val3 = request.getParameter("val3");
String val4 = request.getParameter("val4");
logger.info + "|"+ToolsUser.getPlatform()
+ ">Update Survey Inputs"
+ "|Answers:"
+ "|Answer-1:"+val0
+ "|Answer-2:"+val1
+ "|Answer-3:"+val2
+ "|Answer-4:"+val3
+ "|Answer-5:"+val4
);
thanks in advance
can you replace this line
data : {values: data.toString() },
with this
data : "values=" data.toString(),
and in your controller try to get the value of
request.getParameter("values");
and let me know if this worked for you

Parse.com not return the data from the table?

I want to Query the data from the table on parse collection.
This my code
var DummyObject = Parse.Object.extend("dummyFlow2");
var dummyObject = new DummyObject();
var query = new Parse.Query(DummyObject);
query.equalTo("oneT", 280);
query.find({
success: function(results) {
alert("Successfully retrieved " + results.length + " scores.");
// Do something with the returned Parse.Object values
console.log(results);
console.log(results[0]);
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
But i only got the id of the data not the content of it like this
This is some data from my class
So how can i get the rest of the data?
Thanks!
try this to get the contents:
Basically if you want to access data from parse object then data is stored with attributes and element name
EX as follows:
to get MF:
results[0].attributes.MF
to get id:
results[0].id
to get fiveHundred:
results[0].attributes.fiveHundred

Send mms using twilio and parse.com

I saw this topic before: Send MMS using Twilio in ios
But it cant help me.
So... the problem is I'm trying to send MMS using such chain: My program -> parse.com (using CloudCode)-> twilio. Text messages works fine but images never been delivered with mms. I'm sure that images comes to parse.com database.
Here's code of message send function on CloudCode (looks like problem happens here):
function Serialize(obj) {
var str = [];
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
}
console.log("Serialized object: " + str);
return str.join("&");
}
some code
var params = Serialize({
To: number,
From: message.get("from"),
Body: resultBody,
MediaInfo: medialUrl
});
Parse.Cloud.httpRequest({
method: 'POST',
url: 'https://api.twilio.com/2010-04-01/Accounts/**********************/Messages.json',
headers: {
'Authorization': 'Basic *****************************************************'
},
body: params,
success: function (httpResponse) {
console.log("SMS was sent to " + number);
promise.resolve(number);
}, error: function (httpResponse) {
var data = httpResponse.data;
var errorMessage = data.message;
console.error("Twilio Error response to number " + number + "\n" + JSON.stringify(httpResponse));
message.add("errorNumbers", number);
message.save();
promise.reject(number);
var error = new DetailedError();
error.set("phoneNumber", number);
error.set("errorMessage", "(" + data.code + ") " + errorMessage);
error.set("message", message);
error.save();
}
}); some further code
Any help appreciate
Twilio developer evangelist here.
You seem to be using the parameter name MediaInfo for the media URL. That should be MediaUrl (see the sending messages documentation). I think everything else you have looks good, so change that bit and your media should start working!

Where do the parameters come from when sending a post request in ZPL?

I'm also trying to code this in Ruby. So an example in ruby would be splendid!
I'm not sure which parameters you were looking for, the ZPL, the HTTP parameters, etc. To print something like a directory listing in ZPL using HTTP POST to a Zebra printer, it should have the format:
POST /pstprnt HTTP/1.1<CR><LF>Content-Length: 9<CR><LF><CR><LF>^XA^WD^XZ
I don't have a ruby example, but in javascript it looks like this:
function print_this(zpl, ip_addr)
{
var output = document.getElementById("output");
var url = "http://"+ip_addr+"/pstprnt HTTP/1.1";
var method = "POST";
var async = true;
var request = new XMLHttpRequest();
request.onload = function () {
var status = request.status; // HTTP response status, e.g., 200 for "200 OK"
var data = request.responseText; // Returned data, e.g., an HTML document.
output.innerHTML = "Status: " + status + "<br>" + data;
}
request.open(method, url, async);
request.setRequestHeader("Content-Length", zpl.length);
// Actually sends the request to the server.
request.send(zpl);
}

Resources