update cant change record in mongodb database using c# - javascript

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);

Related

web application send form two times

My web app works fine until i press the <button id="button" class="btn btn-primary btn-lg" onclick="sendForm()" value="GENERA XML">GENERA XML</button>
when i press it, the web app crash, i've check the debugger it seems like the function post is called two times, the first time the function works perfectly, the second time it runs it make my application crash.
this is the form:
<form class="container broadcast-form" action="/form" enctype="multipart/form-data" method="post">
this is my client side js:
function sendForm() {
const Form = document.querySelector('.broadcast-form')
let formSend = new FormData();
const cliente = Form.querySelector('#clienti').options[clienti.selectedIndex].text
formSend.append('cliente', cliente);
$.ajax({
url: '/form',
method: "POST",
dataType: 'json',
data: formSend,
processData: false,
contentType: false,
success: function(result){
console.log(result);
},
error: function(er){
console.log(er);
}
});
}
and this is my server side:
app.post('/form', (req, res) => {
con.query(('SELECT * FROM Tab_Clienti WHERE Cliente = "' + cliente +'"'), (err, QCliente, fields) =>{
if (err) console.log(err)
else{...}
})
})
For obvious reasons i've reduced the code with only the essential.
How do I let the application send the form just one time?
This is the missing part:
const cliente = Form.querySelector('#clienti').options[clienti.selectedIndex].text
const emittente = Form.querySelector('#emittenti').options[emittenti.selectedIndex].text
const inputFile = Form.querySelector('#path').value.replace(/.*[\/\\]/, '')
const dataT = Form.querySelector('#date').value
const oraTrasmissione = Form.querySelector('#timeTransmission').value
const sottotitolo = Form.querySelector('#sottotitolo').value
const titoloTrasmissione = Form.querySelector('#titoloTrasmissione').value
const presentatore = Form.querySelector('#presentatore').value
const sommario = Form.querySelector('#sommario').value
const keyword = Form.querySelector('#keyword').value
const currentDate = new Date().toLocaleDateString()
const currentTime = new Date().toLocaleTimeString();
const durataTrasmissione = Math.floor(Form.querySelector('#preview').duration);
const fileVideo = Form.querySelector('#preview').src
formSend.append('cliente', cliente);
formSend.append("inputFile",Form.querySelector('#path').value.replace(/.*[\/\\]/, ''));
formSend.append('emittente', emittente);
formSend.append('sottotitolo',sottotitolo);
formSend.append('dataT', dataT);
formSend.append('currentDate', currentDate);
formSend.append('currentTime', currentTime);
formSend.append('oraTrasmissione', oraTrasmissione);
formSend.append('durataTrasmissione', durataTrasmissione);
formSend.append('titoloTrasmissione', titoloTrasmissione);
formSend.append('presentatore', presentatore);
formSend.append('sommario', sommario);
formSend.append('keyword', keyword);
formSend.append('fileVideo', Form.querySelector('#preview').src);
and server side:
app.post('/form', upload.single('fileVideo'),(req, res) => {
var date = new Date(),
blockid = (date.toJSON().replace(/[\-T:.Z]/g, ''));
cliente = req.body.cliente
inputFile = req.body.inputFile
dataT = req.body.dataT
currentDate = req.body.currentDate
currentTime = req.body.currentTime
oraTrasmissione = req.body.oraTrasmissione
durataTrasmissione = req.body.durataTrasmissione
emittente = req.body.emittente
sottotitolo = req.body.sottotitolo
titoloTrasmissione = req.body.titoloTrasmissione
presentatore = req.body.presentatore
sommario = req.body.sommario
keyword = req.body.keyword
fileVideo = req.body.fileVideo
blockdate = JSON.stringify(date.getFullYear()) + "-" + JSON.stringify(date.getMonth()+1) + "-" + JSON.stringify(date.getDate()) + " " + JSON.stringify(date.getHours()) + ":" + JSON.stringify(date.getMinutes()) + ":" + JSON.stringify(date.getSeconds())
con.query(('INSERT INTO movedb.Tab_Invii (Data_Invio, Orario_Invio, Nome_File_Inviato, Cliente, Emittente, Orario_trasmissione, Durata_trasmissione, Nome_trasmissione, Titolo_Trasmissione, Presentatore, Keyword) VALUES ("' + currentDate + '","' + currentTime + '","' + inputFile + '","' + cliente + '","' + emittente + '","' + oraTrasmissione + '","' + durataTrasmissione + '","'+ sottotitolo + '","' + titoloTrasmissione + '","' + presentatore + '","' + keyword +'");'), (err, req, res)=>{
if (err) console.log(err)
else{
con.query(('SELECT * FROM Tab_Clienti WHERE Cliente = "' + cliente +'"'), (err, QCliente, fields) =>{
if (err) console.log(err)
else{
con.query(('SELECT * FROM Tab_Emittenti WHERE Emittente = "' + emittente +'"'), (err, QEmittente, fields) =>{
if (QEmittente[0].Media == 'TV') var mediaEmittente = 'T';
if (QEmittente[0].Media == 'Radio') var mediaEmittente = 'R';
if (QEmittente[0].Media == 'W') var mediaEmittente = 'W';
Try like below
$('.broadcast-form').unbind('submit').submit();
or
('.broadcast-form').submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: $(this).attr( 'action' ),
data: $(this).serialize(),
success: function( response ) {
}
});
return false;
});
The problem is that both:
<form class="container broadcast-form" action="/form" enctype="multipart/form-data" method="post">
AND
$.ajax({
url: '/form',
method: "POST",
dataType: 'json',
data: formSend,
processData: false,
contentType: false,
success: function(result){
console.log(result);
},
error: function(er){
console.log(er);
}
});
They Were sending the same form to the same "post" call, so one of them get the data and the other one not so the other one return an error. The solution is to let one of them address the call to another "post".
You should try to remove action in your code to have something like this:
<form class="container broadcast-form"
enctype="multipart/form-data" method="post">
Then in the sendForm() function pass e and add e.preventdefault() in your function.

Post restful method java error

Can anyone tell me why this error?
Server Log:
StandardWrapperValve[ws_site.ApplicationConfig]: Servlet.service() for servlet ws_site.ApplicationConfig threw exception
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 5
at com.google.gson.stream.JsonReader.expect(JsonReader.java:339)
at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:322)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:165)
at com.google.gson.Gson.fromJson(Gson.java:791)
Javascript function, responsible for capturing the data of the filled form and sending to the server:
function save()
{
var str_name = $("#name").val();
var str_email = $("#email").val();
var str_country = $("#country").val();
var str_state = $("#state").val();
var str_city = $("#city").val();
var str_zipcode = $("#zipcode").val();
var str_neighborhood = $("#neighborhood").val();
var str_street = $("#street").val();
var str_number = $("#number").val();
var objdata = '{"email_user":"' + str_email + '","name_user":"' + str_name}';
var objlocation = '{"country":"' + str_country + '","state":"' + str_state + '","city":"' + str_city + '","neighborhood":"' + str_neighborhood + '","street":"' + str_street + '","number":"' + str_number + '","zipcode":"' + str_zipcode + '"}';
var obj = '{"user":['+objdata+'],"endereco":['+objlocation+']}';
$.ajax({
headers: {'content-type': 'application/json'},
dataType: 'json',
method: "POST",
url: "http://localhost:8080/SystemExample/webservice/Save/data",
data: obj
}).done(function (data)
{
alert(data);
});
}
Restful Java method:
#POST
#Path("data")
#Produces(MediaType.TEXT_PLAIN)
#Consumes({MediaType.APPLICATION_JSON})
public String registerUser(Gson json)
{
User u = json.fromJson("user", User.class);
Address a = json.fromJson("endereco", Address.class);
u.setAddress(a);
userDAO.save(u);
return "Saved successfully!";
}
Save userDAO method:
public void save(User u) {
EntityManager em = JPAUtil.getEntityManager();
EntityTransaction tx = em.getTransaction();
try {
tx.begin();
if (u.getId_User() == null) {
em.persist(u);
} else {
em.merge(u);
}
tx.commit();
} catch (Exception ex) {
ex.printStackTrace();
if (tx != null && tx.isActive()) {
tx.rollback();
}
} finally {
em.close();
}
}
Using Gson to convert json into an object
You're not sending an object to the server, you're just sending a string:
var obj = '...';
Instead, send an object:
var objdata = {
"email_user": str_email,
"name_user": str_name
};
var objlocation = {
"country": str_country,
"state": str_state,
"city": str_city,
"neighborhood": str_neighborhood,
"street": str_street,
"number": str_number,
"zipcode": str_zipcode
};
var obj = {
"user": [objdata],
"endereco": [objlocation]
};
A string that looks like an object is still a string.
objdata was not populating correctly as valid json. Try with this:
function save() {
var str_name = $("#name").val();
var str_email = $("#email").val();
var str_country = $("#country").val();
var str_state = $("#state").val();
var str_city = $("#city").val();
var str_zipcode = $("#zipcode").val();
var str_neighborhood = $("#neighborhood").val();
var str_street = $("#street").val();
var str_number = $("#number").val();
var objdata = '{"email_user":"' + str_email + '","name_user":"' + str_name + '"}';
console.log(objdata);
var objlocation = '{"country":"' + str_country + '","state":"' + str_state + '","city":"' + str_city + '","neighborhood":"' + str_neighborhood + '","street":"' + str_street + '","number":"' + str_number + '","zipcode":"' + str_zipcode + '"}';
console.log(objlocation);
var obj = '{"user":[' + objdata + '],"endereco":[' + objlocation + ']}';
console.log(obj);
$.ajax({
headers: {'content-type': 'application/json'},
dataType: 'json',
method: "POST",
url: "http://localhost:8080/SystemExample/webservice/Save/data",
data: JSON.parse(obj)
}).done(function (data) {
alert(data);
});
}
In your server side you are trying bind JSON data.
User u = json.fromJson("user", User.class);
Address a = json.fromJson("endereco", Address.class);
It mean user and endereco should be a JSON objects like below.
{
"user":{
"email_user":"str_mail","name_user":"nameeee"
},
"endereco":{
"country":"str_country","state":"str_state","city":"str_city","neighborhood":"str_neighborhood","street":"str_street","number":"str_number","zipcode":"str_zipcode"
}
}
But in your case user and endereco are actually a JSONArray's(See the square brackets.).
{
"user":[
{
"email_user":"str_mail",
"name_user":"nameeee"
}
],
"endereco":[
{
"country":"str_country",
"state":"str_state",
"city":"str_city",
"neighborhood":"str_neighborhood",
"street":"str_street",
"number":"str_number",
"zipcode":"str_zipcode"
}
]
}
So change below line
var obj = '{"user":['+objdata+'],"endereco":['+objlocation+']}';
to
var obj = '{"user":'+objdata+',"endereco":'+objlocation+'}';

Error trying to get a value from Azure table storage in JavaScript

I have so far been unable to query my Azure table from JavaScript. I followed the steps at https://msdn.microsoft.com/en-us/library/azure/dd179428.aspx, describing how to authenticate the request, but so far I only get an Ajax error callback. Does anyone know what is going wrong here? Below is the code that I used:
CORS code (C# Console Application):
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using Microsoft.WindowsAzure.Storage.Shared.Protocol;
namespace WindowsFormsApplication1 {
public partial class Form1 : Form {
private const String ACCOUNT_NAME = "<ACCOUNT_NAME>";
private const String ACCOUNT_KEY = "<ACCOUNT_KEY>";
public Form1() {
InitializeComponent();
}
private CloudTableClient makeTableClient() {
String connectionString = "AccountName=" + ACCOUNT_NAME + ";AccountKey=" + ACCOUNT_KEY + ";DefaultEndpointsProtocol=https";
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
return tableClient;
}
private void btnAdd_Click(object sender, EventArgs e) {
addRule(makeTableClient());
}
private void btnRemove_Click(object sender, EventArgs e) {
removeRule(makeTableClient());
}
public void addRule(CloudTableClient tableClient) {
try {
CorsRule corsRule = new CorsRule() {
AllowedHeaders = new List<string> { "*" },
AllowedMethods = CorsHttpMethods.Connect | CorsHttpMethods.Delete | CorsHttpMethods.Get | CorsHttpMethods.Head | CorsHttpMethods.Merge
| CorsHttpMethods.Options | CorsHttpMethods.Post | CorsHttpMethods.Put | CorsHttpMethods.Trace,
//Since we'll only be calling Query Tables, let's just allow GET verb
AllowedOrigins = new List<string> { "*" }, //This is the URL of our application.
ExposedHeaders = new List<string> { "*" },
MaxAgeInSeconds = 1 * 60 * 60, //Let the browser cache it for an hour
};
ServiceProperties serviceProperties = tableClient.GetServiceProperties();
CorsProperties corsSettings = serviceProperties.Cors;
corsSettings.CorsRules.Add(corsRule);
tableClient.SetServiceProperties(serviceProperties);
} catch (Exception e) {
txtOutput.Text = e.ToString();
}
}
public void removeRule(CloudTableClient tableClient) {
try {
ServiceProperties serviceProperties = tableClient.GetServiceProperties();
CorsProperties corsSettings = serviceProperties.Cors;
corsSettings.CorsRules.RemoveAt(0);
tableClient.SetServiceProperties(serviceProperties);
} catch (Exception e) {
txtOutput.Text = e.ToString();
}
}
}
}
HTML/JavaScript code:
function CallTableStorage() {
var accountName = "<ACCOUNT_NAME>";
var tableName = "<TABLE_NAME>";
var userId = "<PARTITION_AND_ROW_KEY>";
var secretKey = "<ACCOUNT_KEY>";
var partitionKey = userId;
var rowKey = userId;
var queryString = encodeURIComponent(tableName + "(PartitionKey='" + partitionKey + "',RowKey='" + rowKey + "')");
var urlPath = "https://" + accountName + ".table.core.windows.net/" + queryString + "?$select=adid";
var VERB = "GET";
var contentMD5 = "";
var contentType = "text/plain; charset=UTF-8";
var date = (new Date()).toUTCString();
var canonicalizedResource = "/" + accountName + "/" + queryString;
stringToSign = VERB + "\n" +
contentMD5 + "\n" +
contentType + "\n" +
date + "\n" +
canonicalizedResource;
var signature = CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA256(CryptoJS.enc.Utf8.parse(stringToSign), CryptoJS.enc.Base64.parse(secretKey)));
$.ajax({
url: urlPath,
type: 'GET',
success: function(data) {
console.log('Success:', data);
},
beforeSend: function (xhr) {
xhr.setRequestHeader('x-ms-version', '2014-02-14');
xhr.setRequestHeader('x-ms-date', date);
xhr.setRequestHeader('Authorization', "SharedKey " + accountName + ":" + signature);
xhr.setRequestHeader('Accept', 'application/json;odata=nometadata');
xhr.setRequestHeader('Accept-Charset', 'UTF-8');
xhr.setRequestHeader('DataServiceVersion', '3.0;NetFx');
xhr.setRequestHeader('MaxDataServiceVersion', '3.0;NetFx');
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
},
error: function(data) {
console.log('Error:', data);
}
});
}
window.onload = CallTableStorage;
Can you try removing content-type from your stringToSign and see if that works? Or, as Michael Roberson suggested, add a setRequestHeader for Content-Type and see if that works.
Also, if this javascript/html is for a client side app you should be cautious as your account key will be sent in plain text.

Ajax send image to server

I am working phonegap application. I want to send data image to server but i can not sent it.
function addSiteToServer() {
var cId = localStorage.getItem("cId");
var sname = $('#sitename').val();
var slat = $('#lat').val();
var slng = $('#lng').val();
var storedFieldId = JSON.parse(localStorage["field_id_arr"]);
var p = {};
for (var i = 0; i < storedFieldId.length; i++) {
var each_field = storedFieldId[i];
var val_each_field = $('#' + each_field).val();
p[each_field] = val_each_field;
console.log("p" + p);
}
var online = navigator.onLine;
if (online) {
var data = {
site: {
collection_id: cId,
name: sname,
lat: slat,
lng: slng,
properties: p
}
};
//function sending to server
$.ajax({
url: App.URL_SITE + cId + "/sites?auth_token=" + storeToken(),
type: "POST",
data: data,
enctype: 'multipart/form-data',
crossDomain: true,
datatype: 'json',
cache: false,
contentType: false,
processData: false,
success: function(data) {
console.log("data: " + data);
alert("successfully.");
},
}
Looks like you are using the normal method to send data/image to server which is not recommended by Phonegap/Cordova Framework.
I request you to replace your code with the following method which works as you expected,I also used local storage functionality to send values to server,
function sendDataToServer(imageURI) {
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
var params = {};
params.some_text = localStorage.getItem("some_text");
params.some_id = localStorage.getItem("some_id");
params.someother_id = localStorage.getItem("someother_id");
options.params = params;
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI("http://example.co.uk/phonegap/receiveData.php"), win, fail, options);
}
function win(r) {
console.log("Code = " + r.responseCode+"Response = " + r.response+"Sent = " + r.bytesSent);
}
function fail(error) {
alert("An error has occurred: Code = " + error.code);
}
function saveData(){
sendDataToServer(globalvariable.imageURI);
alert("Data Saved Successfully");
}
Hope this helps.

posting multiple arrays to .net webservice using 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

Categories

Resources