Pass large string into api controller by $http angular service - ajax

I have big string, now I want to pass data into api controller by $http angular service. I have lost many times.
Here is my large string
var strObj="{\"countryName\":null,\"cityName\":null,\"stateName\":null,\"objectID\":-1,\"id\":0,\"locationID\":1,\"companyName\":\"\",\"companyShortName\":\"\",\"yearEstablished\":0,\"companyTypeID\":0,\"noOfEmployee\":null,\"regNo\":\"\",\"cBINo\":null,\"yearlyRevenue\":null,\"tINNo\":\"\",\"vATNo\":\"\",\"phone\":\"\",\"mobile\":null,\"fax\":null,\"email\":\"\",\"webSite\":\"\",\"houseNo\":\"\",\"flat\":null,\"section\":null,\"block\":null,\"street\":null,\"cityID\":0,\"stateID\":null,\"countryID\":0,\"zip\":\"\",\"pOBox\":null,\"directories\":null,\"license\":null,\"status\":1,\"isGroupOfCompany\":1,\"isCompanyBranch\":1,\"insertUserID\":100000001,\"editUserID\":null,\"lastUpdate\":\"1899-12-31T18:00:00.000Z\",\"isSelected\":false,\"isEnabled\":false,\"companyMiscList\":[],\"contactPersonList\":[{\"countryName\":null,\"cityName\":null,\"stateName\":null,\"contactPersonName\":null,\"contactDetails\":null,\"objectID\":-2,\"id\":1,\"locationID\":1,\"contactPersonRefID\":-1,\"contactPersonBankID\":0,\"contactPersonRefCode\":1,\"titleID\":0,\"firstName\":\"\",\"middleName\":null,\"lastName\":\"\",\"genderID\":0,\"designation\":\"\",\"workPhone\":\"\",\"homePhone\":null,\"fax\":null,\"mobile\":\"\",\"email\":\"\",\"houseNo\":\"\",\"flat\":null,\"section\":null,\"block\":null,\"street\":null,\"cityID\":0,\"stateID\":null,\"countryID\":0,\"zip\":null,\"isMainContact\":0,\"insertUserID\":100000001,\"editUserID\":null,\"lastUpdate\":\"1899-12-31T18:00:00.000Z\",\"isSelected\":false,\"isEnabled\":false}],\"billingAddressList\":[{\"countryName\":null,\"cityName\":null,\"stateName\":null,\"addressType\":null,\"contactType\":null,\"contactPersonName\":null,\"contactPersonMobile\":null,\"contactPersonEmail\":null,\"addressDetails\":null,\"objectID\":-3,\"id\":2,\"locationID\":1,\"addressRefID\":0,\"addressBillingID\":-1,\"addressShippingID\":0,\"addressRefCode\":1,\"addressTypeID\":100000040,\"houseNo\":\"\",\"flat\":null,\"section\":null,\"block\":null,\"street\":null,\"cityID\":0,\"stateID\":null,\"countryID\":0,\"phone\":\"\",\"fax\":null,\"mobile\":\"\",\"zip\":\"\",\"email\":\"\",\"pOBox\":null,\"contactPersonID\":0,\"contactTypeID\":0,\"insertUserID\":100000001,\"editUserID\":null,\"lastUpdate\":\"1899-12-31T18:00:00.000Z\",\"isSelected\":false,\"isEnabled\":false}],\"shippingAddressList\":[{\"countryName\":null,\"cityName\":null,\"stateName\":null,\"addressType\":null,\"contactType\":null,\"contactPersonName\":null,\"contactPersonMobile\":null,\"contactPersonEmail\":null,\"addressDetails\":null,\"objectID\":-4,\"id\":3,\"locationID\":1,\"addressRefID\":0,\"addressBillingID\":0,\"addressShippingID\":-1,\"addressRefCode\":1,\"addressTypeID\":100000041,\"houseNo\":\"\",\"flat\":null,\"section\":null,\"block\":null,\"street\":null,\"cityID\":0,\"stateID\":null,\"countryID\":0,\"phone\":\"\",\"fax\":null,\"mobile\":\"\",\"zip\":\"\",\"email\":\"\",\"pOBox\":null,\"contactPersonID\":0,\"contactTypeID\":0,\"insertUserID\":100000001,\"editUserID\":null,\"lastUpdate\":\"1899-12-31T18:00:00.000Z\",\"isSelected\":false,\"isEnabled\":false}],\"bankList\":[{\"countryName\":null,\"cityName\":null,\"stateName\":null,\"objectID\":-5,\"id\":4,\"locationID\":1,\"bankRefID\":-1,\"bankRefCode\":0,\"bankName\":\"\",\"branchName\":null,\"houseNo\":\"\",\"flat\":null,\"section\":null,\"block\":null,\"street\":null,\"cityID\":0,\"stateID\":null,\"countryID\":0,\"zip\":\"\",\"pOBox\":null,\"acctName\":null,\"acctNumber\":\"\",\"swiftCode\":null,\"iBANNumber\":null,\"aBANumber\":null,\"phone\":\"\",\"mobile\":null,\"fax\":null,\"email\":\"\",\"webSite\":null,\"insertUserID\":100000001,\"editUserID\":null,\"lastUpdate\":\"1899-12-31T18:00:00.000Z\",\"isSelected\":false,\"isEnabled\":false,\"contactPersonList\":[]}]}"
I have written code for sending
$http({
url: remoteService + '/SaveDraft',
method: 'POST',
data: $.param({ jsonData: strObj }),
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
//params: { jsonData: strObj },
//timeout: d,
//cache: d,
//transformRequest: d,
//transformResponse: d
}).then(function (results) {
return results;
}).catch(function (e) {
throw e;
});
and Here is my api controller method
[HttpPost]
public int SaveDraft(string jsonData)
{
try
{
return 1;
}
catch (Exception)
{
throw;
}
}
What is problem of my code. please help me. Thanks

If you want to pass a large string that for cause you have to use two method one is javascript and another is api method.
The java script method look like this
var data = {
Data: strObj
};
$http({
url: url,
method: 'POST',
data: data,
headers: { 'Content-Type': 'application/json; charset=UTF-8' },
//params: { jsonData: "I am shohel rana" },
//timeout: 10,
//cache: false,
//transformRequest: false,
//transformResponse: false
}).then(function (success) {
return success;
}).catch(function (e) {
throw e;
});
and the api method is
[HttpPost]
public bool SaveDraft([FromBody]object draft)
{
try
{
}
catch (Exception)
{
throw;
}
}

Related

OnDelete Handler always trigger a bad request

Trying to be more consistent with HTTP verbs, I'm trying to call a delete Handler on a Razor Page via AJAX;
Here's my AJAX code, followed by the C# code on my page :
return new Promise(function (resolve: any, reject: any) {
let ajaxConfig: JQuery.UrlAjaxSettings =
{
type: "DELETE",
url: url,
data: JSON.stringify(myData),
dataType: "json",
contentType: "application/json",
success: function (data) { resolve(data); },
error: function (data) { reject(data); }
};
$.ajax(ajaxConfig);
});
my handler on my cshtml page :
public IActionResult OnDeleteSupprimerEntite(int idEntite, string infoCmpl)
{
// my code
}
which never reaches ... getting a bad request instead !
When I switch to a 'GET' - both the type of the ajax request and the name of my handler function ( OnGetSupprimerEntite ) - it does work like a charm.
Any ideas ? Thanks !
Short answer: The 400 bad request indicates the request doesn't fulfill the server side's needs.
Firstly, your server is expecting a form by;
public IActionResult OnDeleteSupprimerEntite(int idEntite, string infoCmpl)
{
// my code
}
However, you're sending the payload in application/json format.
Secondly, when you sending a form data, don't forget to add a csrf token:
#inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Xsrf
<script>
function deleteSupprimerEntite(myData){
var url = "Index?handler=SupprimerEntite";
return new Promise(function (resolve, reject) {
let ajaxConfig = {
type: "DELETE",
url: url,
data: myData ,
success: function (data) { resolve(data); },
error: function (data) { reject(data); }
};
$.ajax(ajaxConfig);
})
}
document.querySelector("#testbtn").addEventListener("click",function(e){
var myData ={
idEntite:1,
infoCmpl:"abc",
__RequestVerificationToken: "#(Xsrf.GetAndStoreTokens(HttpContext).RequestToken)",
};
deleteSupprimerEntite(myData);
});
</script>
A Working Demo:
Finally, in case you want to send in json format, you could change the server side Handler to:
public class MyModel {
public int idEntite {get;set;}
public string infoCmpl{get;set;}
}
public IActionResult OnDeleteSupprimerEntite([FromBody]MyModel xmodel)
{
return new JsonResult(xmodel);
}
And the js code should be :
function deleteSupprimerEntiteInJson(myData){
var url = "Index?handler=SupprimerEntite";
return new Promise(function (resolve, reject) {
let ajaxConfig = {
type: "DELETE",
url: url,
data: JSON.stringify(myData) ,
contentType:"application/json",
headers:{
"RequestVerificationToken": "#(Xsrf.GetAndStoreTokens(HttpContext).RequestToken)",
},
success: function (data) { resolve(data); },
error: function (data) { reject(data); }
};
$.ajax(ajaxConfig);
})
}
document.querySelector("#testbtn").addEventListener("click",function(e){
var myData ={
idEntite:1,
infoCmpl:"abc",
};
deleteSupprimerEntiteInJson(myData);
});

Ajax form submit calling method twice in ASP.NET MVC

I have a weird scenario happens when I send my ajax request that has 2 objects
first time it passes the second obj with the right value while the first object is null.Then second call it passes the first obj with value and the second obj as null
Here's my ajax method
var serializedForm = $(form).serialize();
var postData = {
merchTask: obj,
items: arrItems
};
$.ajax({
type: "POST",
url: $(form).attr('action'),
contentType: "application/json; charset=utf-8",
dataType:'json',
data: JSON.stringify(postData),
success: function (response) {
alert('done');
},
error: function (xhr, status, error) {
alert("Oops..." + xhr.responseText);
}
});
And here's my action in controller
public ActionResult EditTask(Task merchTask, string[] items)
{
short CompanyID = Convert.ToInt16((gSessions.GetSessionValue(gSessionsData.Company) as Company).ID);
try
{
merchTask.CompanyID = CompanyID;
if (merchTask.TaskID != 0)
{
taskTemplatesBF.Update(merchTask);
}
else
{
taskTemplatesBF.InsertMerchTask(merchTask);
}
string[] selectedLst = items;
foreach (string item in selectedLst)
{
taskTemplatesBF.InsertItemsLink(CompanyID,merchTask.TaskID,merchTask.ItemCode);
}
}
catch (Exception ex)
{
if (ex.InnerException != null)
{
ModelState.AddModelError("", ex.InnerException.Message);
}
ModelState.AddModelError("", ex.Message);
}
return RedirectToAction("TasksTemplates", "Merch");
}
*I found a workaround to send each object separately in different ajax
but what's wrong when I send them in one request?
You have added a lot of code in the question but missed the code that was actually needed.
Okay add the event.preventDefault(); and event.stopImmediatePropagation(); functions inside your form summit event as follows:
$(document).ready(function(){
$("formId").on('submit',function(event){
event.preventDefault();
event.stopImmediatePropagation();
var serializedForm = $(form).serialize();
var postData = {
merchTask: obj,
items: arrItems
};
$.ajax({
type: "POST",
url: $(form).attr('action'),
contentType: "application/json; charset=utf-8",
dataType:'json',
data: JSON.stringify(postData),
success: function (response) {
alert('done');
},
error: function (xhr, status, error) {
alert("Oops..." + xhr.responseText);
}
});
});
});
Hope this will solve your problem.

Ajax call to Webmethod, cross domain

I have two Asp projects. On close of a dialog box in project A I am trying to call a static webmethod in project B using ajax call.
Instead of calling the Webmethod it is calling the PageLoad.
Any ideas what I am doing wrong?
WebMethod
[WebMethod]
public static string UpdateSession()
{
return "Test";
}
$(function () {
$('div#DialogDiv').on('dialogclose', function (event) {
CloseDialog("http://localhost:1330/Application_Default.aspx/UpdateSession");
return false;
});
});
function CloseDialog(URL) {
jQuery.support.cors = true;
$.ajax({
type: "GET",
url: URL,
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: function (response) {
alert("success");
},
failure: function (response) {
alert("Failed to trying to find the method: " + URL );
}
});
return false;
}
Try this with pure javascript
function CloseDialog(URL) {
var request = new XMLHttpRequest();
request.open("GET", URL);
request.onload = function() {
if (request.status === 200) {
alert(request.responseText);
// to convert to JSON object-> JSON.parse(request.responseText);
} else {
alert("Failed to trying to find the method: " + URL );
}
};
request.send();
return false;
}
With jQuery I would just do this, you don't need more. It should work with cross-domain too.
function CloseDialog(URL) {
$.ajax({
url: URL,
success: function (response) {
jQuery.each(result.list, function(i, val) {
// iterate the JSON object
// val.node;
});
},
failure: function (response) {
alert("Failed to trying to find the method: " + URL );
}
});
return false;
}

Symfony2 redirect in an ajax action

I am using Symfony2 and in my register.html.twig, I have:
var registerdata= {
"email": email,
"pwd": pwd,
"phoneNum": phoneNum
};
$.ajax({
type: 'POST',
url: "register",
data: registerdata,
success: function(msg){
alert("OK! ");
},
error: function(XmlHttpRequest,textStatus, errorThrown){
alert("Failed! ");
}
});
In my controller, after inserting those data into the database, I want to redirect to the login page, and I have code like this:
try
{
$this -> insertData($account);
return $this ->redirect($this ->generateUrl('login'));
}
catch (Exception $e)
{
return new response('Message: '. $e->getMessage());
}
It does not work, however. How should I handle the problem?
You need another more step in your jQuery code. When the server returns a redirect response, you should redirect the client using javascript:
var registerdata= {
"email": email,
"pwd": pwd,
"phoneNum": phoneNum
};
$.ajax({
type: 'POST',
url: "register",
data: registerdata,
success: function(msg){
alert("OK! ");
},
error: function(XmlHttpRequest,textStatus, errorThrown){
alert("Failed! ");
},
complete: function(xhr)
{
if (xhr.status == 302) {
location.href = xhr.getResponseHeader("Location");
}
}
});
Of course this is far from ideal.

How call WebAPi in phonegap?

I am calling Web API by using Datajs and it is working in each browser but when i am calling this by Phonegap then i am getting error
Http Request failed.
function DefaultHandler() {
var oldDefaultHandler = OData.defaultHandler;
OData.defaultHandler = {
accept: oldDefaultHandler.accept,
read: function (response, context) {
var contentType = response.headers["Content-Type"];
if (contentType && contentType.indexOf("text/html") === 0) {
response.data = response.body;
} else {
oldDefaultHandler.read(response, context);
}
},
write: function (request, context) {
oldDefaultHandler.write(request, context);
}
};
}
function GetContact() {
$('#products').html('');
OData.defaultHttpClient.enableJsonpCallback = true;
DefaultHandler();
OData.read(
{
requestUri: "http://192.168.11.46/odata/Contact",
enableJsonpCallback: false,
datatype: "json",
headers: { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET', 'Content-Type': 'application/json', 'Accept': 'text/html', "Authorization-Token": "94,214,182,1,98,51,181,18,190,167,152,19,225,97,211,221,145,78,188,26,247,172,226,13,90,113,105,2,226,15,137,12,190,22,95,226,215,9,111,95,162,33,36,220,238,197,99,169,158,140,170,61,3,186,190,97,244,173,125,212,3,135,172,111,235,229,133,101,234,188,104,188,127,10,188,221,72,120,48,25,184,56,215,80,87,83,117,30,57,241,133,80,137,220,185,220,230,0,20,122,181,0,106,69,234,27,106,212,187,77,77,27,39,159,31,253,140,105,43,167,210,238,35,71,44,251,180,199" },
method: "GET"
},
success,
error
);
}
success = function (data) {
alert('success Odata');
};
error = function (err) {
alert('error Odata');
};
Is there any setting that i need to set in Eclipse or in emulator.

Resources