How to convert variables into json? - javascript

I want to send json data to ajax but how do you convert variables into json or convert an array to json?
$(".confirm_order").click(function(event) {
event.preventDefault();
var street = $("#street").val();
var location = $("#location").val();
var number = $("#number").val();
var f = ???
$.ajax({
type: 'post',
url: "/orders",
dataType: "json",
data: f,
success: function (l) {
alert("Done");
}
});
});

If you really want to convert the data into JSON, you have to create an object or array and use JSON.stringify (available in newer browser and can be loaded form here):
var f = JSON.stringify({street: street, location: location, number: number});
but you cannot just set the data attribute to f then. You have to assign it to another variable:
data: {data: f}
This will produce the POST parameters like so:
data={"number":"value of number","location:...}
However, there is not reason to create JSON here. I would sent the values as normal post parameters. For that you just create an object like above and assign it to data:
data: {street: street, location: location, number: number}
This will create the POST parameters:
street=valueofstreet&location=valueoflocation&...
This would be easier as you don't have to parse the JSON at the server side.

If you want to send a JSON formatted request to the server you could specify the proper content type for this request and then use the JSON.stringify method:
var street = $('#street').val();
var location = $('#location').val();
var number = $('#number').val();
$.ajax({
type: 'post',
url: '/orders',
dataType: 'json',
data: JSON.stringify({ street: street, location: location, number: number }),
contentType: 'application/json; charset=utf-8',
success: function (l) {
alert("Done");
}
});
This will send the following in the POST body:
{ street: 'foo', location: 'bar', number: 'baz' }
Obviously the server side script you are sending this AJAX to need to be capable of handling and parsing JSON strings.

var f = {}
f['street'] = $("#street").val();
f['location'] = $("#location").val();
f['number'] = $("#number").val();

var f = {
"street": street,
"location": location,
"number": number
};

Use JSON.stringify from json2.js
Don't forget to specify contentType: 'application/json' in your config object.

try this. values will be replaced respectively
{street : street,location : location, number : number}

Related

Parse return value from $ajax call in JavaScript from MVC Controller

I'm using VS2022 with C# and I'm trying to use an $ajax get method in my JavaScript function. I'm sending a parameter and returning a string[] list but when I receive the return I use JSON.stringify but when I try to use JSON.Parse it fails. The Javascript code is
$.ajax({
type: "GET",
url: '/Home/GetCategories/',
contentType: 'application/json',
datatype: 'json',
data: { ctgData: JSON.stringify(relvalue)}
}).done(function(result) {
let userObj = JSON.stringify(result);
let resultList = JSON.parse(userObj);
});
The code in the controller which returns the list is simple at the moment until I get the return working
[HttpGet]
public ActionResult GetCategories(string ctgData)
{
string[] categoryList = { "Food & Drink", "Sport & Fitness", "Education", "Housework", "Fiction", "Horror Books", "Fantasy", "Magic" };
return Json(new { data = categoryList });
}
The value in result is
{"data":["Food & Drink","Sport & Fitness","Education","Housework","Fiction","Horror Books","Fantasy","Magic"]}
I've tried a number of different ways in Parse but it always fails, can you tell me what I'm missing to get my resultList to contain the string array.
You don' t need to parse anything. It is already java script object
$.ajax({
type: "GET",
url: '/Home/GetCategories/',
contentType: 'application/json',
datatype: 'json',
data: { ctgData: JSON.stringify(relvalue)}
sucess: function(result) {
let data=result.data; // data = ["Food & Drink","Sport & Fitness",..]
}
});
use this:
JSON.parse(JSON.stringify(data))
const data = {"data":["Food & Drink","Sport & Fitness","Education","Housework","Fiction","Horror Books","Fantasy","Magic"]}
const resultJSON = JSON.parse(JSON.stringify(data))
console.log("json >>>", resultJSON)

Can not get value from JSON object

I'm having trouble getting the data value from JSON object. Here is my code:
var ab_id = $( "#ab_id" ).val();
$.ajax({
type: 'GET',
contentType: 'application/json',
url: 'edit_account.php',
data: {ab_id:ab_id, u_id:u_id},
success: function(data)
{
alert(data.ab_name);
},
});
When I do alert(data), I got the actual data like this:
{
"ab_id":"7",
"ab_name":"Lily's Storage Address",
"ab_ship_name":"LIly C\/O SELF STORAGE",
"ab_addr_1":"C\/O Lily",
"ab_addr_2":"16 PIUMA AVENUE, UNIT #2",
"ab_city":"CERI",
"ab_state":"CA",
"ab_postal":"90700",
"ab_phone":null,
"ab_default":"0",
"ab_is_storage":"1"
}
However, when I retrieve the data value by using data.ab_name, it returns undefined.
Am I missing something here?
Use bracket notation
alert(data['ab_name']);
for reference https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors
Parse your string to a object
data = JSON.parse(data);
alert(data.ab_name);

I need to serialize an object to JSON. I'm using jQuery. Is there a "standard" way to do this?

I need to serialize an object to JSON. I'm using jQuery. Is there a "standard" way to do this?
My specific situation: I have an array defined as shown below:
var countries = new Array();
countries[0] = 'ga';
countries[1] = 'cd';
...
and I need to turn this into a string to pass to $.ajax() like this:
$.ajax({
type: "POST",
url: "Concessions.aspx/GetConcessions",
data: "{'countries':['ga','cd']}",
...
You can use JSON.stringify(countries);
var c = {
countries: countries
}
$.ajax({
type: "POST",
url: "Concessions.aspx/GetConcessions",
data: JSON.stringify(c),
contentType: "application/json"
...
Note that you will want to specify contentType; otherwise, URI-encoding is assumed.
You can use JSON.stringify() to turn any object in to a JSON string:
var countries = new Array();
countries[0] = 'ga';
countries[1] = 'cd';
var json = JSON.stringify({ countries: countries}); // = '{"countries":["ga","cd"]}'
// or more simply:
var countries = [ 'ga', 'cd' ];
var json = JSON.stringify({ countries: countries}); // = '{"countries":["ga","cd"]}'
However, you should note that it's better practice to provide the data property of $.ajax with an object as jQuery will then create the JSON for you and at the same time escape any invalid characters and do any required encoding. Try this:
$.ajax({
type: "POST",
url: "Concessions.aspx/GetConcessions",
data: {
'countries': countries
}
});
you can use JSON.parse() to convert object to json
like this
countries = JSON.parse(countries);
object is convert in json and store in countries variable

.serialize() an array of variables in Javascript

I have a list of variables available to me and I want to send it via $.ajax post. What format would I have to keep these in to use the function .serialize? I keep getting this error:
Object 'blank' has no method 'serialize'
I've tried to make them an array and I've tried jQuery.param(). I have a feeling this is simple but I can't seem to get it. Thanks!
var $data = jQuery.makeArray(attachmentId = attachmentID, action = 'rename', oldName = filename, newName, bucketName, oldFolderName, newFolderName, projectId = PID, businessId = BID);
var serializedData = $data.serializeArray();
//alert(theurl);
$.ajax({ type: "post", url: theurl, data: serializedData, dataType: 'json', success: reCreateTree });
.serialize is for form elements:
Encode a set of form elements as a string for submission.
The $.ajax documentation says for the data option:
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
So all you need to do is passing an object. For example:
$.ajax({
type: "post",
url: theurl,
data: { // <-- just pass an object
attachmentId: attachmentID,
action: 'rename',
// ...
},
dataType: 'json',
success: reCreateTree
});
It seems you're used to the PHP style of array's (associated arrays). In Javascript, objects are basically the same thing (though can be MUCH more complicated).
So if you are trying to create an array like this in php it would be
$array = array(
"foo" => "bar",
"bar" => "foo",
);
in Javascript using an object instead of an array it would be
var arr = {
foo: "bar",
bar: "foo"
}

JQuery $.ajax() post - data in a java servlet

I want to send data to a java servlet for processing. The data will have a variable length and be in key/value pairs:
{ A1984 : 1, A9873 : 5, A1674 : 2, A8724 : 1, A3574 : 3, A1165 : 5 }
The data doesn't need to be formated this way, it is just how I have it now.
var saveData = $.ajax({
type: "POST",
url: "someaction.do?action=saveData",
data: myDataVar.toString(),
dataType: "text",
success: function(resultData){
alert("Save Complete");
}
});
saveData.error(function() { alert("Something went wrong"); });
The $.ajax() function works fine as I do get an alert for "Save Complete". My dilemna is on the servlet. How do I retrieve the data? I tried to use a HashMap like this...
HashMap hm = new HashMap();
hm.putAll(request.getParameterMap());
...but hm turns out to be null which I am guessing means the .getParameterMap() isn't finding the key/value pairs. Where am I going wrong or what am I missing?
You don't want a string, you really want a JS map of key value pairs. E.g., change:
data: myDataVar.toString(),
with:
var myKeyVals = { A1984 : 1, A9873 : 5, A1674 : 2, A8724 : 1, A3574 : 3, A1165 : 5 }
var saveData = $.ajax({
type: 'POST',
url: "someaction.do?action=saveData",
data: myKeyVals,
dataType: "text",
success: function(resultData) { alert("Save Complete") }
});
saveData.error(function() { alert("Something went wrong"); });
jQuery understands key value pairs like that, it does NOT understand a big string. It passes it simply as a string.
UPDATE: Code fixed.
Simple method to sending data using java script and ajex call.
First right your form like this
<form id="frm_details" method="post" name="frm_details">
<input id="email" name="email" placeholder="Your Email id" type="text" />
<button class="subscribe-box__btn" type="submit">Need Assistance</button>
</form>
javascript logic target on form id #frm_details after sumbit
$(function(){
$("#frm_details").on("submit", function(event) {
event.preventDefault();
var formData = {
'email': $('input[name=email]').val() //for get email
};
console.log(formData);
$.ajax({
url: "/tsmisc/api/subscribe-newsletter",
type: "post",
data: formData,
success: function(d) {
alert(d);
}
});
});
})
General
Request URL:https://test.abc
Request Method:POST
Status Code:200
Remote Address:13.76.33.57:443
From Data
email:abc#invalid.ts
you can use ajax post as :
$.ajax({
url: "url",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ name: 'value1', email: 'value2' }),
success: function (result) {
// when call is sucessfull
},
error: function (err) {
// check the err for error details
}
}); // ajax call closing
For the time being I am going a different route than I previous stated. I changed the way I am formatting the data to:
&A2168=1&A1837=5&A8472=1&A1987=2
On the server side I am using getParameterNames() to place all the keys into an Enumerator and then iterating over the Enumerator and placing the keys and values into a HashMap. It looks something like this:
Enumeration keys = request.getParameterNames();
HashMap map = new HashMap();
String key = null;
while(keys.hasMoreElements()){
key = keys.nextElement().toString();
map.put(key, request.getParameter(key));
}
To get the value from the servlet from POST command, you can follow the approach as explained on this post by using request.getParameter(key) format which will return the value you want.

Categories

Resources