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) {
}
}
Related
I POST my table data using ajax in database. Now I want to get back when I give click the open button.
$.ajax({
type: "POST",
url: "http://localhost/./Service/GetPageInfo",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
filename: filename
}),
success: function (data) {
debugger;
//var p = JSON.stringify('[' + data + ']');
// alert(p.GetPageInfoResult[0])
//var k = data.main[0];
//alert(data.length);
//var jsonObj = $.parseJSON('[' + data + ']');
//alert(JSON.parse(data));
var jsonPretty = JSON.stringify(JSON.parse(data), null, 2);
},
error: function () {
alert('Error');
When I give my file name I want to display my pageinfo. I get data like
[{"main":{"sub":[],"tittle":"oops","startvalue":"21","stopvalue":"45","status":"","accumalated":"","comment":""}}]
You have not cleared where you want place your resultant Json. Below is that Success result placed in div having table . It is just a sample you may change as per your requirement:
function OnSuccess(response) {
debugger;
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
var page = xml.find("Table");
var row = "";
$('#popupdiv tbody').html('');
page.each(function () {
var page = $(this);
row = " " + page.find("tittle").text() + " " + page.find("startvalue").text() +
" " + page.find("stopvalue").text() + " " + page.find("status").text() +
" " + page.find("accumalated").text() + " " + page.find("comment").text() + "";
$('#popupdiv tbody').append(row);
});
}
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);
I have a javascript code as below
var xReg = '<region><width>' + $("#txtWidth").val() + '</width> <height>' + $("#txtHeight").val() + '</height><float>' + $("#floats").val() + '</float><contenttype>' + $("#contenttype").val() + '</contenttype><style>' + rgnStyle + '</style></region>';
$.ajax({
type: "POST",
url: "myurl/addRegion",
data: "{pubId: '" + Number($("#pubs").val()) + "',section: '" + $("#sections option:selected").text() + "',layoutW: '" + Number($("#txtLayoutW").val()) + "',layoutH: '" + Number($("#txtLayoutH").val()) + "',bSubReg: '" + Boolean($("#chkSubRegion").is(':checked')) + "',parentRegId: '" + Number(parentRgn) + "',sXmlRegion: '" + xReg.toString() + "'}",
contentType: "application/json; charset=utf-8",
async: false,
dataType: "json",
success: function (result) {
document.body.style.cursor = 'pointer';
if (result.d == -1) {
$("#errMsg").text("Failed to create new region");
}
else {
if ($("#chkSubRegion").is(':checked')) {
$("#regions").append("<option class='ddindent' value='" + result.d + "'>REGION-" + result.d.toString() + "</option>");
} else {
$("#subregions").append("<option class='ddindent' value='" + result.d + "'>SUBREGION-" + result.d.toString() + "</option>");
}
}
},
error: function (result) {
if (result.status == 200 && result.statusText == 'OK') {
if ($("#chkSubRegion").is(':checked')) {
$("#regions").append("<option class='ddindent' value='" + result.d + "'>REGION-" + result.d.toString() + "</option>");
} else {
$("#subregions").append("<option class='ddindent' value='" + result.d + "'>SUBREGION-" + result.d.toString() + "</option>");
}
}
else {
alert("FAILED : " + result.status + ' ' + result.statusText);
}
},
async: true
});
Server code as below
[WebMethod]
public int addRegion(int pubId, string section, int layoutW, int layoutH, bool bSubReg, int parentRegId, string sXmlRegion)
{
string path = Server.MapPath("~");
path = Path.Combine(path, "Published");
path = Path.Combine(path, pubId.ToString());
path = Path.Combine(path, section);
XmlDocument doc = new XmlDocument();
int rgnCount = 0;
try
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
path = Path.Combine(path, "layout.xml");
if (!File.Exists(path))
{
XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
doc.AppendChild(docNode);
XmlNode templateNode = doc.CreateElement("layout");
doc.AppendChild(templateNode);
XmlNode xNodeW = doc.CreateElement("width");
xNodeW.AppendChild(doc.CreateTextNode(layoutW.ToString()));
XmlNode xNodeH = doc.CreateElement("height");
xNodeH.AppendChild(doc.CreateTextNode(layoutH.ToString()));
}
else
{
doc.Load(path);
doc.DocumentElement.SelectSingleNode("/layout/width").InnerText = layoutW.ToString();
doc.DocumentElement.SelectSingleNode("/layout/height").InnerText = layoutH.ToString();
}
XmlElement root = doc.DocumentElement;
XmlNode xParent = root;
if (bSubReg)
{
xParent = root.SelectSingleNode("/layout/region[id='" + parentRegId.ToString() + "']");
rgnCount = xParent.SelectNodes("/region").Count;
}
else
{
rgnCount = root.SelectNodes("/Layout/region").Count;
}
rgnCount++;
XmlDocumentFragment docFragment = doc.CreateDocumentFragment();
docFragment.InnerXml = sXmlRegion;
XmlNode xID = doc.CreateElement("id");
xID.AppendChild(doc.CreateTextNode(rgnCount.ToString()));
docFragment.FirstChild.AppendChild(xID);
xParent.AppendChild(docFragment);
doc.Save(path);
return rgnCount;
}
catch (Exception eX)
{
return -1;
}
}
The call is going to server from client. And no issues I could find in server code till last return statement while I debugged it. In the javascript debugging I found that after ajax call is always going to error callback function. Can anyone suggest whats wrong with the code.
Thanks & Appreciate Your Time.
I found the bug in my code there is issue with below lines of code
},
async: true
at the end of error: callback function
I removed the line async: true and it worked
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
I have web methods that are called via AJAX in a .Net 4.0 web app. In many cases, the AJAX calls are made repeatedly in a for loop. My problem is, the information the web method is syncing to my server is time stamped and therefore must be synced in the order in which I am sending it to AJAX. Unfortunately, it seems whatever finishes first, simply finishes first and the time stamps are all out of order. I need to basically queue up my AJAX requests so that they execute in order rather than Asynchronously, which I know is the A in AJAX so this might be a totally dumb question.
How do I force the order of execution for AJAX calls done in a for loop?
Edit: Some code
for (var i = 0; i < itemCnt - 1; i++) {
try {
key = items[i];
item = localStorage.getItem(key);
vals = item.split(",");
type = getType(key);
if (type == "Status") {
var Call = key.substring(7, 17);
var OldStat = vals[0];
var NewStat = vals[1];
var Date1 = vals[2];
var Time1 = vals[3];
var miles = vals[4];
try {
stat(Call, OldStat, NewStat, Date1, Time1, miles, key);
}
catch (e) {
alert("Status " + e);
return;
}
}
else if (type == "Notes") {
var Call = key.substring(6, 16);
var Notes = item;
try {
addNotes(Call, Notes);
}
catch (e) {
alert("Notes " + e);
return;
}
}
else if (key == "StartNCTime" || key == "EndNCTime") {
var TechID = vals[0];
var Date = vals[1];
var Time = vals[2];
var Activity = vals[3];
var Location = vals[4];
var Type = vals[5];
try {
logTime(TechID, Date, Time, Activity, Location, Type,
}
catch (e) {
alert(key + ' ' + e);
return;
}
}
}
catch (e) {
alert(key + ' ' + e);
return;
}
}
function stat(Call, OldStat, NewStat, Date1, Time1, miles, key) {
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "Service.asmx/update_Stat",
data: '{ CallNumber:"' + Call + '", OldStat:"' + OldStat + '", NewStat:"' + NewStat + '", Date1:"' + Date1 + '", Time1:"' + Time1 + '", Miles: "' + miles + '"}',
success: function (data) { },
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert("Sync Update Stat: " + err.Message);
location = location;
}
});
}
function logTime(TechID, Date, Time, Activity, Location, Type, key) {
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "Service.asmx/nonCallTime",
data: '{ TechID:"' + TechID + '", Date1:"' + Date + '", Time1:"' + Time + '", Activity:"' + Activity + '", Location:"' + Location + '", Type: "' + Type + '"}',
success: function (data) { },
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert("Sync Non Call Time: " + err.Message);
location = location;
}
});
}
function addNotes(Call, Notes) {
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "Service.asmx/addNote",
data: '{ Call:"' + Call + '", Notes:"' + Notes + '"}',
success: function (data) { },
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert("Sync Notes: " + err.Message);
location = location;
}
});
}
You have to use callbacks.
function ajax1(){
//..some code
//on ajax success:
ajax2();
}
//etcetera...
Or might I suggest using a javascript library like jQuery to synchronize your ajax requests for you.
set the third parameter in xmlhttp object's open method to false to make it synchronous.
http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
A general pattern for making actions serial would be such:
function doAjax(data, cb) {
...
// when ready call cb
}
(function (next) {
var xhr = doAjax(data, next);
})(function (next) {
var xhr = doAjax(data, next);
})(function (next) {
doAjax(data);
});
Doing so in a for loop would require recursion.
(function next() {
if ( i < n ) {
doAjax(data[i++], next);
}
})();