I'm able to successfully post to the createCustomerProfile endpoint using ARC, but NOT with a simple AJAX post inside javascript. I'm using the following AJAX request:
$.ajax({
type: "POST",
crossDomain: true,
url: 'https://apitest.authorize.net/xml/v1/request.api',
dataType: "json",
data: createCustomerProfileRequest,
success: function (response) {
if (response.dataValue == "Error") {
alert(response.dataDescriptor);
} else {
alert('Successfully sumitted payment!');
}
$("#ccButton").attr("disabled", false);
},
error: function (error) {
alert('Could NOT submit payment!');
$("#ccButton").attr("disabled", false);
}
});
My data is verified to be the following:
"createCustomerProfileRequest": {
"merchantAuthentication": {
"name": "myActualApiKey",
"transactionKey": "myActualTransactionKey"
},
"profile": {
"merchantCustomerId": "Homer Simpson",
"description": "Creating Customer Profile for: Homer Simpson",
"email": "crodgers#newbenefits.com",
"paymentProfiles": {
"customerType": "individual",
"payment": {
"creditCard": {
"cardNumber": "6011000990139424",//Test credit card
"expirationDate": "2028-01"
}
}
}
}
}
}
I'm not certain what i'm doing wrong here. I know i have to have the crossDomain set to true but i keep running into the following parsing error:
"Unexpected character encountered while parsing value: c. Path '', line 0, position 0."
What is causing this to happen in the browser (i'm using Chrome) and NOT when using ARC?
I needed to stringify the JSON i was sending. This will work:
$.ajax({
type: "POST",
crossDomain: true,
url: 'https://apitest.authorize.net/xml/v1/request.api',
dataType: "json",
data: JSON.stringify(createCustomerProfileRequest),
data: createCustomerProfileRequest,
success: function (response) {
if (response.dataValue == "Error") {
alert(response.dataDescriptor);
} else {
alert('Successfully sumitted payment!');
}
$("#ccButton").attr("disabled", false);
},
error: function (error) {
alert('Could NOT submit payment!');
$("#ccButton").attr("disabled", false);
}
});
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.
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;
}
}
How can I pass custom error information from an ASP.NET MVC3 JsonResult method to the error (or success or complete, if need be) function of jQuery.ajax()? Ideally I'd like to be able to:
Still throw the error on the server (this is used for logging)
Retrieve custom information about the error on the client
Here is a basic version of my code:
Controller JsonResult method
public JsonResult DoStuff(string argString)
{
string errorInfo = "";
try
{
DoOtherStuff(argString);
}
catch(Exception e)
{
errorInfo = "Failed to call DoOtherStuff()";
//Edit HTTP Response here to include 'errorInfo' ?
throw e;
}
return Json(true);
}
JavaScript
$.ajax({
type: "POST",
url: "../MyController/DoStuff",
data: {argString: "arg string"},
dataType: "json",
traditional: true,
success: function(data, statusCode, xhr){
if (data === true)
//Success handling
else
//Error handling here? But error still needs to be thrown on server...
},
error: function(xhr, errorType, exception) {
//Here 'exception' is 'Internal Server Error'
//Haven't had luck editing the Response on the server to pass something here
}
});
Things I've tried (that didn't work out):
Returning error info from catch block
This works, but the exception can't be thrown
Editing HTTP response in catch block
Then inspected xhr in the jQuery error handler
xhr.getResponseHeader(), etc. contained the default ASP.NET error page, but none of my information
I think this may be possible, but I just did it wrong?
You could write a custom error filter:
public class JsonExceptionFilterAttribute : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.HttpContext.Response.StatusCode = 500;
filterContext.ExceptionHandled = true;
filterContext.Result = new JsonResult
{
Data = new
{
// obviously here you could include whatever information you want about the exception
// for example if you have some custom exceptions you could test
// the type of the actual exception and extract additional data
// For the sake of simplicity let's suppose that we want to
// send only the exception message to the client
errorMessage = filterContext.Exception.Message
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}
}
and then register it either as a global filter or only apply to particular controllers/actions that you intend to invoke with AJAX.
And on the client:
$.ajax({
type: "POST",
url: "#Url.Action("DoStuff", "My")",
data: { argString: "arg string" },
dataType: "json",
traditional: true,
success: function(data) {
//Success handling
},
error: function(xhr) {
try {
// a try/catch is recommended as the error handler
// could occur in many events and there might not be
// a JSON response from the server
var json = $.parseJSON(xhr.responseText);
alert(json.errorMessage);
} catch(e) {
alert('something bad happened');
}
}
});
Obviously you could be quickly bored to write repetitive error handling code for each AJAX request so it would be better to write it once for all AJAX requests on your page:
$(document).ajaxError(function (evt, xhr) {
try {
var json = $.parseJSON(xhr.responseText);
alert(json.errorMessage);
} catch (e) {
alert('something bad happened');
}
});
and then:
$.ajax({
type: "POST",
url: "#Url.Action("DoStuff", "My")",
data: { argString: "arg string" },
dataType: "json",
traditional: true,
success: function(data) {
//Success handling
}
});
Another possibility is to adapt a global exception handler I presented so that inside the ErrorController you check if it was an AJAX request and simply return the exception details as JSON.
The advice above wouldn't work on IIS for remote clients. They will receive a standard error page like 500.htm instead of a response with a message.
You have to use customError mode in web.config, or add
<system.webServer>
<httpErrors existingResponse="PassThrough" />
</system.webServer>
or
"You can also go into IIS manager --> Error Pages then click on the
right on "Edit feature settings..." And set the option to "Detailed
errors" then it will be your application that process the error and
not IIS."
you can return JsonResult with error and track the status at javascript side to show error message :
JsonResult jsonOutput = null;
try
{
// do Stuff
}
catch
{
jsonOutput = Json(
new
{
reply = new
{
status = "Failed",
message = "Custom message "
}
});
}
return jsonOutput ;
My MVC project wasn't returning any error message (custom or otherwise).
I found that this worked well for me:
$.ajax({
url: '/SomePath/Create',
data: JSON.stringify(salesmain),
type: 'POST',
contentType: 'application/json;',
dataType: 'json',
success: function (result) {
alert("start JSON");
if (result.Success == "1") {
window.location.href = "/SomePath/index";
}
else {
alert(result.ex);
}
alert("end JSON");
},
error: function (xhr) {
alert(xhr.responseText);
}
//error: AjaxFailed
});
Showing the xhr.responseText resulted in a very detailed HTML formatted alert message.
If for some reason you can't send a server error. Here's an option that you can do.
server side
var items = Newtonsoft.Json.JsonConvert.DeserializeObject<SubCat>(data); // Returning a parse object or complete object
if (!String.IsNullOrEmpty(items.OldName))
{
DataTable update = Access.update_SubCategories_ByBrand_andCategory_andLikeSubCategories_BY_PRODUCTNAME(items.OldName, items.Name, items.Description);
if(update.Rows.Count > 0)
{
List<errors> errors_ = new List<errors>();
errors_.Add(new errors(update.Rows[0]["ErrorMessage"].ToString(), "Duplicate Field", true));
return Newtonsoft.Json.JsonConvert.SerializeObject(errors_[0]); // returning a stringify object which equals a string | noncomplete object
}
}
return items;
client side
$.ajax({
method: 'POST',
url: `legacy.aspx/${place}`,
contentType: 'application/json',
data: JSON.stringify({data_}),
headers: {
'Accept': 'application/json, text/plain, *',
'Content-type': 'application/json',
'dataType': 'json'
},
success: function (data) {
if (typeof data.d === 'object') { //If data returns an object then its a success
const Toast = Swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 3000
})
Toast.fire({
type: 'success',
title: 'Information Saved Successfully'
})
editChange(place, data.d, data_);
} else { // If data returns a stringify object or string then it failed and run error
var myData = JSON.parse(data.d);
Swal.fire({
type: 'error',
title: 'Oops...',
text: 'Something went wrong!',
footer: `<a href='javascript:showError("${myData.errorMessage}", "${myData.type}", ${data_})'>Why do I have this issue?</a>`
})
}
},
error: function (error) { console.log("FAIL....================="); }
});
I've a php page and I would to send a jquery ajax request to another page for sending email. This new page accept one parameter and then it executes query ecc...
<div id="customer" name="customer" style="visibility: hidden;"><?php echo $customer; ?></div>
<?php echo '<input id="pulsante" type="image" src="includes/templates/theme485/buttons/english/button_confirm_order.gif" onclick="inoltra();"> '; ?>
this is the script
function inoltra(){
var jqxhr = $.ajax({
type: "POST",
url: "../gestione_di_canio/services.php",
datatype: "json",
data: ??????????????
async:true,
success:function() {
try{
alert("ok");
}catch (e){
alert("correggi");
}
}
});
}
how can I pass to data value of div "customer"?
On data: { varName: $('#customer').html() }
on Php:
$varName= $_POST['varName'];
For a simpler sintax, you use this (it the same):
$.post("../gestione_di_canio/services.php", { varName: $('#customer').html() } )
.success(function() {
try{
alert("ok");
}catch (e){
alert("correggi");
}
});
function inoltra(){
var jqxhr = $.ajax({
type: "POST",
url: "../gestione_di_canio/services.php",
datatype: "json",
data: { customer: $('#customer').html() },
async:true,
success:function() {
try{
alert("ok");
}catch (e){
alert("correggi");
}
}
});
}
I hope this will work for ya...
function inoltra(){
({var jqxhr = $.ajax
type: "POST",
url: "../gestione_di_canio/services.php",
datatype: "json",
data: {"parameter1": value1, "parameter2": value2},// e.i data: {"customer": $('div#customer').html() },
async:true,
success:function() {
try{
alert("ok");
}
catch (e)
{
alert("correggi");
}
}
});
}
as many parameters you want to send would be accessable.
function inoltra(){
var jqxhr = $.ajax({
type: "POST",
url: "../gestione_di_canio/services.php",
datatype: "json",
data: JSON.stringify({paramName: $('#customer').html()}),
async:true,
success:function() {
try{
alert("ok");
}catch (e){
alert("correggi");
}
}
});
}