I have to call a REST url for example : https://{baseurl}/employees/taxvalidation/. The Request type is JSON, but I'am always get the error Alert. I can't figure out what is the wrong in my code. I am using JQuery
The Supported HTTP Method is : PUT (HTTP PUT with correct request needs to be made) and also i need to pass a API key: XXXXX-XXXXX-XXXXX-XXXXX as request Header.
I have just have two mandatory fields in web page Employee name and Employee Tax.
I have tried the below using JQuery Ajax call.
Request Body Sample:
"name": "Company XYZ", /* mandatory */
"TAX": "*********", /* mandatory */
"taxType": "U", /* Could be E, S, or U */
"address": "2501 Boilermaker road", /* optional */
"citystatezip":"Lapalma ca 76567", /* optional */
"country": "US", //optional
"checks" : "DT",`enter code here`
"details": "DT"`enter code here` //optional
$(function() {
$("#btnSubmit").click(function() {
alert("Hi JQuery");
var URL = "https://api.dev.amx-city.com/tesmdm/dev/tesmdm/empcatalog/partners/taxvalidation/";
$.ajax({
url: URL,
headers : {
'AMX-API-KEY': '487b9474-27a6-4d21-8eda-c3a2a14e4ebe'
},
type: 'POST',
data: {
name: 'Employeename',
tin: '79847324987',
tinType: 'U'
},
dataType: 'json',
success: function(result) {
alert(result);
},
error: function (restul) {
alert(result);
}
});
});
});
when i try to hit the button the debugging is stopped till Alert, after that i don't see the URL is hitting. Let me know if i am doing any wrong?
I am able to get the response now. Below is the working script
$.ajax({
url: URL,
type: "PUT",
headers: {
'AXT-API-KEY': '48776474-26a6-4d21-8eda-c3a2a14e4ebe'
},
data: JSON.stringify({"name": "SupplierName, LLC","tin": "522323454","tinType": "U","checks": "DT"
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
alert(result);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr);
alert(thrownError);
}
});
It worked when i use the key in beforeSend function. But i am not sure the difference.
beforeSend: function (xhr) {
xhr.setRequestHeader("AXT-API-KEY': '48776474-26a6-4d21-8eda-c3a2a14e4ebe");
Related
I need to send id my load page and how can ı send id and load another page ?
MY error : Uncaught SyntaxError: Unexpected string
I now this error syntax error but ı am tried everything , ı am new in ajax and mvc
this is my code :
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url : "http://localhost:9000/api/Customer/CustomerList",
success: function (data) {
$("#customerList").DataTable({
pageLength:50,
destroy: true,
"data": data,
"columns": [
{ "data": "CustID"},
{
"data": function send(data) {
return "#using (Html.BeginForm("CustomerList", "Customers", FormMethod.Post, new { target = "_blank" })) {<input type='submit' value=" + data.custID + " />}";
}
}
]
});
},
error: function (data) {
alert("CustomerList");
}
});
The Razor syntax has to be parsed before it works. If you inspect the output of your page, you will never find the "Html.BeginForm" tag/code.
You code shows you are getting the CustomerList using an ajax request. You can simply use the same technique to post the id when the button is clicked.
return "<input type='submit' onClick='sendID(" + data.custID )'/>";
the sendID function could look something like this
function sendID(customerID){
$.ajax({
type: "POST",
data: {custID: customerID},
contentType: "application/json; charset=utf-8",
url : "http://localhost:9000/api/Customer/GetCustomer", // your endpoint url here
success: function (data) {
// do something
});
},
error: function (data) {
alert("Could not send customerid");
}
});
}
This is untested code.
Salaamun Alekum
I am getting null in controller action via an AJAX request:
var ProjectPermission = [{
"CreatedBy": "Akshay"
},{
"CreatedBy": "Kumar"
},{
"CreatedBy": "ETC"
}]
$.ajax({
url: '/api/Projects/AssignProjectPermissions',
type: 'POST',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify({
ProjectPermission: ProjectPermission
}),
success: function (data) {
alert(data);
},
// processData: false //Doesn't help
});
My C# controller:
[System.Web.Http.HttpPost, System.Web.Http.HttpGet]
public string AssignProjectPermissions(ProjectPermission[] ProjectPermission)
{
I am getting null in ProjectPermission. I already tried other answers but none of them worked for me. These were the posts I checked:
How to get Ajax posted Array in my C# controller?
Ajax post to ASP.net MVC controller - object properties are null
Thank You
You should not be using GET and POST on the same method first of all, just use POST in this case. That aside you do not need the property name. You are putting your array inside of an object. Your method is expecting an array.
var ProjectPermission = [{ CreatedBy: "Akshay" },
{ CreatedBy: "Kumar" },
{ CreatedBy: "ETC" }]
$.ajax({
url: '/api/Projects/AssignProjectPermissions'
, type: 'POST'
, contentType: 'application/json'
, dataType: 'json'
, data: JSON.stringify(ProjectPermission) //<------------issue here
, success: function (data)
{ alert(data); }
//, processData: false
});
In ASP.NET MVC I was using this script to call a method in controller:
<script>
$.ajax({
url: '#Url.Action("getBookedByUser", "Home")',
data: "2",
dataType: "html",
success: function (data) {
$('#someElement').html(data); // add the returned html to the DOM
console.log(data);
},
});
</script>
and this is the method I call:
public async Task getBookedByUser(string id)
{
BenchesService benchService = new BenchesService();
List<Bench> obj = await benchService.getLastBenchByUser(id);
userBench = obj.ElementAt(0);
}
My problem is that id in my controller method is null. It doesn't assume the value "2" as I intend.
Any idea why?
You're almost there. You need to setup the JSON to include your id property:
$.ajax({
url: '#Url.Action("getBookedByUser", "Home")',
data: { id: '2' },
dataType: "html",
success: function (data) {
$('#someElement').html(data); // add the returned html to the DOM
console.log(data);
},
});
This is my ajax post:
$.ajax({
type: "POST",
url: "AddUpdateConfigs",
data: ({id: #Model.QueueMonitorConfigurationsID, pathType: $('#ddlConfigTypeName').val(), threshold:$('#ddlThreshold').val(), valueType:$('#ddlValueTypeName').val(), location: $('#txtbLocation').val(), limit: $('#txtbLimit').val(), config: $('#NewOrUpdate').val() }),
dataType: JSON,
statusCode: {
404: function() {
alert("Data is duplicated");
},
405:function(){
alert("Location Path is not correct");
},
406: function(){
alert("Location Path has to be UNC path");
},
407: function(error){
alert(error);
}
},
success: function()
{
alert ("Success");
}
});
It works good at the beggining and the AddUpdateConfigs function is called.
That function finished with return Json(result); where result is true.
And then my success is not firing because I'm not getting the alert
Any ideas please, what am I doing wrong?
Thank you
success: function()
this should be
success: function(data)
Never mind, I solved it using:
[HttpPost]
public ActionResult AddUpdateConfigs(int id, string pathType, string threshold, string valueType, string location, int limit, string config)
{return new HttpStatusCodeResult(410, "New Data inserted");}
and:
$.ajax({
type: "POST",
url: "AddUpdateConfigs",
data: ({id: #Model.QueueMonitorConfigurationsID, pathType: $('#ddlConfigTypeName').val(), threshold:$('#ddlThreshold').val(), valueType:$('#ddlValueTypeName').val(), location: $('#txtbLocation').val(), limit: $('#txtbLimit').val(), config: $('#NewOrUpdate').val() }),
dataType: 'application/json',
statusCode: {
404: function(){
alert("Data is duplicated");
},
405:function(){
alert("Location Path is not correct");
},
406: function(){
alert("Location Path has to be UNC path");
},
407: function(error){
alert(error);
},
410:function(result){
alert("Item added correctly");
},
411:function(result){
alert("Item updated correctly");
}
}
});
First, on your controller method you should use this:
return Json(result, JsonRequestBehaviour.AllowGet);
Basically, if your action method does not return sensitive data, then it should be safe to allow the get.
However, MVC puts this in with DenyGet as the default to protect you against this attack. It makes you consider the implications of what data you are exposing, before you decide to expose it over HTTP GET.
In your AJAX, change your ContentType to
contentType: 'application/json'
JS:
var queueMonitor = { id: #Model.QueueMonitorConfigurationsID,
pathType: $('#ddlConfigTypeName').val(),
threshold:$('#ddlThreshold').val(),
valueType:$('#ddlValueTypeName').val(),
location: $('#txtbLocation').val(),
limit: $('#txtbLimit').val(),
config: $('#NewOrUpdate').val() };
$.ajax({
url: 'AddUpdateConfigs ',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ parameterName: queueMonitor }),
success: function() {
alert("Success");
}
});
Controller:
[HttpPost]
public JsonResult AddUpdateConfigs(QueueMonitor parameterName) //Note parameter being same as that passed in AJAX Call.
{
//Logic
return Json(result, JsonRequestBehaviour.AllowGet);
}
My success wasnt firing because I wasn't returning with a success, I was using a random error code because I thought I can just give them numbers like that.
For my case it was because the form beaviour, closed before reaching the success/error event
preventDefault() solved it
I am trying $.ajax post MVC call from http to https cross domain.
Client Side
enter code here
$.ajax({
type: 'post',
crossDomain: true,
url: 'https://localhost/views/Member/VerifyEmail',
beforeSend: function () { alert('I am sending'); },
data: '{name:"John"}',
dataType: "json",
success: function (data) { pdata = data; }
});
Server Side
[RequireHttps]
[HttpPost]
public string VerifyEmail(string name){
return "got it"
}
I have added Access-Control-Allow-Origin to web.config so the call can be established fine. Now the problem is on server side I got variable name = null
I have also checked debugging and found the data has actually been send to server
HttpContext.Request.Form
{%7bname%3a%22hello%22%7d}
[System.Web.HttpValueCollection]: {%7bname%3a%22hello%22%7d}
The question is how I could retrieve it from the web method?
%7bname%3a%22hello%22%7d This is HTML entity String please Decode the String then parse for JSON.
I think you can change your call to
$.ajax({
type: 'post',
crossDomain: true,
url: 'https://localhost/views/Member/VerifyEmail',
beforeSend: function () { alert('I am sending'); },
data: 'John',
dataType: "text",
success: function (data) { pdata = data; }
});