My API URL contains a payment transaction ID. I want to GET the data about this transaction from my API. The part that says console.log(response); is where I need to GET the data from the API. I will then fill this data into labels. How can I do this? I am using jQuery, ASP.NET, and C#. Thanks.
$.ajax(settings).done(function(response) {
console.log(response);
});
Adding 'success' and 'error' methods to the ajax call will help fetch the data and error codes.
Here is a working example:
$.ajax({
type: "GET",
contentType: "application/json",
url: "URL_WITH_TRANSACTION_ID",
headers: {
"Authorization": "auth-header-string"
},
success: function (output) {
console.log("Success: " + JSON.stringify(output))
},
error: function (e) {
console.log("ERROR : ", e.responseText)
}
})
Maybe native fetch is better choice? Just suggestion.
const { transaction_id } = await fetch(settings).then(r => r.json())
Tell the $.ajax function to expect a JSON response. Do this by adding "datatype": "json" to the settings object. This now means that the response you receive will be treated as JSON, meaning if it is a string with an object in it, it will turn the string into a workable object for you.
From the jQuery documentation:
dataType: The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).
function SubmitTransaction() {
// Card Card US Transaction Settings and Data
var settings = {
"url": "URL_WITH_TRANSACTION_ID",
"method": "GET",
"dataType": "json", // Add this line.
"headers": {
"X-Forte-Auth-Organization-Id": "ORGID",
"Authorization": "AUTHID",
"Content-Type": "application/json",
},
}
$.ajax(settings).done(function(response) {
console.log(response.transaction_id);
console.log(response.organization_id);
console.log(response.location_id);
console.log(response.status);
// etc..
});
}
Related
I am pulling information from a URL using AJAX.
var settings = {
"url": ".php",
"method": "POST",
"timeout": 0,
"headers": {
"Content-Type": "application/json"
},
"data": JSON.stringify({"email":"mail","userid":"admin","type":"push","apikey":"apikey"}),
};
e.preventDefault();
$.ajax(settings).done(function (response) {
console.log(response);
alert(response);
});
$.ajax({
url: ".php",
type: "POST",
"headers": {
"Content-Type": "application/json"
},
"data": JSON.stringify({"email":"mail","userid":"admin","type":"push","apikey":"apikey"}),
error: function(error) {
console.log(error.responseText);
}
And then I get data like this using responseText. When I print error.reponseText, I get data like this:
{
"status": 402,
"status_message": "Failed",
"OTP": "536960"
}
and this data type is a string. There was no problem when I test it on JSON formatter, but I get errors like (json.Parse anonymous) while parsing it or trying to access error.responseText.OTP
var ex = JSON.parse({"status":402,"status_message":"Failed","OTP":"536960"});
This is how I trying to parse.
JSON.parse() works only with string parameter. So you can try:
var ex = JSON.parse(error.responseText)
Also, in your code, the URL parameter is ".php". What is that supposed to mean? That's probably cause of your error. Try to set the actual php filename that you want to send request to.
Actually, your error.reponseText has already Json, So you can access like this way
console.log(error.responseText.OTP);
Updated
Note that JSON.parse() works only with string parameter
var str = "{\"status\":402,\"status_message\":\"Failed\",\"OTP\":\"536960\"}";
var ex = JSON.parse(str);
console.log(ex.OTP);
I'm sending a POST request to a Razor page handler using jQuery .ajax(). The network tab shows that this data is being sent as expected:
My breakpoints confirm that I'm hitting the handler, though the invitationId is not coming over (or at the very least, not deserializing correctly):
The JavaScript is as follows:
class GenericService {
constructor(controller) {
this.controller = controller;
}
async post(data, handler = "") {
return await $.ajax({
type: "post",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN", $('input:hidden[name="__RequestVerificationToken"]').val());
},
data: JSON.stringify(data),
url: `/${this.controller}${handler}`,
contentType: "application/json",
dataType: "json"
});
}
}
(async () => {
const _ajax = new GenericService("Admin/Index");
await _ajax.post({ invitationId: 1 }, "Reset");
})();
I imagine that I'm misunderstanding the implicit deserialization, but examples I've seen elsewhere on the internet seem to indicate that sending a JSON serialized object should be fine.
This is using .NET Core 3.0.
Can anyone explain what might be my issue here?
As expected, I had some wires crossed as it relates to the deserialization.
If I send the data as a plain object without serialization (and remove the corresponding json type declarations from the .ajax() options), the invitationId comes across.
return await $.ajax({
type: "post",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN", $('input:hidden[name="__RequestVerificationToken"]').val());
},
data: data, //Remove JSON.stringify(...)
url: `/${this.controller}${handler}`
//contentType: "application/json", Remove
//dataType: "json" Remove
});
I am trying to make a POST call using AJAX. Here's my controller:
#RequestMapping(method = RequestMethod.POST, value = "/submitsignup")
#ResponseBody
public String persistSignupData(#RequestBody SignupModel signupModel) {
signupDaoImpl.persistSignupData(signupModel);
return "success";
}
Javascript:
$(document).ready(function() {
$("#password2").keyup(checkPasswordMatch);
$('#signup-button').click(function() {
$.ajax({
type: "POST",
url: "/cinestop/submitsignup",
data: JSON.stringify(getFormDataJSON()),
contentType: "application/json",
dataType: "json"
});
});
});
When I make the call, a 404 is returned. I have been unable to debug this problem till now. What is it that I am doing wrong?
When I make the call, a 404 is returned.
Did you ensure that you put the correct url in your ajax part..?
HTTP error 404 usually means that the document that you'r requesting can't be loaded because it's
not existing
it is not readable
the mime type for the document is not defined (usually a problem of common webservers, i dont think that this matches on your specific setup)
Quote of relevant code
url: "/cinestop/submitsignup",
#RequestMapping(method = RequestMethod.POST, value = "/submitsignup")
Avoid stringifying the JSON, since your datatType expected is JSON.
$(document).ready(function() {
$("#password2").keyup(checkPasswordMatch);
$('#signup-button').click(function() {
$.ajax({
type: "POST",
url: "/cinestop/submitsignup",
data: getFormDataJSON(),
contentType: "application/json",
dataType: "json"
});
});
});
First try to debug the application step by step
From postman, curl or any other rest client try to hit a post call with the payload body as empty JSON.If this also return 404, then it is a server problem.If it succeeds or throw any java error then we know it is UI error.Also make sure to add content type header asĀ 'application/json'
This will help in isolating the issue and will help us in giving a quick resolution
Try to run this solution:
var settings = {
"url": "/cinestop/submitsignup",
"method": "POST",
"headers": {
"Content-Type": "application/json"
},
"data": getFormDataJSON()
}
$.ajax(settings).done(function (response) {
console.log(response);
});
and thank you in advance for helping me.
I'm trying to make a POST where I pass the TOKEN in the URL and I want to pass another param too so I can save the info in the DB. I have this:
$("#btnAddCompany").click(function(e) {
var token = "123";
var companyValue = document.getElementById("companyValue").value;
var obj ={CompanyId: 4 ,Name: companyValue }
var postData = JSON.stringify(obj);
console.log(postData);
$.ajax({
type: "POST", //REQUEST TYPE
dataType: "json", //RESPONSE TYPE
contentType: "application/json",
data: postData,
url: "http://banametric.ddns.net/BanaMetricWebServices/BanaSov_WS.svc/CompanySave/"+token,
success: function(data) {
toastr.success("Lidl Adicionado!");
},
error: function(err) {
console.log("AJAX error in request: " + JSON.stringify(err, null, 2));
}
}).always(function(jqXHR, textStatus) {
if (textStatus != "success") {
alert("Error: " + jqXHR.statusText);
}
})
});
But I'm getting an 400 error (Bad Request) so I assume that I'm making something wrong, but I don't find out what. The error trace is this:
AJAX error in request: { "readyState": 4, "responseText": "\r\n
The server encountered an error processing the request. The
exception message is 'The incoming message has an unexpected message
format 'Raw'. The expected message formats for the operation are
'Xml', 'Json'. This can be because a WebContentTypeMapper has not been
configured on the binding. See server logs for more
details. The exception stack trace is: \r\n at
System.ServiceModel.Dispatcher.DemultiplexingDispatchMessageFormatter.DeserializeRequest(Message
message, Object[] parameters)\r\n at
It's error because of
The expected message formats for the operation are 'Xml', 'Json'.
So you can pass contentType in your ajax call
$.ajax({
....,
contentType: "application/json"
})
I am not sure, but it depends on what server wants to read from you.
Server does not want to read raw bytes, it wants xml or json
Try to add headers like
beforeSend: function(xhrObj){
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Accept","application/json");
},
in $.ajax() function
You need to set the content type header in your request to inform the server you're sending the data as JSON.
The error message is telling you that the server does not understand the content you're sending it - you have to give it a hint that the data is in a particular format, especially because, again as mentioned in the error message, it allows you to submit in more than one different format (JSON or XML in this case).
Adding
contentType: "application/json"
to the options in your $.ajax call should resolve the issue.
P.S. We can't see the signature of your controller method but it's possible you may also need to give your parameter a name within the JSON, e.g. something like data: JSON.stringify({ "companyValue": postData }); , but there's not enough info in your question to say for certain what the correct structure should be.
$("body").on("submit", ".example_form", function() {
$.ajax({
url: 'http://example.com/{ROUTE_URL}',
data: new FormData(this),
processData: false,
contentType: false,
/* OR contentType: "application/json; charset=utf-8"*/
type: 'POST',
dataType: "json",
success: function(data) {
console.log(data);
}
});
});
Instead of this
var postData = JSON.stringify(companyValue);
why don't you try this:
var obj ={token :token ,companyValue:companyValue }
And then make use of the json stringify function
var postData = JSON.stringify(obj);
After that in ajax call only change the url:
url: "http://webservice/CompanySave/"
I'm calling a page (external, on other domain), with this code:
var instagram_container = $('div#instagram-answer');
if (instagram_container.length>0)
{
var url = 'http://www.xxxx.it/admin/get_instagram_token';
$.ajax({
type : 'GET',
url : url,
async : false,
jsonpCallback: 'jsonCallback',
contentType: 'application/json',
dataType: 'jsonp',
success: function(response)
{
console.log(response);
instagram_container.html(response.client_id);
},
error: function(e)
{
console.log(e);
}
});
}
I have answer with console.log(e) (basically it recognizes as error)?
Object { readyState=4, status=200, statusText="success", altri elementi...}
But in Firebug, under NET tab, I have the right answer...
This is the console. Line 19 is exactly the
console.log(e);
in error section.
My goal is obtain that Json. Thank you
Is your server returning plain text, or an actual JSON file? Jquery will ignore the response if the server returned a string instead of JSON.
The response type should be: "application/json"
EDIT:
I'd recommend you to use the basic jquery ajax call:
$.ajax({
url: "test.html",
cache: false
})
.done(function( response ) {
console.log(response);
});