posting multiple arrays to .net webservice using JavaScript - javascript

Hello guys I'm struggling posting multiple arrays to a .net web service here is the signature to my web service.
<WebMethod()> _
Public Function Lib_Processor(ByVal w_vendor As String(), _
ByVal w_invoice As String(), _
ByVal w_invdate As String(), _
ByVal w_amount As Decimal(), _
ByVal w_account As String(), _
ByVal w_fund As String(), _
ByVal w_org As String(), _
ByVal w_prog As String(), _
ByVal w_adrsstyp As String(), _
ByVal w_adrss_seq As String(), _
ByVal w_Row As String(), _
ByVal w_bank As String(), _
ByVal w_user As String(), _
ByVal w_addl_info As String()) As List(Of GetErrors)
I'm looping a table and getting all the values into objects then using json.stringfy to properly create the object to send to the service.
like this.
var invoice = JSON.stringify({ w_invoice:w_invoice });
var vendor = JSON.stringify({ w_vendor: w_vendor });
var invdate = JSON.stringify({ w_invdate:w_invdate });
var amount = JSON.stringify({ w_amount:w_amount });
var fund = JSON.stringify({ w_fund:w_fund });
var org = JSON.stringify({ w_org:w_org });
var prog = JSON.stringify({ w_prog: w_prog });
var account = JSON.stringify({ w_account: w_account });
var adrsstyp = JSON.stringify({ w_adrsstyp:w_adrsstyp });
var adrss_seq = JSON.stringify({ w_adrss_seq:w_adrss_seq });
var Row = JSON.stringify({ w_Row:w_Row });
var bank = JSON.stringify({ w_bank:w_bank });
var user = JSON.stringify({ w_user:w_user });
var addl_info = JSON.stringify({ w_addl_info: w_addl_info });
then i makea call to my service to send in the arrays.
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: '{w_vendor:"' + w_vendor + '",w_invoice:"' + w_invoice + '",w_invdate:"'+w_invdate + "}",
//data: "{"+vendor, invoice, invdate, amount,account,fund,org,prog,adrsstyp,adrss_seq,Row,bank,user,addl_info +"}",
// "{"+ vendor+invoice+invdate+amount+account+fund+org+prog+adrsstyp+adrss_seq+Row+bank+user+addl_info+"}"
url: "ServiceApUtils.asmx/Lib_Processor",
dataType: "json",
success: respond,
error: function (e) { $('.result').html("An Error Occured"); }
});
however this fails miserably i can understand why because im simply trying to send many json objects to the 1 service. how can i fix this? I have tried just doing one object like
var thisInvoice = {INVOICE:INVOICE}
and basically
var dto = { 'INVOICE': INVOICE };
var PnJ = JSON.stringify(dto);
but this does not work . how can i properly adjust this object to be send into my service?
any help would be greatly appreciated.

Make sure two things:
Your json string is valid
Json string name matches with property name on pagemethod
In addition I would suggest you to go through below link which explains how to pass complex type to WebMethod.
http://encosia.com/using-complex-types-to-make-calling-services-less-complex/

after hours of frustruation i decided to do things my own way and here is what i came up with. I have an html table which i read from and i needed to use ajax to send the html data to a webservice. i used jquery to read the table data like the following.
/* webservice variables*/
var w_vendor = [];
var w_invoice = [];
var w_invdate = [];
var w_amount = [];
var w_account = [];
var w_fund = [];
var w_org = [];
var w_prog = [];
var w_adrsstyp = [];
var w_adrss_seq = [];
var w_Row = [];
var w_bank = [];
var w_user = [];
var w_addl_info = [];
var w_activity = [];
var w_location = [];
var w_bank = [];
then on submit we simply called these functions.
function GetAllTableRows() {
try{
//var MyInvoice = [];
$('#ADPControlProcessor_GridView1 tbody tr').each(function (index, value) {
var row = GetRow(index)
//MyInvoice.push(row);
});
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: '{' + 'w_vendor:[' + w_vendor + "],w_invoice:[" + w_invoice + "],w_invdate:[" + w_invdate + "]," + "w_amount:[" + w_amount + "],"+
"w_account:[" + w_account + "]," + "w_fund:[" + w_fund + "]," + "w_org:[" + w_org + "]," + "w_prog:[" + w_prog + "]," + "w_adrsstyp:[" + w_adrsstyp + "]," +
"w_adrss_seq:[" + w_adrss_seq + "]," + "w_Row:[" + w_Row + "]," + "w_bank:[" + w_bank + "]," + "w_user:[" + w_user + "]," + "w_addl_info:[" + w_addl_info+"]" + "}",
url: "ServiceApUtils.asmx/Lib_Processor",
dataType: "json",
success: respond,
error: function (e) { $('.result').html("An Error Occured"); }
});
}
catch (err)
{
alert(err)
}
//return MyInvoice;
}
function respond() {
alert('worked!')
}
function GetRow(rowNum)
{
try{
var row = $('#ADPControlProcessor_GridView1 tbody tr').eq(rowNum);
w_vendor.push('"'+ row.find('td:eq(2)').text().trim()+'"');
w_invoice.push('"' + row.find('td:eq(1)').text().trim()+'"' );
w_invdate.push('"' + row.find('td:eq(3)').text().trim() + '"');
w_amount.push('"' + row.find('td:eq(4)').text().trim() + '"');
w_fund.push('"' + row.find('td:eq(5)').text().trim() + '"');
w_org.push('"' + row.find('td:eq(6)').text().trim() + '"');
w_account.push('"' + row.find('td:eq(7)').text().trim() + '"');
w_prog.push('"' + row.find('td:eq(8)').text().trim() + '"');
w_activity.push('"' + row.find('td:eq(8)').text().trim() + '"');
w_location.push('"' + row.find('td:eq(8)').text().trim() + '"');
w_addl_info.push('"' + row.find('td:eq(11)').text().trim() + '"');
w_adrsstyp.push('"' + row.find('td:eq(12)').text().trim() + '"');
w_adrss_seq.push('"' + row.find('td:eq(13)').text().trim() + '"');
w_Row.push('"' + row.find('td:eq(14)').text().trim() + '"');
w_user.push('"' + "MIGUEL83_BANNER" + '"');
w_bank.push('"' + "2" + '"');
}
catch (err)
{
alert (err)
}
//return INVOICE;
}
The function "GetAllTableRows()" simply calls the the rows function to get everysingle row and put the values into the variables. This is code that i actually found on this site.
however i tried to used json stringify but it just would not suite my needs for this particular case if you look at the signature of my service the service expects 12 or 13 string arrays however all the examples i have seen expect you to change your service and create a class and so forth. Well i dont have that ability here so here is the next best thing. how would you do it? you create your own string and thats what i did on the "getRow()" function i concatenated all the strings with double quotes and voila. Then i formatted the string on the data paremeter according to jquery specs and json specs. yes a bit painful but quite useful. In hindsight i could have created a helper function to make format all the strings for me but ill leave that for my future project. hope this helps someone else

Related

update cant change record in mongodb database using c#

this is my c# code
public static void updateSubmit(string id,string fname,string lname,string email,string password,string address)
{
string connectionString = "mongodb://10.10.32.125:27017";
MongoClientSettings settings = MongoClientSettings.FromUrl(new MongoUrl(connectionString));
MongoClient mongoClient = new MongoClient(settings);
var Server = mongoClient.GetDatabase("mongovaibhav");
var collection = Server.GetCollection<employee>("mongov");
ObjectId objectId = ObjectId.Parse(id);
var filter = Builders<employee>.Filter.Eq(s => s._id, objectId);
employee emp = new employee();
emp.fname = fname;
emp.lname = lname;
emp.email = email;
emp.pass = password;
emp.address = address;
collection.ReplaceOneAsync(filter, emp);
}
This is my ajax code with whom i send update request and data also
function updateSubmit()
{
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'Home.aspx/updateSubmit',
data: "{'id':'" + $("#hidden").val()+ "','fname':'" + $("#fname").val() + "','lname':'" + $("#lname").val() + "','email':'" + $("#email").val() + "','password':'" + $("#password").val() + "','address':'" + $("address").val() + "'}",
async: false,
success: function (response) {
alert("You Have SuccessFully Update Data");
},
error: function () {
console.log('there is some error');
}
});
}
Now My Problem is that i get the alert message that you have successfully update record but the record cant change effect in database
i Got the Solution i have Mistake In My "Param" Variable Where I Write Password Insted of "pass" because my employee class contain "pass" property
Thank you every one #souvik #felix
string connectionString = "mongodb://10.10.32.125:27017";
MongoClientSettings settings = MongoClientSettings.FromUrl(new MongoUrl(connectionString));
MongoClient mongoClient = new MongoClient(settings);
var Server = mongoClient.GetDatabase("mongovaibhav");
var collection = Server.GetCollection<employee>("mongov");
ObjectId objectId = ObjectId.Parse(id);
var filter = Builders<employee>.Filter.Eq(s => s._id, objectId);
string param = "{$set: { fname:'" + fname + "',lname:'" + lname + "',email:'" + email + "',pass:'" + password + "',address :'" + address + "' } }";
BsonDocument document = BsonDocument.Parse(param);
collection.UpdateMany(filter, document);

POST nested JSON Body using asp mvc

I am trying to post a nested json body to an api and I tried few things but couldn't work it out. Another thing is the Json values are coming from different models. It is a bit complicated and I am struggling with it, any kind of help will be appreciated.
public Object getfreight()
{
var json = "{" +
"'from': {" +
"'postcode': '3207'" +
"}," +
"'to': {" +
"'postcode': '2001'" +
"}," +
"'items': [" +
"{" +
"'length': 5," +
"'height': 5," +
"'width': 5," +
"'weight': 5," +
"'item_reference' : 'abc xyz'," +
"'features':{" +
"'TRANSIT_COVER': {" +
"'attributes': {" +
"'cover_amount':1000" +
"}" +
"}" +
"}" +
"}" +
"]" +
"}";
string url =
"https://digitalapi.auspost.com.au/postage/parcel/domestic/calculate.json?length=22&to_postcode=3083&from_postcode=3076&weight=2&height=40&width=50&service_code=AUS_PARCEL_REGULAR";
//synchronous client.
var client = new WebClient();
var serializer = new JavaScriptSerializer();
client.Credentials = new NetworkCredential("***", "***");
client.Headers.Add("Content-Type: application/json");
client.Headers.Add("Accept: application/json");
client.Headers.Add("account-number: ***");
var data = serializer.Serialize(json);
var content = client.UploadString(url,json);
var jsonContent = serializer.Deserialize<Object>(content);
return jsonContent;
}
Can't use jQuery to pass your json object to API ?
function Search () {
try {
var req = {
length:"5",
Higet: "10",
item_reference: "",
}
$.ajax({
url: https://digitalapi.auspost.com.au/postage/parcel/domestic,
type: 'POST',
data: req,
dataType: "json",
async: true,
success: function (result) {
},
error: function (e) {
}
});
}
catch (e) {
}
}

Why isn't my code getting the JSON values?

function getResults(){
var text = encodeURIComponent(searchField.val().trim());
$.ajax({
type: "GET",
url: "https://en.wikipedia.org/w/api.php?action=query&prop=extracts&exintro&format=json&titles=" + text,
dataType: "jsonp",
success: function(data){
showResults(data, text);
}
});
}
function showResults(data, text) {
results.show();
var query = "https://en.wikipedia.org/wiki/" + text;
for (var id in data.query.pages) {
var code = "<a href=" + query + " class='results'>" + "<div class='results'>";
code = code + "<strong>" + id.title + "</strong>";
code = code + "<br>";
code = code + id.extract;
code = code + "</div></a>"
$(code).appendTo(results);
}
}
In the showResults function, its showing the id.title and id.extract as undefined. Why is that? What am I doing wrong?
When you do this:
for (var id in data.query.pages)
The, id variable is filled with a property name which is simply a string. If you want to get that value of that property, you have to reference the value of that property as in:
data.query.pages[id]
Or, if that's an object that you then want .title from, then you would need
data.query.pages[id].title
and
data.query.pages[id].extract
That's because when iterating over an object (using for-var-in-object loop), the var (id in this case) is the key, but if you need value, use object[key] syntax. Check the following code
$.ajax({
type: "GET",
url: "https://en.wikipedia.org/w/api.php?action=query&prop=extracts&exintro&format=json&titles=newton",
dataType: "jsonp",
success: function(data) {
for (var id in data.query.pages)
document.write(data.query.pages[id].title);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
In your case, you are using just key=> '321123'. To get value of object use key. To get object data.query.pages[id].
for (var id in wiki = data.query.pages){
wiki[id].title;
wiki[id].extract;
}
This one should work.
function showResults(data, text) {
results.show();
var query = "https://en.wikipedia.org/wiki/" + text;
for (var id in wiki = data.query.pages) {
var code = "<a href=" + query + " class='results'>" + "<div class='results'>";
code = code + "<strong>" + wiki[id].title + "</strong>";
code = code + "<br>";
code = code + wiki[id].extract;
code = code + "</div></a>"
$(code).appendTo(results);
}
}

invoking method using ajax at code behind in asp.net

hey i am making a simple web form its a product detail insertion web page. I am trying to insert using ajax call. without ajax it works .. but $.ajax is not invoking my code behind static method, no idea wat's the issue. here's the code:
$(document).ready(function () {
$("#submit").click(function () {
var cat = document.getElementById('DropDownList1').value;
var nm = document.getElementById('name').value;
var cde = document.getElementById('code').value;
var dt = document.getElementById('dt').value;
var price = document.getElementById('price').value;
var f3 = document.getElementById('ty').innerHTML;
alert("you clicked " + cat + " - " + nm + "-" + cde + "-" + dt +
"-" + price + "-" + f3 + "-");
//////////////uptil here alert gives the right value.
$.ajax({
method: "POST",
contentType: "application/json",
url: "home.aspx/ins",
dataType: "json",
data: "{'Name :' + nm + 'code :' + cde +'category :'+ cat +
'date :'+ dt +'price :'+ pr +'img_name :' + f3}",
//data:"{}",
//async: false,
success: function (response) {
alert("User has been added successfully.");
window.location.reload();
}
});
})
});
//////////////////////////////// here is the code behind method:
[System.Web.Services.WebMethod]
public static void ins(string Name,string code,string category, DateTime date,
int price,string img_name)
{
productclass pc = new productclass();
pc.Pr_name = Name;
pc.Code = code;
pc.Category = category;
pc.Expiry = date;
pc.Price = price;
pc.Pr_image = img_name;
dalinsert di = new dalinsert();
bool flag = di.insert(pc);
}
Correct way to pass data to ajax post via webmethod is like this.
var params = "{'Name' :'" + nm + "', 'code' :'" + cde + "', 'category' :'" + cat + "', 'date' : '" + dt + ", 'price' :'" + pr + "' , 'img_name' :'" + f3 + "' }" // Declare this above $.ajax...
data: params, //Use above in $.ajax... .
I believe the issue is in your data being passed in:
data: "{'Name :' + nm + 'code :' + cde +'category :'+ cat +'date :'+ dt +'price :'+ pr +'img_name :' + f3}"
I see two possible issues there. First, your '+' are being treated as literals there as they are surrounded by double quotes that are never escaped. What you are trying to achieve, I believe, is:
data: "{'Name :'"+ nm +"'code :'"+ cde +"'category :'"+ cat +"'date :'"+ dt +"'price :'"+ pr +"'img_name :'"+ f3 +"}"
However that still has a potential problem as I believe that json will be malformed. The expected syntax of a json string, with string variables at least, is '{"key1":"value1","key2":"value2"}'.
A better way to make sure your right and to save yourself work is to use JSON.stringify to do the work for you.
var temp = {};
temp.Name = nm;
temp.code = cde;
temp.category = cat;
temp.date = dt;
temp.price = pr;
temp.img_name = f3;
var data = JSON.stringify(temp);

Merging JSON api Response using Javascript

I am trying get paged json responses from Topsy (http://code.google.com/p/otterapi/) and am having problems merging the objects. I want to do this in browser as the api rate limit is per ip/user and to low to do things server side.
Here is my code. Is there a better way? Of course there is because this doesn't work. I guess I want to get this working, but also to understand if there is a safer, and/or more efficient way.
The error message I get is ...
TypeError: Result of expression 'window.holdtweetslist.prototype' [undefined] is not an object.
Thanks in advance.
Cheers
Stephen
$("#gettweets").live('click', function(event){
event.preventDefault();
getTweets('stephenbaugh');
});
function getTweets(name) {
var MAX_TWEETS = 500;
var TWEETSPERPAGE = 50;
var BASE = 'http://otter.topsy.com/search.json?type=tweet&perpage=' + TWEETSPERPAGE + '&window=a&nohidden=0&q=#' + name + '&page=1';
var currentpage = 1;
alert(BASE);
$.ajax({
dataType: "json",
url: BASE,
success: function(data) {
window.responcesreceived = 1;
var response=data.response;
alert(response.total);
window.totalweets = response.total;
window.pagestoget = Math.ceil(window.totalweets/window.TWEETSPERPAGE);
window.holdtweetslist = response.list;
window.holdtweetslist.prototype.Merge = (function (ob) {var o = this;var i = 0;for (var z in ob) {if (ob.hasOwnProperty(z)) {o[z] = ob[z];}}return o;});
// alert(data);
;; gotTweets(data);
var loopcounter = 1;
do
{
currentpage = currentpage + 1;
pausecomp(1500);
var BASE = 'http://otter.topsy.com/search.json?type=tweet&perpage=' + TWEETSPERPAGE + '&window=a&nohidden=0&q=#' + name + '&page=' + currentpage;
alert(BASE);
$.ajax({dataType: "json", url: BASE, success: gotTweets(data)});
}
while (currentpage<pagestoget);
}
});
};
function gotTweets(data)
{
window.responcesreceived = window.responcesreceived + 1;
var response = data.response;
alert(response.total);
window.holdtweetslist.Merge(response.list);
window.tweetsfound = window.tweetsfound + response.total;
if (window.responcesreceived == window.pagestoget) {
// sendforprocessingsendtweetlist();
alert(window.tweetsfound);
}
}
You are calling Merge as an static method, but declared it as an "instance" method (for the prototype reserved word).
Remove prototype from Merge declaration, so you'll have:
window.holdtweetslist.Merge = (function(ob)...
This will fix the javascript error.
This is Vipul from Topsy. Would you share the literal JSON you are receiving? I want to ensure you are not receiving a broken response.
THanks to Edgar and Vipul for there help. Unfortunately they were able to answer my questions. I have managed to work out that the issue was a combination of jquery not parsing the json properly and needing to use jsonp with topsy.
Here is a little test I created that works.
Create a doc with this object on it ....
RUN TEST
You will need JQUERY
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
And put the following in a script too. The is cycle through the required number of tweets from Topsy.
Thanks again everyone.
$("#gettweets").live('click', function(event){
event.preventDefault();
getTweets('stephenbaugh');
});
var MAX_TWEETS = 500;
var TWEETSPERPAGE = 50;
var BASE = 'http://otter.topsy.com/search.json';
var currentpage;
var responcesreceived;
var totalweets;
var pagestoget;
var totalweets;
var TWEETSPERPAGE;
var holdtweetslist = [];
var requestssent;
var responcesreceived;
var tweetsfound;
var nametoget;
function getTweets(name) {
nametoget=name;
currentpage = 1;
responcesreceived = 0;
pagestoget = 0;
var BASE = 'http://otter.topsy.com/search.js?type=tweet&perpage=' + TWEETSPERPAGE + '&window=a&nohidden=0&q=#' + nametoget + '&page=1';
$('#gettweets').html(BASE);
$.ajax({url: BASE,
dataType: 'jsonp',
success : function(data) {
getalltweets(data);
}
});
};
function getalltweets(data) {
totalweets = data.response.total;
$('#gettweets').append('<p>'+"total tweets " + totalweets+'</p>');
$('#gettweets').append('<p>'+"max tweets " + MAX_TWEETS+'</p>');
if (MAX_TWEETS < totalweets) {
totalweets = 500
}
$('#gettweets').append('<p>'+"new total tweets " + totalweets+'</p>');
gotTweets(data);
pagestoget = Math.ceil(totalweets/TWEETSPERPAGE);
var getpagesint = self.setInterval(function() {
currentpage = ++currentpage;
var BASE = 'http://otter.topsy.com/search.js?type=tweet&perpage=' + TWEETSPERPAGE + '&window=a&nohidden=0&q=#' + nametoget + '&page=' + currentpage;
$.ajax({url: BASE,
dataType: 'jsonp',
success : function(data) {
gotTweets(data);
}
});
if (currentpage == pagestoget) {
$('#gettweets').append('<p>'+"finished sending " + currentpage+ ' of ' + pagestoget + '</p>');
clearInterval(getpagesint);
};
}, 2000);
};
function gotTweets(data)
{
responcesreceived = responcesreceived + 1;
holdlist = data.response.list;
for (x in holdlist)
{
holdtweetslist.push(holdlist[x]);
}
// var family = parents.concat(children);
$('#gettweets').append('<p>receipt # ' + responcesreceived+' - is page : ' +data.response.page+ ' array length = ' + holdtweetslist.length +'</p>');
// holdtweetslist.Merge(response.list);
tweetsfound = tweetsfound + data.response.total;
if (responcesreceived == pagestoget) {
// sendforprocessingsendtweetlist();
$('#gettweets').append('<p>'+"finished receiving " + responcesreceived + ' of ' + pagestoget + '</p>');
}
}

Categories

Resources