I am trying to do an ajax post request with multiple parameters. The method is called on server side but the parameters returns null. What am I doing wrong here? I've tried with and without JSON.stringify.
.cs file:
public async Task<IActionResult> OnPostGenerate(string fname, string lname)
{
return new JsonResult(fname + lname);
}
AJAX script:
$.ajax({
type: "POST",
url: "Index?handler=Generate",
dataType: "json",
contentType: "application/json; charset=utf-8",
headers: {
RequestVerificationToken:
$('input:hidden[name="__RequestVerificationToken"]').val()
},
data: JSON.stringify({
fname: "testFirstname",
lname: "testLastname"
}),
success: function (data) {
alert(data);
}
});
Try to change
data: JSON.stringify({
fname: "testFirstname",
lname: "testLastname"
}),
to
data: {
"fname": "testFirstname",
"lname": "testLastname"
},
and remove
contentType: "application/json; charset=utf-8",
I have a method that should return a response from another server. I use request-promise and put the URL in the options object.
As you can see in the code below, all is in good shape, but when I send the request, it returns 404 - resource not found.
When I change the request(options) method with request("https://api.quickpay.net/payments"), I get a positive answer from the server -- it tells me to add headers and so forth, which is positive.
public requestNewQuickpayPayment(order_id: String, currency : String, callback: Function) {
var options = {
method: 'POST',
uri: 'https://api.quickpay.net/payments',
form:{
order_id : "order123",
currency : "dkk"
},
headers: {
"Content-Type" : "application/json",
'Accept-Version': 'v10'
},
json: true
};
request(options).then((response:any)=>{
console.log(response);
return response;
}).catch((error:any)=>{
console.log(error);
return error;
}).finally(()=>{
console.log("done");
})
}
Something from the console
Request {
_events: [Object],
_eventsCount: 5,
_maxListeners: undefined,
method: 'POST',
uri: [Url],
transform2xxOnly: true,
headers: [Object],
readable: true,
writable: true,
explicitMethod: true,
_qs: [Querystring],
_auth: [Auth],
_oauth: [OAuth],
_multipart: [Multipart],
_redirect: [Redirect],
_tunnel: [Tunnel],
_rp_resolve: [Function],
_rp_reject: [Function],
_rp_promise: [Promise],
_rp_callbackOrig: undefined,
callback: [Function],
_rp_options: [Object],
setHeader: [Function],
hasHeader: [Function],
getHeader: [Function],
removeHeader: [Function],
localAddress: undefined,
pool: {},
dests: [],
__isRequestRequest: true,
_callback: [Function: RP$callback],
proxy: null,
tunnel: true,
setHost: true,
originalCookieHeader: undefined,
_disableCookies: true,
_jar: undefined,
port: 443,
host: 'api.quickpay.net',
body: 'order_id=asdasdasd¤cy=dkk',
path: '/payments',
_json: true,
httpModule: [Object],
agentClass: [Function],
agent: [Agent],
_started: true,
href: 'https://api.quickpay.net/payments',
req: [ClientRequest],
ntick: true,
response: [Circular],
originalHost: 'api.quickpay.net',
originalHostHeaderName: 'host',
responseContent: [Circular],
_destdata: true,
_ended: true,
_callbackCalled: true },
toJSON: [Function: responseToJSON],
caseless: Caseless { dict: [Object] },
body: '404 Not Found' } }
What is wrong here? The path to the ressource is checked many times - nothing is wrong there....
For api.quickpay.net, 404 Not Found does not mean the URI is not recognized, but indicating invalid request body. It has nothing to do with whether the URI is stated in options object, or stated as string parameter of request().
Here is a simple experiment. The code below would return "positive" result, warning missing headers ({"error":"Accept-Version http header is required"}), which indicates that the URI is "recognized":
request({
method: 'POST',
uri: 'https://api.quickpay.net/payments'
}, function(err, res, body) {
console.log(body);
});
However, after the missing Accept-Version header is added, we get 404 Not Found:
request({
method: 'POST',
uri: 'https://api.quickpay.net/payments',
headers: {
'Accept-Version': 'v10'
}
}, function(err, res, body) {
console.log(body);
});
Thus, in order to make the API call work, you need to make the HTTP request valid (following to the document).
I have a WebAPI and I need AJAX call to access this
but on the cross domain
Here is my code :
$.ajax({
type: "POST",
url: '/api/myapiname/apiactionname',
contentType: "application/json",
data: {
name: "Abhishek",
email: "abhi#abhi.com",
password: "******"
},
crossDomain:true,
success: function(data) { console.log(data); },
error: function(data) {console.log(data); },
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
},
});
Have you enabled CORS within your API? Follow the link, http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api
Usually we send data to controller by ajax like following::
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Controller/MyAction",
data: "{'Name':'" + id + "','Class':'" + cls + "'}",
dataType: "json",
See I have to members to send to controller by two different parameters.
I want to send it as a list.
but What I want is to send a list to the controller in just one parameter. Is it possible but how can I achieve that?
JSON.stringify is the key here.
Here is the code:
var myList = { List: [{ Name: "A", Class: "B" },
{ Name: "C", Class: "D" }] };
$.ajax({
type: 'POST',
url: '/{controller}/{action}',
cache: false,
data: JSON.stringify(myList),
dataType: 'json',
contentType: 'application/json; charset=utf-8'
});
"<"?xml version=\"1.0\" encoding=\"utf-8\"?>
"<"string xmlns=\"http://xyz.org/\">
Hello World
"<"/string>
I want to get Hellow World. Then What to do?
If you are using jquery:
$(document).ready(function() {
$("#Result").click(function() {
$.ajax({
type: "POST",
url: "Default.aspx/MyWebMethod",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg.d);
}
});