Appending to JSON notation? - javascript

I have the following JSON object:
new Ajax.Request(url, {
method: 'post',
contentType: "application/x-www-form-urlencoded",
parameters: {
"javax.faces.ViewState": encodedViewState,
"client-id": options._clientId,
"component-value": options._componentValue
}
});
Now, I would like to be able to append to the "Parameters" object programattically, but I am unsure of how I would actually do this.

you can simply assign to it. But you might want to do that before creating the request.
var parameters = {
"javax.faces.ViewState": encodedViewState,
"client-id": options._clientId,
"component-value": options._componentValue
}
parameters.foo = 'bar';
var myAjax = new Ajax.Request(url, {
method: 'post',
contentType: "application/x-www-form-urlencoded",
parameters: parameters
});

Assume that the JSON object is named as obj in the Ajax.Request Javascript function. You could now add to the parameters object like this:
obj['parameters']['someproperty'] = 'somevalue';
Hope this helps

You can't append to it after you call new, because Prototype automatically sends and starts processing the Ajax request upon creation, instead do something like this if you need to alter the parameters object:
var params = {
"javax.faces.ViewState": encodedViewState,
"client-id": options._clientId,
"component-value": options._componentValue
// Either add your additional properties here as:
// propertyName : propertyValue
};
// Or add your properties here as:
// params.propertyName = propertyValue;
new Ajax.Request(url, {
method: 'post',
contentType: "application/x-www-form-urlencoded",
parameters: params
});

Here's a solution I used to append to the JSON object's existing data attribute, but I needed it to be generic enough to handle different key-value pairs. Here's what I created based on this post which seems to work for me.
doAction : function(mData){
this.data = mData;
this.appendData = function(mDataToAppend){
var jsonStrAr = JSON.stringify(mDataToAppend).replace('{','').replace('}','').split('","');
for(var v = 0; v < jsonStrAr.length; v++){
var m = jsonStrAr[v].split(':');
this.data[m[0].replace(/"/g,'')] = m[1].replace(/"/g,'');
}
}
}
The result is a single JSON object with n to many attributes, which can then be sent over to the server via the JSON.stringify() command in the ajax request. Still getting comfortable/thinking with JSON, so there might be a better way to do this - in which case, I'm all ears.

Related

How do I pass a variable inside a POST request URL in JavaScript?

I am trying to pass a variable that is derived from a database (and keeps changing) to a fetch URL. I don't want to hard code it in the URL. How do I go about it? Here is the snippet of the code.
};
var searchString = amount;
var payload = JSON.stringify(data);
var options = {
'method': 'POST',
'Content-Type': 'application/json',
'payload' : data,
};
var url = 'https://......./**amount**/budget_items?token';
var response = UrlFetchApp.fetch(url, options);
I want to pass the search string variable but I don't know-how. Any help?
If you want to include searchString in the url you can use string concatenation or string interpolation. Here is string concatenation:
var url = 'https://.../' + searchString + '/...';
And here is string interpolation:
var url = `https://.../${searchString}/...`;
If you're sending a GET request, you must include the query arguments in the URL. You don't have to hardcode anything - just add the query parameters in the fetch itself:
var response = UrlFetchApp.fetch(url + `?search=${searchString}`);
If you're trying to send a JSON object, you should instead use POST. You'll be able to preserve the URL as it is (as long as it's accepting POST requests). You'll be able to send JSON in the data option too.
To dynamically include searchString in the URL string you can use Matt's method, but you have some problem with your code. You are passing the wrong payload. Here is the modified code you can use it.
};
var searchString = amount;
var payload = JSON.stringify(data);
var options = {
'method': 'POST',
'Content-Type': 'application/json',
payload
};
var url = `https://......./${searchString}/budget_items?token`;
var response = UrlFetchApp.fetch(url, options);
To know more about Template literals
You may also use URL object (needs polyfills in IE)
const url = new URL('http://foo.bar/?search');
url.searchParams.set('search', searchString);

javascript, array of string as JSON

I'm having problems with passing two arrays of strings as arguments in JSON format to invoke ASMX Web Service method via jQuery's "POST".
My Web Method is:
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public List<string> CreateCollection(string[] names, string[] lastnames)
{
this.collection = new List<string>();
for (int i = 0; i < names.Length; i++)
{
this.collection.Add(names[i] + " " + lastnames[i]);
}
return this.collection;
}
Now, the js:
function CreateArray() {
var dataS = GetJSONData(); //data in JSON format (I believe)
$.ajax({
type: "POST",
url: "http://localhost:45250/ServiceJava.asmx/CreateCollection",
data: dataS,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//something
}
})
}
GetJSONData() is my helper method creating two arrays from column in a table. Here's the code:
function GetJSONData() {
//take names
var firstnames = $('#data_table td:nth-child(1)').map(function () {
return $(this).text();
}).get(); //["One","Two","Three"]
//take surnames
var surnames = $('#data_table td:nth-child(2)').map(function () {
return $(this).text();
}).get(); //["Surname1","Surname2","Surname3"]
//create JSON data
var dataToSend = {
names: JSON.stringify(firstnames),
lastnames: JSON.stringify(surnames)
};
return dataToSend;
}
Now, when I try to execude the code by clicking button that invokes CreateArray() I get the error:
ExceptionType: "System.ArgumentException" Message: "Incorrect first
JSON element: names."
I don't know, why is it incorrect? I've ready many posts about it and I don't know why it doesn't work, what's wrong with that dataS?
EDIT:
Here's dataToSend from debugger for
var dataToSend = {
names: firstnames,
lastnames: surnames,
};
as it's been suggested for me to do.
EDIT2:
There's something with those "" and '' as #Vijay Dev mentioned, because when I've tried to pass data as data: "{names:['Jan','Arek'],lastnames:['Karol','Basia']}", it worked.
So, stringify() is not the best choice here, is there any other method that could help me to do it fast?
Try sending like this:
function CreateArray() {
var dataS = GetJSONData(); //data in JSON format (I believe)
$.ajax({
type: "POST",
url: "http://localhost:45250/ServiceJava.asmx/CreateCollection",
data: {names: dataS.firstnames,lastnames: dataS.surnames} ,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//something
}
})
}
This should work..
I think since you are already JSON.stringifying values for dataToSend property, jQuery might be trying to sending it as serialize data. Trying removing JSON.stringify from here:
//create JSON data
var dataToSend = {
names : firstnames,
lastnames : surnames
};
jQuery will stringify the data when this is set dataType: "json".
Good luck, have fun!
Altough, none of the answer was correct, it led me to find the correct way to do this. To make it work, I've made the following change:
//create JSON data
var dataToSend = JSON.stringify({ "names": firstnames, "lastnames": surnames });
So this is the idea proposed by #Oluwafemi, yet he suggested making Users class. Unfortunately, after that, the app wouldn't work in a way it was presented. So I guess if I wanted to pass a custom object I would need to pass it in a different way.
EDIT:
I haven't tried it yet, but I think that if I wanted to pass a custom object like this suggested by #Oluwafemi, I would need to write in a script:
var user1 = {
name: "One",
lastname:"OneOne"
}
and later pass the data as:
data = JSON.stringify({ user: user1 });
and for an array of custom object, by analogy:
data = JSON.stringify({ user: [user1, user2] });
I'll check that one later when I will have an opportunity to.

How to submit a form and pass some extra parameters to a $.getJSON callback method?

I know how to pass some parameters to a JQuery $.getJSON callback method, thanks to this question:
$.getJSON('/website/json',
{
action: "read",
record: "1"
},
function(data) {
// do something
});
And I can also submit a form to a $.getJSON callback method:
$.getJSON('/website/json', $(formName)
function(data) {
// do something
});
But I want to pass some parameters AND submit some form elements. How can I combine the two things togheter?
I could serialize the form elements and manually add some parameters to the url, and it looks like it works:
$.getJSON('/website/json',
'action=read&record=1&'
+ $(formName).serialize(),
function(data) {
// do something
});
But it doesn't look very elegant. Is this the proper way, or there's a better way to do it?
We could implement the functionality demonstrated in this answer as a custom jQuery instance method which produces an object of key/value pairs from a form and combines it with the properties that aren't derived from the form:
$.fn.formObject = function (obj) {
obj = obj || {};
$.each(this.serializeArray(), function (_, kv) {
obj[kv.name] = kv.value;
});
return obj;
};
$.getJSON('/website/json', $(formName).formObject({
action: "read",
record: "1"
}), function(data) {
// do something
});
Make an Ajax post to send the data to the server. Retrieve the parameter data in the backend code along with the form data.
var formData = {data from form};
formData.action = 'read';
formData.post = '1';
$.ajax({
url: '/website/json',
type: "post",
data: formData
}).done(function (data) {
// remove prior values set upon request response
formData.action = null;
formData.post = null;
});

Posting multiple objects in an ajax call

I have a list of data which is within multiple objects.
Each object has an ID and a status and then the main object has a type and a form id.
The problem I am having is posting result via ajax as it doesn't like the multiple objects.
This is the code I have:
var permissionsData = [];
$(".workflowBox").each(function(index, element) {
var obj = {
status: $(this).attr("data-user-status"),
record:$(this).attr("data-user-id")
};
permissionsData.push(obj);
});
permissionsData.userGroupID = userGroupID;
permissionsData.formID = formID;
var posting = $.ajax({
url: "http://www.test.com",
method: 'post',
data: permissionsData
});
How can I wrap/send permission data?
How about changing your array to an object and using jQuery's param function.
var permissionsData = {};
$(".workflowBox").each(function(index, element) {
var obj = {
status: $(this).attr("data-user-status"),
record:$(this).attr("data-user-id")
};
permissionsData[index] = obj;
});
permissionsData.userGroupID = userGroupID;
permissionsData.formID = formID;
var posting = $.ajax({
url: "http://www.test.com",
method: 'post',
data: $.param(permissionsData)
});
maybe you can use json2.js
it can parse the object to json string and parse the json string to object
you can use JSON.stringify method for parse object to json string

Passing string array from ASP.NET to JavaScript

I am trying to call the server side from JavaScript and then pass a string array back to JavaScript, but running into problems.
// Call the server-side to get the data.
$.ajax({"url" : "MyWebpage.aspx/GetData",
"type" : "post",
"data" : {"IdData" : IdData},
"dataType" : "json",
"success": function (data)
{
// Get the data.
var responseArray = JSON.parse(data.response);
// Extract the header and body components.
var strHeader = responseArray[0];
var strBody = responseArray[1];
// Set the data on the form.
document.getElementById("divHeader").innerHTML = strHeader;
document.getElementById("divBody").innerHTML = strBody;
}
});
On the ASP.Net server side, I have:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static object GetTip(String IdTip)
{
int iIdTip = -1;
String[] MyData = new String[2];
// Formulate the respnse.
MyData[0] = "My header";
MyData[1] = "My body";
// Create a JSON object to create the response in the format needed.
JavaScriptSerializer oJss = new JavaScriptSerializer();
// Create the JSON response.
String strResponse = oJss.Serialize(MyData);
return strResponse;
}
I am probably mixing things up, as I am still new to JSON.
UPDATE with error code:
Exception was thrown at line 2, column 10807 in http://localhost:49928/Scripts/js/jquery-1.7.2.min.js
0x800a03f6 - JavaScript runtime error: Invalid character
Stack trace:
parse JSON[jquery-1.7.2.min.js] Line 2
What is my problem?
I modified your ajax call script to :
// Call the server-side to get the data.
$.ajax({
url: "WebForm4.aspx/GetTip",
type: "post",
data: JSON.stringify({ IdTip: "0" }),
dataType: "json",
contentType: 'application/json',
success: function (data) {
// Get the data.
var responseArray = JSON.parse(data.d);
// Extract the header and body components.
var strHeader = responseArray[0];
var strBody = responseArray[1];
// Set the data on the form.
document.getElementById("divHeader").innerHTML = strHeader;
document.getElementById("divBody").innerHTML = strBody;
}
});
Note that I added contentType: 'application/json' and changed
var responseArray = JSON.parse(data.response);
to
var responseArray = JSON.parse(data.d);
This s purely out of guess work. But see if this is what you are getting:-
In your Ajax call, your data type is json and looking at the method you are returning a json string. So you do not need to do JSON.parse(data.response). Instead just see if the below works for you. Also i dont see a response object in your Json, instead it is just an array. So it must be trying to parse undefined
var strHeader = data[0];
var strBody = data[1];

Categories

Resources