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);
Related
I have recently came across this JS code for Zapier by #ReganStarr to create a "like tweet" action for any given tweet_id. I'm no expert but it sure looks fine (no error messages either), nevertheless, for some reason it doesn't work!
Would appreciate a lot if an experienced Zapier + JS eye can identify why isn't it working.
here is the code:
var twitterApplicationConsumerKey = 'MyTwitterConsumerKey';
var twitterApplicationConsumerSecret = 'MyTwitterConsumerSecret';
var twitterApplicationAccessToken = 'MyTwitterAccessToken';
var twitterApplicationAccessTokenSecret = 'MyTwitterTokenSecret';
// That's it. No need to edit anything below.
function b64_hmac_sha1(k,d,_p,_z){
if(!_p){_p='=';}if(!_z){_z=8;}function _f(t,b,c,d){if(t<20){return(b&c)|((~b)&d);}if(t<40){return b^c^d;}if(t<60){return(b&c)|(b&d)|(c&d);}return b^c^d;}function _k(t){return(t<20)?1518500249:(t<40)?1859775393:(t<60)?-1894007588:-899497514;}function _s(x,y){var l=(x&0xFFFF)+(y&0xFFFF),m=(x>>16)+(y>>16)+(l>>16);return(m<<16)|(l&0xFFFF);}function _r(n,c){return(n<<c)|(n>>>(32-c));}function _c(x,l){x[l>>5]|=0x80<<(24-l%32);x[((l+64>>9)<<4)+15]=l;var w=[80],a=1732584193,b=-271733879,c=-1732584194,d=271733878,e=-1009589776;for(var i=0;i<x.length;i+=16){var o=a,p=b,q=c,r=d,s=e;for(var j=0;j<80;j++){if(j<16){w[j]=x[i+j];}else{w[j]=_r(w[j-3]^w[j-8]^w[j-14]^w[j-16],1);}var t=_s(_s(_r(a,5),_f(j,b,c,d)),_s(_s(e,w[j]),_k(j)));e=d;d=c;c=_r(b,30);b=a;a=t;}a=_s(a,o);b=_s(b,p);c=_s(c,q);d=_s(d,r);e=_s(e,s);}return[a,b,c,d,e];}function _b(s){var b=[],m=(1<<_z)-1;for(var i=0;i<s.length*_z;i+=_z){b[i>>5]|=(s.charCodeAt(i/8)&m)<<(32-_z-i%32);}return b;}function _h(k,d){var b=_b(k);if(b.length>16){b=_c(b,k.length*_z);}var p=[16],o=[16];for(var i=0;i<16;i++){p[i]=b[i]^0x36363636;o[i]=b[i]^0x5C5C5C5C;}var h=_c(p.concat(_b(d)),512+d.length*_z);return _c(o.concat(h),512+160);}function _n(b){var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s='';for(var i=0;i<b.length*4;i+=3){var r=(((b[i>>2]>>8*(3-i%4))&0xFF)<<16)|(((b[i+1>>2]>>8*(3-(i+1)%4))&0xFF)<<8)|((b[i+2>>2]>>8*(3-(i+2)%4))&0xFF);for(var j=0;j<4;j++){if(i*8+j*6>b.length*32){s+=_p;}else{s+=t.charAt((r>>6*(3-j))&0x3F);}}}return s;}function _x(k,d){return _n(_h(k,d));}return _x(k,d);
}
var tweetId = input.tweet_id;
//create nonce
function generateRandomString(desiredLengthOfRandomString) {
var result = '';
var possibleCharactersForRandomString = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < desiredLengthOfRandomString; i++ )
result += possibleCharactersForRandomString.charAt(Math.floor(Math.random() * possibleCharactersForRandomString.length));
return result;
}
var randomString = generateRandomString(32);
var nonce = new Buffer(randomString).toString('base64');
//create timestamp
var timestamp = Math.floor(new Date() / 1000);
//create the signature
var signatureParameterString = 'id=' + tweetId + '&oauth_consumer_key=' + twitterApplicationConsumerKey + '&oauth_nonce=' + encodeURIComponent(nonce) + '&oauth_signature_method=HMAC-SHA1&oauth_timestamp=' + timestamp + '&oauth_token=' + twitterApplicationAccessToken + '&oauth_version=1.0';
var signatureBaseString = 'POST&https%3A%2F%2Fapi.twitter.com%2F1.1%2Ffavorites%2Fcreate.json&' + encodeURIComponent(signatureParameterString);
var signingKey = encodeURIComponent(twitterApplicationConsumerSecret) + '&' + encodeURIComponent(twitterApplicationAccessTokenSecret);
var signature = b64_hmac_sha1(signingKey, signatureBaseString);
var apiUrl = 'https://api.twitter.com/1.1/favorites/create.json?id=' + tweetId;
var oauthString = 'OAuth oauth_consumer_key="' + twitterApplicationConsumerKey + '", oauth_nonce="' + encodeURIComponent(nonce) + '", oauth_signature="' + encodeURIComponent(signature) + '", oauth_signature_method="HMAC-SHA1", oauth_timestamp="' + timestamp + '", oauth_token="' + twitterApplicationAccessToken + '", oauth_version="1.0"';
fetch(apiUrl, {
method: 'POST',
headers: {
'Authorization': oauthString
}
})
.then(function(res) {
return res.json();
})
.then(function(body) {
var output = body;
callback(null, output);
})
.catch(callback);
Thanks :-)
I just tried the code you posted and it worked for me.
You might double-check that you have your Access Levels set to "read and write" for your app at https://apps.twitter.com/ so that the 4 variables you include at the top of your code have the correct permissions.
And also make sure that you pass in tweet_id in the Input Data of the Zapier code step. (screenshot)
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) {
}
}
I've written some scripts to convert the pagination (20 photos per ajax request) from instagram json feeds to csv for easily storing the photo urls in our database. Our CMS is automatically able to convert CSV files into SQl files either by replacing the table or by appending to it. The problem is it will only work if ALL of the columns are the same.
It's close to totally working but I can't import my generated csvs because they keep getting an empty column where it should be line breaking to a new row because the final CSV output contains a comma + line break when it should only be returning the line break (i.e. without a trailing comma).
Encoding is UTF-8 and line breaks are being added using "\n". I've tried console logging just about every step of the process and it seems that there that
Here's a picture of one of the CSVs I am generating: http://screencast.com/t/dZfqN08A
Below is all the relevant code:
First I'm using ajax with a jsonp callback to load instagram photos based on a hashtag.
Photos are loaded like this:
function loadNext(nextUrl) {
$.ajax({
url: url,
cache: false,
type: 'POST',
dataType: "jsonp",
success: function(object) {
console.log('loadmore');
if (object) {
console.log(object);
$('.loadmore').fadeOut(500);
// chargement photos gallerie
$.each( object.data, function(home, photo) {
photo = '<div class="photo photo-load">' +
'<img class="pull-me" src="' + photo.images.low_resolution.url + '" height="380px" width="380px" alt="photo">' +
'<div class="dot"></div>' +
'<div class="share" >' +
'<!-- AddThis Button BEGIN -->' +
'<div class="addthis_toolbox addthis_default_style addthis_16x16_style">' +
'<a class="addthis_button_twitter"></a>' +
'<a class="addthis_button_facebook"></a>' +
'</div>' +
'<!-- AddThis Button END -->' +
'</div>' +
'<div class="text-photo">' +
'<div class="svg line w-line"></div>' +
'<h4 class="left">'+ photo.user.username + '</h4>' +
'<h4 class="right share-photo">PARTAGE</h4>' +
'</div>' +
'<div class="vote w-path-hover">' +
'<div class="fb-like" data-href="http://dev.kngfu.com/maurice/" data-layout="box_count" data-action="like" data-show-faces="false" data-share="false"></div>' +
'<div class="insta-like">' +
'<div class="count-box">' +
'<p>'+ photo.likes.count + '</p>' +
'</div>' +
'<a class="insta-button" title="Pour appuyer votre proposition préférée, rendez-vous sur Instagram." href="http://instagram.com/" ><i class="fa fa-instagram"></i>J aime</a>' +
'</div> ' +
'<div class="w-path"></div>' +
'<div class="base-cross"></div>' +
'<h4 class="vote-button">VOTE</h4>' +
'</div>' +
'</div>';
$(photo).appendTo( $( ".gallery" ) );
});
url = object.pagination.next_url;
console.log(url);
} else {
console.log("error");
}
} // end success func.
});
}
Then in a separate ajax call I can convert the same json feed to a csv file using this function (this function also calls a couple other functions so the dependent functions are included below the ajax call):
function convertJSON (nextUrl) {
$.ajax({
url: url,
cache: false,
type: 'POST',
dataType: "jsonp",
success: function(object) {
if (object) {
console.log(object);
var fromJSON = new Array();
i = 0;
$.each( object.data, function(home, photo) {
i++;
var photopath = photo.images.low_resolution.url;
var postID = photo.id;
var userID = photo.user.id;
var user = photo.user.username;
// watch out for those wild fullnames in instagram json
var fullname = photo.user.full_name;
fullname = fullname.replace(/[^a-z0-9]+|\s+/gmi, " ");
//console.log(fullname);
var likes = photo.likes.count;
var winner = 0;
var winnerplace = " ";
var campaign = "maurice1";
var timestamp = photo.created_time;
// easydate field formatting
var date = new Date();
date.setSeconds( timestamp );
var photodeleted = 0;
// add new rows to csv
var linebreak = "\n";
var arrayFromJSON = new Array( linebreak+photopath,
postID,
userID,
user,
fullname,
likes,
winner,
winnerplace,
campaign,
timestamp,
date,
photodeleted );
fromJSON[i] = arrayFromJSON.join();
});
//url = object.pagination.next_url;
//console.log(url);
//console.log( fromJSON );
makeCSV( fromJSON );
} else {
console.log("error");
}
} // end success func.
});
}
// json to csv converter
function makeCSV (JSONData) {
//console.log("makeCSV() function was started");
var data = encodeURIComponent(JSONData);
var currentTime = new Date().getTime();
var date = getDate( currentTime );
//console.log(JSONData);
var fileName = date;
var uri = "data:text/csv;charset=utf-8," // sets mime/data type
+ "photopath," // now 12 strings which are the CSV's column titles
+ "postid,"
+ "userid,"
+ "username,"
+ "fullname,"
+ "likes,"
+ "winner,"
+ "winnerplace,"
+ "campaign,"
+ "creationdate,"
+ "easydate,"
+ "photodeleted"
+ data; // finally append our URI encoded data
console.log(uri);
// generate a temp <a /> tag that will auto start our download when the function is called
var link = document.createElement("a");
link.id = new Date().getTime();
link.href = uri;
// link visibility hidden
link.style = "visibility:hidden";
link.download = fileName + ".csv";
// append anchor tag and click
$("div#hidden").append(link);
link.click();
//document.body.removeChild(link);
}
// this function just makes human readable dates for CSV filename and id of our link tag
function getDate() {
var date = new Date();
//zero-pad a single zero if needed
var zp = function (val){
return (val <= 9 ? '0' + val : '' + val);
}
//zero-pad up to two zeroes if needed
var zp2 = function(val){
return val <= 99? (val <=9? '00' + val : '0' + val) : ('' + val ) ;
}
var d = date.getDate();
var m = date.getMonth() + 1;
var y = date.getFullYear();
var h = date.getHours();
var min = date.getMinutes();
var s = date.getSeconds();
var ms = date.getMilliseconds();
return '' + y + '-' + zp(m) + '-' + zp(d) + ' ' + zp(h) + 'h' + zp(min) + 'm' + zp(s) + 's';
}
From all the console logging I've done, I can definitely assure you that I'm getting no trailing comma until the final step where the json array data gets URI encoded.
Since this extra column is also included in the header row I'm wondering if it has to do with this line?
var uri = "data:text/csv;charset=utf-8," // sets mime/data type
I've also tried ISO-8859-1 encoding but I get the same result.
Does anyone know why this is happening? Any help would be appreciated
Your passing an array of lines to encodeURIComponent. That will stringify the array, joining it with a comma - which you don't want.
What you should do is
var arrayFromJSON = new Array( photopath,
// remove linebreak here ^
postID,
userID,
user,
fullname,
likes,
winner,
winnerplace,
campaign,
timestamp,
date,
photodeleted );
fromJSON[i] = arrayFromJSON.join(",");
// make comma explicit: ^^^
…
makeCSV( fromJSON );
…
var data = encodeURIComponent(JSONData.join("\n"));
// join the lines by a linebreak: ^^^^
…
var uri = "data:text/csv;charset=utf-8," // sets mime/data type
+ "photopath," // now 12 strings which are the CSV's column titles
+ "postid,"
+ "userid,"
+ "username,"
+ "fullname,"
+ "likes,"
+ "winner,"
+ "winnerplace,"
+ "campaign,"
+ "creationdate,"
+ "easydate,"
+ "photodeleted"
+ "\n"
// ^^^^^^ add linebreak
+ data; // finally append our URI encoded data
I am trying to access hourly info from a weather API.
The problem is its not quite working for me, and I am not 100% sure of how to gain access to the information.
This is the site I am working with, and the page on the hourly info.
http://www.wunderground.com/weather/api/d/docs?d=data/hourly&MR=1
I have a strong feeling it has to do with the way the access to variables...
This is my code:
<script>
jQuery(document).ready(function($) {
$.ajax({
url: "http://api.wunderground.com/api/6368023a57d122c7/geolookup/conditions/q/DominicanRepublic/Barahona.json",
dataType : "jsonp",
success : function(parsed_json) {
//get the hourly info -- cant get hourly to work...
var month = parsed_json['hourly_forecast']['FCTTIME']['mon_padded'];
var day = parsed_json['hourly_forecast']['FCTTIME']['mday_padded'];
var year = parsed_json['hourly_forecast']['FCTTIME']['year'];
var time = parsed_json['hourly_forecast']['FCTTIME']['civil'];
var updated = month + "/" + day + "/" + year + " " + time;
var weather = parsed_json['hourly_forecast']['condition'];
var temp = parsed_json['hourly_forecast']['temp']['metric'];
var humid = parsed_json['hourly_forecast']['humidity'];
var wind_direction = parsed_json['hourly_forecast']['wdir']['dir'];
var wind_speed = parsed_json['hourly_forecast']['wspd']['metric'];
var wind_string = wind_direction + " " + wind_speed + " Km/h";
document.getElementById("weather").innerHTML = weather;
document.getElementById("temp").innerHTML = temp;
document.getElementById("hum").innerHTML = humid;
document.getElementById("wind").innerHTML = wind_string;
}
});
});
</script>
If you open the JSON file from that URL you will see that it does not contain "hourly_forecast" or "FCTTIME".
EDIT:
Open up the JSON file that you are downloading and look at what fields it is sending back to you. JQuery already does the hard part and parses it into an object model. Also, the javascript debuggers in Chrome is great at showing you the JSON object model. You can just set a breakpoint at the beginning of the "success" function and use the "Local Variables" window to explore the JSON object.
Here's your code after I updated it to use the correct field names from the JSON file...
<script>
jQuery(document).ready(function ($) {
$.ajax({
url: "http://api.wunderground.com/api/6368023a57d122c7/geolookup/conditions/q/DominicanRepublic/Barahona.json",
dataType: "jsonp",
success: function (parsed_json) {
var current_observation = parsed_json.current_observation;
var lastUpdated = current_observation.observation_time;
var weather = current_observation.weather;
var temp = current_observation.temp_c;
var humid = current_observation.relative_humidity;
var wind_direction = current_observation.wind_dir;
var wind_speed = current_observation.wind_kph;
var wind_string = wind_direction + " " + wind_speed + " Km/h";
alert("Weather: " + weather + "\n"
+ "Temp: " + temp + "\n"
+ "Humidity: " + humid + "\n"
+ "Wind: " + wind_string + "\n"
+ lastUpdated
);
}
});
});
</script>
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