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);
}
});
Related
Im working on a project, where we try to exchange different parameters between the UI and a RestAPI via AJAX. The RestAPI defines how the data has to look:
I tried to solve it this way:
$(document).ready(function(){
$("#submit").click(function(){
var credentials = [
{user_name: $("#uname").val(),
password: $("#pwd").val()
}
];
alert(credentials);
$.ajax({
url:"../rest/user/login",
type:"POST",
data:JSON.stringify({credentials: credentials}),
success: function(){
window.location.href = "startrackhome.html";
},
error: function error(response){
try{
var json = JSON.parse(response.responseText);
if(typeof json.message === 'undefined'){
throw new Error("Response json has no message");
}
else{
alert(json.message);
}
}
catch(ex){
alert("unexpected error (code:" + response.status +")");
}
}
});
});
});
The alert shows this: [object Object]
And I always get an error message (error: 400), which means that I mus have made a mistake and I think the format I'm sendig is wrong but I dont know how to fix it.
I hope you can help me! :)
I made some changes to your code :
// credentials is an object
var credentials = {
user_name: $("#uname").val(),
password: $("#pwd").val()
}
alert(credentials);
$.ajax({
// check this url seems a bit off
url: "../rest/user/login",
type: "POST",
data: {
credentials: credentials
},
success: function() {
window.location.href = "startrackhome.html";
},
error: function error(response) {
try {
var json = JSON.parse(response.responseText);
if (typeof json.message === 'undefined') {
throw new Error("Response json has no message");
} else {
alert(json.message);
}
} catch (ex) {
alert("unexpected error (code:" + response.status + ")");
}
}
});
in my case it makes this request :
fetch("https://stackoverflow.com/posts/rest/user/login", {
"headers": {
"accept": "*/*",
"accept-language": "",
"content-type": "application/x-www-form-urlencoded; charset=UTF-8",
"sec-ch-ua": "\" Not A;Brand\";v=\"99\", \"Chromium\";v=\"102\"",
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": "\"Linux\"",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
"x-requested-with": "XMLHttpRequest"
},
"referrer": "https://stackoverflow.com/posts/72620005/edit",
"referrerPolicy": "strict-origin-when-cross-origin",
"body": "credentials%5Buser_name%5D=test&credentials%5Bpassword%5D=test",
"method": "POST",
"mode": "cors",
"credentials": "include"
});
credentials[user_name]: test
credentials[password]: test
which seems good, if the server needs a json, you can stringify the credentials, which gives this paylaod :
credentials: {"user_name":"test","password":"test"}
In my kendo dataSource > transport > update. I want to catch a server response status (refer image), but none of this methods trigger an alert. Any idea why?
update: {
url: "./getRevenueAccounts.php",
type: "POST",
data: function() {
return {
method: "editRevenueAccounts"
}
},
success: function(e) {
if(e.status == 'duplicate'){
alert('Trigger 1');
}
},
error: function(e) {
if (e.errorThrown == 'duplicate') {
alert("Trigger 2");
}else if(e.status == 'duplicate' ){
alert("Trigger 3")
}
},
complete: function (e) {
if(e.status == 'duplicate'){
alert('Trigger 4');
}
}
},
console.log(e) screen shot
Try the following code for your success function:
success: function(e) {
if(e.responseText.status == 'duplicate'){
alert('Trigger 1');
}
},
Essentially, you are looking at the status property when you should have been looking at the responseText property to get the status (which is another property on that object).
You need to make an ajax call inside the update function.
Like:
var dataSource = new kendo.data.DataSource({
transport: {
read: function(options) {
/* implementation omitted for brevity */
},
update: function(options) {
// make JSONP request to https://demos.telerik.com/kendo-ui/service/products/update
$.ajax({
url: "https://demos.telerik.com/kendo-ui/service/products/update",
dataType: "jsonp", // "jsonp" is required for cross-domain requests; use "json" for same-domain requests
// send the updated data items as the "models" service parameter encoded in JSON
data: {
models: kendo.stringify(options.data.models)
},
success: function(result) {
// notify the data source that the request succeeded
options.success(result);
},
error: function(result) {
// notify the data source that the request failed
options.error(result);
}
});
}
},
batch: true,
schema: {
model: { id: "ProductID" }
}
});
For more details please check this from telerik documentation: https://docs.telerik.com/kendo-ui/api/javascript/data/datasource/configuration/transport.update
Is not a good method to apply, but it works to fetch the response.
if(e.responseText=='{"status":"duplicate"}'){
kendo.alert('duplicate data');
}
I have an AJAX call in cordova application.I have checked the availability of internet connection before actual call. But some times in mobile internet connectivity is lost for few seconds after the call is made and thus device does not read any reply from web-service. It goes to error part of Ajax call. I wants to make this Ajax call again so that DOM should get created
call AJAX function is
function callAjax(type, mainurl, dataType, data, successFunction, errorFunction){
if(isOnline == false)
{
alert('Internet is not running. Please reconnect and try');
return 0;
}
$.ajax({
crossDomain: true,
async:false,
type: type,
url: mainurl,
dataType: "json",
data: data,
beforeSend:function(jqXHR,settings){
jqXHR.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
},
success: function(data) {
successFunction(data);
},
error: function(response) {
// alert(JSON.stringify(response));
errorFunction(response);
}
});
}
If you want to retry after an error, you can just re-call your function recursively, or do something like this to prevent too many retries:
function callAjax(type, mainurl, dataType, data, successFunction, errorFunction){
if (isOnline == false) {
alert('Internet is not running. Please reconnect and try');
return 0;
}
function tryAjax(retryCount) {
$.ajax({
crossDomain: true,
async:false,
type: type,
url: mainurl,
dataType: "json",
data: data,
beforeSend:function(jqXHR,settings){
jqXHR.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
},
success: function(data) {
successFunction(data);
},
error: function(response) {
if (retryCount > 10) {
errorFunction(response);
} else {
tryAjax(retryCount + 1);
}
}
});
}
tryAjax(0);
}
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.
I am using the Data Source object to connect to a SharePoint 2013 ODATA source using REST and then use this as the data for a Kendo UI Grid.
The Data Source reads the list correctly and populates the grid, but when I update an item in the Kendo UI Grid the following error is returned by the REST end point.
The property '__deferred' does not exist on type 'SP.SecurableObject'.
Make sure to only use property names that are defined by the type.
This is caused by the Data Source returning all the properties from the initial read request and then returning in the update command.
SharePoint returns __deferred properties with a REST URL to defer loading, but is throwing a wobbly if they are returned back in an update command request.
Below is my Data Source
var dataSource = new kendo.data.DataSource({
type: "odata",
transport: {
read: {
url: listUrl,
type: "GET",
dataType: "json",
contentType: "application/json;odata=verbose",
headers: {
"accept": "application/json;odata=verbose"
}
},
create: {
url: listUrl,
type: "POST",
dataType: "json",
contentType: "application/json;odata=verbose",
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
}
},
update: {
url: function (data) {
return listUrl + "(" + data.ID + ")";
},
beforeSend: function (jqXhr, options) {
var data = JSON.parse(options.data);
jqXhr.setRequestHeader("If-Match", data.__metadata.etag);
},
type: "POST",
dataType: "json",
contentType: "application/json;odata=verbose",
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"X-HTTP-Method": "MERGE"
},
},
destroy: {
url: function (data) {
return listUrl + "(" + data.ID + ")";
},
type: "DELETE",
dataType: "json",
contentType: "application/json;odata=verbose",
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"X-HTTP-Method": "MERGE",
"If-Match": "*"
}
}
},
pageSize: 20,
schema: {
data: "d.results",
model: {
id: "ID",
fields: {
ID: { editable: false, nullable: false },
Title: { validation: { required: true } },
Body1: { validation: { required: true } },
Votes: { type: "number", validation: { required: true, min: 1 } },
}
}
}
});
You can specify a "parameterMap" function on the DataSource.transport, and filter out the data you don't want.
var dataSource = new kendo.data.DataSource({
type: "odata",
transport: {
parameterMap: function(data, type){
if (type === "update" && data["__deferred"]){
delete data["__deferred"];
}
return kendo.stringify(data);
}
// ...
},
// ...
});
See http://docs.kendoui.com/api/framework/datasource#configuration-transport.parameterMap
Another option, if you're working with observable objects, is to provide a custom .toJSON method on your object. I wrote up a blog post about this, here: http://www.kendoui.com/blogs/teamblog/posts/13-04-04/hijacking-tojson-for-fun-and-profit.aspx
Using Derick Bailey's answer I was able to do the following with the parameterMap
the question object is a defined data model. Using this method, it will only send over the fields defined in the model plus the __metadata field that is need by SharePoint.
parameterMap: function (data, type) {
if (type == "update") {
for (var property in data) {
if (property != "__metadata" && !question.fields[property])
delete data[property];
}
}
return kendo.stringify(data);
}