Sending JSON array to webservice from Google Sheet Script - javascript

We have a webservice that returns product information. The service expects a JSON array in the post data... The
A sample script from a simple HTML test web page is as follows (this works as expected):
&ltscript src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
// request is array of product IDs e.g. pid:[71,72,74]
// request is array of search terms e.g. find:['apples','oranges','pears']
// request can contain requested fields from products
// fields:['CostPrice','Published','title','Price']
jQuery.ajax({
url : 'http://somewebsite.com/__getProductData',
type: 'POST',
dataType : 'json',
data: { pid:[658,71,6,700], fields:['pid','CostPrice','type','published','title'] },
success:function(data) {
// do something with the response...
});
},
error: function( jqXHR, textStatus, errorThrown) {alert('Error Status:' + textStatus + ' Error:'+errorThrown); }
}
);
});
</script>
The web service, written in PHP, receives this correctly. Dumping (print_r) the data received by the web service from the client results in the following array:
Array (
[pid] => Array ( [0] => 658 [1] => 71 [2] => 6 [3] => 700 )
[fields] => Array ( [0] => pid [1] => CostPrice [2] => type [3] => type [4] => published [5] => title )
Now to the problem.... I'm trying to call the webservice from a Google Sheet Script as follows:
function getProduct( pid,datetime) {
//
var url = 'https://somewebsite.com/__getProductData';
//pid:[658,71,6,700], fields:['pid','CostPrice','type','published','title']
var nids = new Array( 658,71,6,700 );
var fields = ['pid','CostPrice','type','published','title']
var payload =
{
pid : nids,
fields: fields
};
var options =
{
"method": 'POST',
"payload": payload
};
var response = UrlFetchApp.fetch(url, options);
Logger.log(response);
}
When the PHP web service is called from Google Sheets script the JSON array is not receive correctly:
Array ( [data] => { pid=[Ljava.lang.Object;#1bfbb500} fields=[Ljava.lang.Object;#3ffbb500})
I expect this is something associated with encoding or headers... I've tried most combinations of headers and contentType but to no avail.... e.g.
var headers = { "Accept":"json",
"Content-Type":"application/json",
};
Suggestions anyone?

var options = {
"method": 'POST',
"payload": JSON.stringify(payload)
};
Or stringify each of the values for pid & fields.

Jonathan - your suggested comment is the solution....
This didn't work:
var options =
{
"method": 'POST',
"payload": JSON.stringify(payload)
};
but stringify on the payload array elements worked (note that simple elements worked without stringify e.g. 'text' : "some text here") :
var nids = [658,71,6,700 ];
var fields = ['pid','CostPrice','type','published','title']
var payload =
{
pid : JSON.stringify(nids),
fields: JSON.stringify(fields)
};
var options =
{
"method": 'POST',
"payload": payload
};

I thinkg I have solved the same issue:
How to send a post request with an array in payload by urlfetchapp
the payload has to be prepared in this way! I have found this solution during I was making a workaround PHP script.
var payload =
{
"fields[0]":"firstString",
"fields[1]":"anotherString in array",
}
Not very intuitive, but it worked for me great!

Related

how to pass data to ajax for an express api call

I'm developing a website with express and ejs. I got into a trouble where i need to call an api via ajax. The problem is on a button onclick i'm passing two values to ajax data. but it gives error ,i tried a lot of ways and i'm messed up. i'm a newbie , find my code below.
const parsedData = JSON.parse(localStorage.getItem('myData'));
const container = document.getElementById('s1');
parsedData.data.rows.forEach((result, idx) => {
var a = result.master_id;
var b = result.session_name;
console.log(a,b,"a","b")
var userData = {"pid":a,"session" :b};
console.log(userData,"userData");
sessionStorage.setItem("user", JSON.stringify(userData));
console.log(userData,"data for api");
const card = document.createElement('div');
card.classList = 'card';
const content = `
<div class="row">
<div class="card-body" onclick="graphApi()">
</div>
</div>
`;
container.innerHTML += content;
});
function graphApi(){
var apiValue =JSON.parse( sessionStorage.getItem("user"));
console.log(apiValue, "value from card");
$.ajax({
type: "POST",
data: apiValue,
dataType:"json",
url: "http://localhost:5000/graphFromcsv",
success: function(data) {
console.log(data,"graph api");
}
error: function(err){
alert("graph api failed to load");
console.log(err);
},
});
i'm always getting this pid in api value undefined and 400 badrequest . but if i use raw data like,
{
"pid":"WE6",
"session":"W.csv"
}
instead of apiValue my ajax is success and i'm gettig the data. i'm using this data to plot a multiple line graph. Any help is appreciated.
You need to correct data key and their value(value must be string in case of json data) and also add contentType key like
$.ajax({
type: "POST",
data: sessionStorage.getItem("user") || '{}',
dataType: "json",
contentType: "application/json",
url: "http://localhost:5000/graphFromcsv",
success: function (data) {
console.log(data, "graph api");
},
error: function (err) {
alert("graph api failed to load");
console.log(err);
},
});
Note: In backend(ExpressJS), make sure you are using correct body-parser middleware like app.use(express.json());
Let assume your apiValue contain {"pid":"WE6", "session":"W.csv" } then body: { apiValue } will be equal to:
body: {
apiValue: {
"pid":"WE6",
"session":"W.csv"
}
}
But if you use the link to the object like body: apiValue (without brackets) js will build it like:
body: {
"pid":"WE6",
"session":"W.csv"
}

javascript to filter json and return another value

I have some javascript:
datasetID is set from the url value.
I get the json data.
const datasetID = urlParams.get('datasetID')
var data;
$.getJSON("json/data.json", function(json){
data = json;
});
Next I want to filter the json data based on the datasetID, then retrieve the value assigned to another attribute vernacularName and assign it to a const.
const record = data.filter(d => d.datasetID === datasetID);
const vernacularName =
How far away am I? Suggestions welcome.
sample code
[
{
"datasetID":"A1"
"language":"en",
"accessRights":"CC BY 4.0",
"vernacularName":"goat"
}
]
Filter in front-end is not a good option (let say your data.json is large) so if you could filter it in back-end before retrieving. For example, I send an ajax request with parameter ID: datasetID :
const datasetID = urlParams.get('datasetID')
var data;
$.ajax({
type: "POST",
url: "/getjson",
dataType: "json",
success: function (json) {
record = json
if (record.length === 1)
vernacularName = record[0]["vernacularName"]
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log('error');
},
data: {
ID: datasetID
},
cache: false
})
If you can't tweak in back-end and datasetID is unique then this should be enough:
if (record.length === 1)
vernacularName = record[0]["vernacularName"]

How do I call a JSON object?

I am having a problem calling a specific object. For example, I want to call mydata.title
I have the ff inside my php (this is just part of the code)
while($row = $DB->result->fetch_assoc()){
$Fthis[] = array(
"title" => $row["title"],
"subtitle" => $row["subtitle"],
"dates" => $row["dates"],
"Author" => $row["Author"],
"content" => $row["content"],
"himgsrc" => $row["himgsrc"]
);
array_push($marxarray, $Fthis);
}
echo json_encode($marxarray);
And then I have this AJAX in my js.
$.ajax({
url: 'editer.php',
type: 'POST',
data: { id: blogid },
success: function (data) {
var mydata= JSON.parse(data);
console.log(mydata);
alert(mydata.title);
}
});
Why does the alert return undefined ??
If I look at the log, I can see that the array has been passed correctly so no problem with the php (i think).
here's how it looks like anyway.
I checked your image, you have to use array index for that
mydata[0][0].title
success: function (data) {
var mydata= JSON.parse(data); // mydata is JSON array
}

Pass object from javascript to Perl dancer framework

I have following ajax code to pass values to dancer framework.
BookSave: function(data) {
### data is an object that contain more than one key value pair
var book = Book.code;
$.ajax ({
type: "GET",
url : 'textbook/save/' + book + '/' + data,
success: function(data) {
if(data.status == 1) {
alert("success");
} else {
alert("fail");
}
},
});
},
In dancer:
any [ 'ajax', 'get' ] => '/save/:book/:data' => sub {
set serializer => 'JSON';
my $book = params->{book};
my $data = params->{data}; ## This I am getting as object object instead of hash
};
Is there any way to pass object from js and getting as hash in dancer?
First and foremost, consider using the http PUT or POST verbs, and not GET. Not only is doing so more semantically correct, it allows you to include more complex objects in the http body, such as your 'data' hash (serialized, per my comments below).
I've had limited success with Dancer's native AJAXy methods, plus there is a bug that causes problems in some versions of Firefox. So instead, I serialize and then deserialize the JSON object.
Suggested changes (note I suggested changes to your routes as well):
$.ajax ({
type: "PUT",
url : '/textbook/' + book,
data: {
myhash : JSON.stringify(data)
},
dataType: 'json',
contentType: 'application/json',
success: function (response) {
if (response.status == 1) {
alert("success")
} else {
alert("fail")
}
}
})
and your Perl Dancer code changes as follows:
any [ 'ajax', 'put' ] => '/textbook/:book' => sub {
set serializer => 'JSON';
my $book = param('book');
my $data = from_json(param('myhash'));
};
I did not go as far as testing this code, but it should at least give you a good starting point to finish solving this problem.
Good luck with your project!

Converting list of objects to a JSON string

UPDATE: It was a programming error, please don't post answers. This question will be deleted. If you've already posted an answer please delete
I'm trying submit a form using jQuery and ajax. One of the fields is a list of objects, like this:
data = [{"id":1},{"id":2}]
I usually use JSON.stringify(data) but that didn't work this time, the server gets [object Object],[object Object]
When I do alert(JSON.stringify(data)) it works but something is changing it back to objects.
I'm using the jQuery form plugin and appending this data to the data attribute of the options object:
function showRequest(formData, jqForm, options) {
return true; //does nothing
}
var options = {
beforeSubmit: showRequest,
url: '/search.php',
iframe: true,
iframeTarget: '#iframe',
type: 'post'
};
options.data.data = JSON.stringify(data);
$('#myForm').ajaxSubmit(options);
How do I convert this to a JSON string that I can send it to the server?
This can be done using jQuery and without using JSON libray.
example using php on back-end
var data = [{"id":1},{"id":2}];
$.ajax({
type : 'POST',
url : 'test.php',
data: {my_array:data},
success : function(data){
//alert(data);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
//alert("error");
}
});
in php
$my_array= $_REQUEST['my_array'];
print_r($my_array);
it will print
Array
(
[0] => Array
(
[id] => 1
)
[1] => Array
(
[id] => 2
)
)

Categories

Resources