Sending and receiving an array to a sql database via JSON - javascript

I put an array in an object which is send to an java webservice (see javascript.js -> sendDataToWebservice()). The webservice proceeds the array (via gson) and saves it as a String in an sql database (see webservice.java -> handleDataFunction()). When I want to receive the array the data is not properly converted back to an array (see javascript.js -> receiveDataFromWebservice()). Instead of an array the data will be converted to an String like this: "["item1", "item2]".
Do I need to parse the array? I think the problem is that somewhere in between there are added the quotation marks and thus the data is recognized as a string and not an array.
Thanks in advance!
javascript.js
var myArray = new Array();
function sendDataToWebservice() {
// Create the JSON to send to the webservice
var jsonData = {
"action": actionName,
"array": myArray
};
// Send the data
$.ajax({
url: "/xaction/",
type: 'POST',
data: JSON.stringify(jsonData),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: true,
success: function (msg) {
// ...
}
});
}
function reveiveDataFromWebservice() {
// Receive the data
jQuery.getJSON("/webservice/getdata", function (returningData) {
if (returningData.success) {
array= returningData.array;
}
});
webservice.java
private void handleDataFunction(inputData) {
// Create a map for the parameters
MapSqlParameterSource namedParameters = new MapSqlParameterSource();
// Create the query string
String query = "my sql query";
// Here I want to retrievethe array as a String to store it in the db
JsonArray jsonArray = currentAntwortFeld.get("array").getAsJsonArray();
// Add the array as an String to the sql parameters
namedParameters.addValue("arraydbfield", jsonArray.toString())
// Execute the sql query
factory.executeUpdate(query, namedParameters);
}

JSON.parse() will turn a string containing an array into an array object.
myArray = JSON.parse(myString)
Can't tell why jQuery isn't already doing that for you though. I thought that was the point of $.getJSON(). But I don't use jQuery, so I don't really know.

For converting from JSON to SQL I implemented as follows:
let jsArray = [1,2,3,4] //Example array in JS
let sqlArray = '{';
jsArray.forEach(element=>sqlArray+=element+',')
sqlArray = sqlArray.substring(0, sqlArray.length-1) + '}'
Now use sqlArray is fit for SQL.

Related

Parsing Json data from asp.net webservice and populating it in asp.net dropdownlist

i am trying to populate an asp.net dropdownlist returned as JSON from my webservice.
WebService
[WebMethod(EnableSession = true)]
public string GetActiveDepositAccountsForLoanAlert(string customerId)
{
var data = BusinessLayer.SMS.SmsSetup.GetActiveDepositAccountsForLoanAlert(customerId.ToLong());
var json = new JavaScriptSerializer().Serialize(data);
return json;
}
The webservice returns
[{"AccountNumber":"NS-0000092"},{"AccountNumber":"6MR-0000002"},{"AccountNumber":"1YFD-0000007"}]
I am calling the data from ajax call and populating it to my dropdownlist.
Ajax call
function GetActiveDepositAccounts(customerrId) {
var customerId = $('#CustomerIdHiddenField').val();
var data = { customerId: $('#CustomerIdHiddenField').val() };
var json_data = JSON.stringify(data);
$.ajax({
type: "POST",
url: "/WebMethods/Misc.asmx/GetActiveDepositAccountsForLoanAlert",
data: json_data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(r) {
var depositRadioList = $("[id*=DepositAccountDropDownList]");
depositRadioList.empty().append('<option selected="selected" value="0">Please select</option>');
for (var i = 0; i < r.d.length; i++) {
depositRadioList.append('<option>' + r.d[i] + '</option>');
}
}
The data gets populated in json.In my dropdown i only want the accountnumber as
NS-0000092.I am getting the whole json in my dropdown.i have searched and seen lots of question with this Json parse thing in here.But couldnt get hold of this.It isnt that i didnt tried,I am newbie,so before marking this as duplicate,please for once have a look at the code.Thank you.
I can't shake the feeling that because your GetActiveDepositAccountsForLoanAlert is returning a string and not an object, r.d is being seen as a string. Try one of 2 things. Either:
Change your method signature to return data type and don't use the JavaScriptSerializer. or,
In your OnSuccess function, add var data = JSON.parse(r.d) and use that variable in your for loop.
Single Object Returned
If by "whole json", you mean you are getting a single {"AccountNumber":"6MR-0000002"} per option -- try outputting the value of the target AccountNumber object (e.g. r.d[i].AccountNumber or r.d[i]["AccountNumber"]).
Modified Function
var depositRadioList = $("[id*=DepositAccountDropDownList]");
depositRadioList.empty().append('<option selected="selected" value="0">Please select</option>');
for (var i = 0; i < r.d.length; i++) {
depositRadioList.append('<option>' + r.d[i].AccountNumber + '</option>');
}
Array of Objects Returned
If the result per option is an entire AccountNumber array of objects, you'll need to loop through your r object until you get to the list of Account Number objects.
Take a look at my Example JS Fiddle. There is probably a cleaner way to do this, but to present the principle, I've laid out nested loops to get you into the list of object values that you need for your <select></select>.
I'm using the JQuery $.each() method, but you can use the for loop. I recommend just using one or the other for consistency. If the data set is really large, for loops have better performance.

Sending Json Array in POST request for JavaScript

I am having trouble in sending a JSON array in an AJAX call. Following is my Code
var company_name = $('input#company_name').val();
var company_localname = $('input#company_localname').val();
var companytype = $('#companytype').val();
if (companytype == 'retailer') {
var bank_name = $('input#bank_name').val();
var account_title = $('input#account_title').val();
var business_nature = $('input#business_nature').val();
var gross_sales = $('input#gross_sales').val();
}
After getting all the values I am storing the data in Json like the following
var jsonArray = [];
jsonArray["company_name"] = company_name;
jsonArray["company_localname "] = company_localname;
if (companytype == 'retailer') {
jsonArray["bank_name"] = bank_name;
jsonArray["account_title"] = account_title;
jsonArray["business_nature"] = business_nature;
jsonArray["gross_sales"] = gross_sales;
}
Now for sending the jsonArray in Ajax call
$.ajax({
url : url,
type : "POST",
dataType : 'json',
contentType : 'application/json; charset=UTF-8',
data : JSON.stringify(jsonArray),
success : function(response) {
//Some Code here
}
});
Please help me sending data. Or tell me if I am making any mistake here. Thank you
In JavaScript / JSON arrays are 0 based indexed data structures. What you are using here is more like a Map:
var jsonArray = [];
jsonArray["company_name"]=company_name ;
In JavaScript you cannot use arrays like this (well you can, but it is probably not what you want). For a data structure like a map that maps strings to objects rather then an index to objects, just use an object.
Or in short: Use var jsonArray = {}; rather than var jsonArray = []; The {} will create an object that you can assign properties to like you did. And JSON.stringify will correctly translate this into a JSON string like this:
{ "property": value, "otherProperty", otherValue }
Do something like this.
$.ajax({
url: url,
type: "POST",
dataType: 'json',
contentType: 'application/json; charset=UTF-8',
data: JSON.parse(JSON.stringify(jsonArray)),
success: function(response) {
//Some Code here
}
});
The JSON.parse() method parses a string as JSON, optionally transforming the value produced by parsing. Read more about JSON.parse() method
The JSON.stringify() method converts a JavaScript value to a JSON string. Read more about JSON.stringify() method
Here simply you can send an array and Parse it in server side.
$.ajax({
url : url,
type : "POST",
dataType : 'json',
data : jsonArray,
success : function(response) {
//Some Code here
}
});

How to parse json object datalist in ajax sucess using javascript

i am trying to parse json datalist in ajax success bt it couldnot work. i have passed object containing list of data using json from controller to view,i help to parse json object in ajax success. i have attached my code below.
//return json object from controller
PurchaseDetails pd = new PurchaseDetails();
foreach (DataRow dr in dt.Rows)
{
pd.serialList.Add(new SerialInfo {
Machine_serial_no = dr[0].ToString(), macAddress = dr[1].ToString(), isMacPresent = _TD1.CheckMac(machineTypes_MTId),brandName=obj.brandName,machineName=obj.machineName,MachineModel=obj.MachineModel,modelId=modelId,machineId=obj.machineId,brandId=obj.brandId});
// pd.macaddressList.Add(new MacAddressInfo { MacAddress = dr[1].ToString() });
}
}
}
return Json(new {pd}, JsonRequestBehavior.AllowGet);
return Json(new {pd}, JsonRequestBehavior.AllowGet);
// my ajax code
$.ajax({
url: "/Import/ImportPurchase",
type: "POST",
data: function () {
var data = new FormData();
data.append("file", jQuery("#file").get(0).files[0]);
data.append("machineTypes_MTId", jQuery('#machineTypes_MTId').val());
data.append("modelId", jQuery('#searchValue').val());
data.append("modelName", jQuery('#searchid').val());
return data;
}(),
dataType:"JSON",
contentType: false,
processData: false,
success: function (data) {
alert(data.Machine_serial_no)
Your controller method is returning
return Json(new { serialObj = pd}, JsonRequestBehavior.AllowGet);
which is an object containing a name serialObj
So in the ajax success call back, you would need to access it using
success: function (data) {
var PurchaseDetails = data.serialObj;
Since PurchaseDetails contains a collection named serialList which is a collection of SerialInfo, then to access the value of the first Machine_serial_no, it would be
var serialNo = data.serialObj.serialList[0].Machine_serial_no;
However it would be easier to just use
return Json(pd, JsonRequestBehavior.AllowGet);
If you then want to access each Machine_serial_no property in the collection, use
success: function (data) {
$.each(data.serialList, function(index, item) {
var serialNo = item.Machine_serial_no;
you can use jQuery.parseJSON() to parse ajax response to JSON.
but seeing from your code, seems the response should already be in JSON because dataType parameter is already set to "JSON".
try this:
remove "()" after the ending bracket of function in "data" parameter.
try to console.log(data) and look at the response from your browser console,
the response might not be a valid json string.
If you are looking for convert js array to JSON then just use JSON.stringify() function. This will convert your JS variable data value to JSON format.
You can more find here.

How to access the serialized data in PHP file in the following scenario?

How to access the serialized data in a PHP file in following situation?
The code and the serialized data is as follows:
$(document).ready(function() { $(document).on('click', '#delete_url', function (e) {
e.preventDefault();
var items = new Array();
$("input:checked:not(#ckbCheckAll)").each(function() {
items.push($(this).val());
});
var str = $("#user_filter").serialize();
$.ajax({
type: "POST",
url: "manage_users.php?op=delete_bulk_users&items="+items,
data: str,
dataType: 'json',
success: function(data) {
//var message = data.success_message;
var redirect_link = data.href;
alert(redirect_link);
window.location.href = redirect_link;
}
});
});
});
The data I'm getting in after serialize in str is as follows:
op=group_filter&page=1&from_date=11%2F10%2F2000&social_login=&to_date=11%2F10%2F2013&login_criteria=all&user_name=&user_state=&user_email_id=&user_city=
Now the PHP file(manage_users.php) is as follows:
/*The code is actually one of the switch casees*/
prepare_request();
$request = empty( $_GET ) ? $_POST : $_GET ;
$op = $request['op'];
switch( $op ) {
case "delete_bulk_users":
print_r($request);/*For printing the received array of values after form submission
Here I'm not getting serialized data */
}
Thanks in advance.
The serialize function is intended to be used to create a query string for a URL from a collection of inputs (or an entire form), and will out of necessity encode characters such as / (which denotes a directory in a URL). There's no way to tell .serialize() to convert to the "proper" format because it already is.
If you're using the result of .serialize() as part of an AJAX request it's fine to do that like so:
$.ajax({
url: 'yourpage.php',
data: str, // the string returned by calling .serialize()
... // other options go here
}).done(function(response) {
// do something with the response
});
Your server should handle decoding those characters when it receives the request and provide the correct values to you.
If you're using it for something else you could try using the native JavaScript decodeURIComponent function to convert those encoded characters back, like so:
str = decodeURIComponent(str);
Note that calling decodeURIComponent and then trying to use it for an AJAX request won't work.
For more information on URI encoding take a read through the MDN entry for encodeURIComponent.

Passing a javascript array to a php page using post method

I want to pass a javascript array to a php page using ajax POST request .How to achieve this.please help..Thanks in advance
Have a look into JSON encoding.
In PHP you can decode it using json_decode, not quite sure how you'll encode it in Javascript but it is possible
http://en.wikipedia.org/wiki/JSON
using jQuery
$.post("test.php", { 'choices[]': ["Jon", "Susan"] });
Edit
if you are creating ajax object and using it then I'll suggest to convert your data in query string send it through ajax object.
like :
var userdetails = [1,2,3,4];
var queryString = "";
for(i=0; i<userdetails.length; i++){
queryString = queryString + 'userdetails[]='+userdetails[i]+'&';
}
connect.send(queryString)
example posting with json
var array = [1,2,3,4,5,6];
$.ajax({
url: "mydomain.com/url",
type: "POST",
dataType: "json",
data: {arrayName: array},
complete: function() {
//called when complete
},
success: function() {
//called when successful
},
error: function() {
//called when there is an error
},
});
Then the json could be parsed server side.
arrays can also be sent using application/x-www-form-urlencoded - this is the default format for submitting.

Categories