Ajax post call seems to work, still throws error? - ajax

Although the code works as expected it throws
"An error occurred whilst trying to contact the server: 200 parsererror SyntaxError: Unexpected end of JSON input"
The success branch is never called but the data arrives to the api.
Should I be concerned and solve it or it probably won't cause problems elswhere? Thank you for your help.
<script>
$(document).ready(function () {
$("#Save").click(function () {
var data2send = JSON.stringify("test");
$.ajax({
url: 'https://localhost:44348/api/products/PostProduct',
type: 'POST',
data: data2send,
contentType: 'application/json',
dataType: 'json',
success: function (data2send) {
console.log(data2send);
},
error: function (jQXHR, textStatus, errorThrown) {
console.log("An error occurred whilst trying to contact the server: " + jQXHR.status + " " + textStatus + " " + errorThrown);
console.log(data2send);
}
});
});
});
</script>
Controller
[HttpPost]
[Route("PostProduct")]
public void Post([FromBody] string obj)
{
Product.prod.Add(new Product() { ProductId = 12, ProductName = obj, Price = 12 });
}

Related

How to send success or failure status to AJAX calls from Asp.Net Web API

I am working on an asp.net C# Web API project. I am posting data from a client using jQuery AJAX. The code is given below. I have tried two types of AJAX calls as shown below. Whether the API succeeds or not, the code under either success or error is never reached in the AJAX.
Asp.Net Web API Code:
[HttpPost]
[Route("SendCustomerDetails")]
public async Task<IHttpActionResult> SendCustomerDetails([FromBody] String jsonData)
{
//Code to process json
//...
//...
resp = await client.PostAsJsonAsync("customer/newcustomer", jObject);
if (resp.IsSuccessStatusCode)
{
//log resp
return Created(Request.RequestUri.ToString(), resp.StatusCode);
}
else{
//log resp
return Created(Request.RequestUri.ToString(), resp.StatusCode);
}
}
Jquery AJAX code1:
$.ajax({
type: 'POST',
url: 'http://localhost:49918/SendCustomerDetails',
dataType: 'json',
//data: jsonData,
data: JSON.stringify(jsonData),
contentType: "application/json"
}).done(function (data) {
alert("Success: " + data);
$('#value1').text(data);
}).fail(function (jqXHR, textStatus, errorThrown) {
alert("failure: " + jqXHR.responseText || textStatus);
$('#value1').text(jqXHR.responseText || textStatus);
});
Jquery AJAX code2:
$.ajax({
type: 'POST',
url: 'http://localhost:49918/SendCustomerDetails',
dataType: 'json',
//data: jsonData,
data: JSON.stringify(jsonData),
contentType: "application/json",
success: function(data) {
alert("Success: " + data);
},
error: function (data) {
alert("error: " + JSON.stringify(data));
}
});
fix the action
[HttpPost]
[Route("~/SendCustomerDetails")]
public IActionResult SendCustomerDetails(JObject model)
{
return Ok(" It is Success");
}
try this code
$.ajax({
type: 'POST',
url: 'http://localhost:49918/SendCustomerDetails',
data: { model:jsonData},
success: function(data) {
alert("Success: " + JSON.stringify(data));
},
error: function (data) {
alert("error: " + JSON.stringify(data));
}
});

Getting 500 error on some docs but not others. Why?

My add-in for MS Word works for some docs but not others. For test-doc-A, it works fine. I get the results I want. test-doc-B throws a 500 error on the $.ajax call that sends the text to the server. Both docs are one page. Granted, 500 errors are supposed to be "server" side. But what could be so different between these docs that's causing this?
The server logs don't indicate anything (to my eye) that tells me what the issue is.
test-doc-A (All Good)
2019-02-28 23:41:33 MyApiEndPoint POST /api/Document/Upload X-ARR-LOG-ID=8b253a46-bca8-4981-9ded-3fdf671fe63c 443 - myIpAddressMozilla/5.0+(Windows+NT+10.0;+WOW64;+Trident/7.0;+Touch;+rv:11.0)+like+Gecko - https://localhost:44399/Home.html?_host_Info=Word$Win32$16.01$en-US myServerUrl 200 0 0 664 3793 46
test-doc-B (500 Error)
2019-02-28 23:42:13 MyApiEndPoint POST /api/Document/Upload X-ARR-LOG-ID=b0095aa0-9fc5-4a26-83b0-40d44ff160ba 443 - myIpAddress Mozilla/5.0+(Windows+NT+10.0;+WOW64;+Trident/7.0;+Touch;+rv:11.0)+like+Gecko - https://localhost:44399/Home.html?_host_Info=Word$Win32$16.01$en-US myServerUrl 500 0 0 326 11306 46
Is there some way to compare the text that's being sent? Am I using the right method 'range.load("text")'?
The only difference between the docs appears to be formatting. But, I'm just sending the text, regardless of formatting, aren't I?
Do I need to "clean" the text before sending? Just so confused, right now.
function sendTextToServer() {
Word.run(function (context) {
var doc = context.document;
var range = doc.body;
range.load("text");
return context.sync()
.then(function () {
var myData = '{\"FileName\": \"WordAddIn-Test\",\"Text\": \"' + range.text + '\" }';
// begin promise
var promise = $.ajax({
url: urlToUse + "/Upload",
method: 'POST',
contentType: 'application/json; charset=utf-8',
beforeSend: function (request) {
request.setRequestHeader("Authorization", "Negotiate");
},
crossDomain: true,
dataType: 'json',
processData: false,
cache: false,
data: myData,
success: function (data) {
log("sendTextToServer Success: " + JSON.stringify(data));
},
error: function (xhr, textStatus, errorMessage) {
log("sendTextToServer promise Error: " + errorMessage + " : " + JSON.stringify(xhr) + " : " + textStatus);
}
});
// end promise
// do something with promise
promise.done(function (data) {
myDocID = data.documentID;
log("sendTextToServer myDocID: " + myDocID);
log("url = " + urlToUse + "/Status?documentID=" + myDocID);
setTimeout(function () { goDoSomethingElse(); }, 2000);
});
})
.then(context.sync);
}).catch(function (error) {
log("Error: " + error);
if (error instanceof OfficeExtension.Error) {
log("Debug info: " + JSON.stringify(error.debugInfo));
log("Something went wrong. Trying again");
}
});
}
"Looks like I picked the wrong week to quit sniffing glue."
~Steve McCroskey

Ajax - Parse oData Response

I have an ajax call that gets data from a REST api.
$.ajax({
url: "http://localhost:52139/odata/WEB_V_CIVIC_ADDRESS",
data: { enteredText: "'" + $('#addressTextField').val() + "'" },
type: "GET",
dataType: 'json',
ContentType: "application/json",
success: function (data) {
alert(JSON.stringify(data));
response($.map(data.accountaddressList, function (item) {
return {
item: item.civicaddress,
value: item.accountNumber,
label: item.civicaddress
}
}));
},
error: function (data, xml, errorThrown) {
alert('Error loading address list: ' + errorThrown);
}
});
The odata returned from that call looks like:
{
"#odata.context":"http://localhost:52139/odata/$metadata#WEB_V_CIVIC_ADDRESS/AValues.Classes.Entities.AccountAddress","value":[
{
"#odata.type":"#AValues.Classes.Entities.AccountAddress","accountNumber":88887,"rowNumber":0,"civicaddress":"123 Fake St"
},{
"#odata.type":"#AValues.Classes.Entities.AccountAddress","accountNumber":88888,"rowNumber":0,"civicaddress":"321 Faker St"
}
]
}
So the current code throws an 'Undefined' error on the line: response($.map(data.accountaddressList, function (item) {
How do I map the 'civicaddress' and 'accountNumber' from each value in the odata response to 'item'?
Thanks.
I got it, needed to change it to response($.map(data.value, function (item)

How to send post ajax request from (.js) file to Spring MVC Controller?

(.js)
$.ajax({
type: "POST",
//contentType : "application/json",
dataType : "json",
url: "getStateNames",
//url:"http://localhost:8081/Mining_22_11_17/pages/admin/a.jsp",
cache: false,
data: "region=" + re + "& stId=" + state_id,
success: function(response){
//$('#result').html("");
alert("hiiii state list");
var obj = JSON.parse(response);
alert("state list" + obj);
//$('#result').html("First Name:- " + obj.firstName +"</br>Last Name:- " + obj.lastName + "</br>Email:- " + obj.email);
},
error: function(){
alert('Error while request..');
}
});
Spring MVC Controller
#RequestMapping(value="/getStateNames",method = RequestMethod.POST)
public #ResponseBody RegionDistrict add(HttpServletRequest request, HttpServletResponse response,#RequestParam String region, #RequestParam String stId) {
System.out.println("Get state");
}
By running this program I am getting 404 error.I want to send request using POST only.
$("#yourID").click(function(event) {
var region = $('#id').val();
var state_id = $('#edited').val();
$.post("${pageContext.request.contextPath}/getStateNames", {
region : region ,
state_id : state_id
}, function(data) {
//var json = JSON.parse(data);
//...
}).done(function(data) {
alert("hiiii state list");
swal("success");
//location.reload();
}).fail(function(xhr, textStatus, errorThrown) {
}).complete(function() {
//$("#btn-save").prop("disabled", false);
});
});
try this hope its works fine
$.ajax({
type: "POST",
url: "/getStateNames",
data: { region: re, stId: state_id },
success : function(response) {
alert(JSON.stringify(resoinse));
},
error: function(){
alert('Error while request..');
}
});
This should work, tell me if this solves your problem

Force.com : Rest API Bad Request in Query Like

I got 'bad request" message on the below Rest API Ajax call, When I tested on Developer console it return data successfully.
var _url = auth.get("instance_url") +
"/services/data/v28.0/query/?q=SELECT Id, Name FROM Account WHERE Website LIKE '%gmail.com%' ";
$.ajax({
url: _url,
cache: false,
async: false,
type: 'GET',
contentType: 'application/json',
headers: {
'Authorization': 'OAuth ' + auth.getAccessToken()
},
success: function (data) {
console.log("accounts: " + JSON.stringify(data));
result = data;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus + +errorThrown);
}
});
You need to URLEncode the query parameter, spaces are not valid in a query string, e.g.
var _url = auth.get("instance_url") + "/services/data/v28.0/query?q=" + encodeURIComponent("select id,name from account");

Resources