textStatus error in API REST - ajax

I make a request to a REST web url API, which answers an error in the textStatus field, but when I look at the response I have it as 200, what could be happening?
$.post( "https://page/Api/SolicitudesAbis", {
"IdCliente": 23,
"IdConvenioAutenticacion": "759A28EB-8E51-4A3D-8681-F7E6F23088A6",
"TipoDocumentoCandidato": "CC",
"Candidato": "1076646338",
"IdMaquina": "",
"CodigoOficina": "Oficina 1",
"IdProducto": 1,
"IdSolicitudCliente": "1",
"TiempoValidez": 1,
"TipoIdentidadMaquina": 3,
"UsuarioCreacion": "jneira",
"ProcesoCliente": 0
}
.done(function( data, textStatus, jqXHR ) {
alert("Done");
})
.fail(function( jqXHR, textStatus, errorThrown ) {
alert("Fail " + textStatus);
});

Related

Ajax post call seems to work, still throws error?

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 });
}

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 raise onError from chunking success endpoint in Fine-uploader

In my application, when the chunking-success-endpoint returns JSON like {"error": "reason..."} (for example the server failed to put the chunks back together), the onError event is not being called.
Just to clarify, the onError event is called if individual chunks fail. It's the final success request that I'm having trouble with.
I'm not sure what I'm missing. Should I be handling this some other way?
My configuration is below. Thanks in advance!
var uploader = $('#fine-uploader').fineUploader({
template: 'qq-template',
debug: true,
callbacks: {
onAllComplete: function(succeeded, failed) {
$('#doclib_tree').jstree(true).refresh()
if (failed.length > 0) {
alert("Error: Some files were not uploaded");
} else {
if (succeeded.length > 0 ) {
alert("Successfully uploaded " + succeeded.length + " file(s)");
}
this.reset();
toggle_upload();
}
},
onError: function(id, name, errorReason, xhrOrXdr) {
alert("Error uploading " + name + ". Reason: " + errorReason)
},
onSubmit: function(id, name) {
var promise = new qq.Promise();
var dest = document.getElementById('dest_label').innerHTML.replace(/ > /g, "/")
$.ajax({
'type': 'POST',
'async': false,
'url': "/documents/exists" ,
'data': {
'parents' : get_path(dest),
'name': name,
},
'success': function(data, textStatus, jqHXR) {
if ( check_session(data) ) {
promise.failure();
} else {
if (confirm("The file '" + dest + "/" + name + "' already exists. Replace?"))
promise.success();
else
promise.failure();
}
},
'error': function(jqHXR, textStatus, errorThrown) {
promise.success();
}
});
return promise;
},
},
chunking: {
enabled: true,
partSize: 20000000, // 20MB
success: {
endpoint: "documents/upload?success=1",
}
},
resume: {
enabled: true,
recordsExpireIn: 1, // 1 day
},
request: {
endpoint: "/documents/upload",
},
autoUpload: true
});
From the documentation under the chunking success section:
For successful responses, you may return an empty body with a status of 200-204. Any other status code is determined to be a failure.
In other words, to indicate failure, you must return a status code that indicates failure. Pick the most appropriate status code given the context of the error. At that point, Fine Uploader should determine that the file has failed in some way, and your onError handler will be called with the error property returned by your server.

Trigger parametrized job build using remote API through ajax

I'm using Jenkins ver. 1.406 and can't get to trigger a parametrized (3 strings) build using AJAX.
Some docs talk about a "token" but there is no such option in Jenkin's OR job's configuration panels.
I'm sending the ajax call like this:
var jqxhr = $.post(
"http://servername:8080/job/jab-name/build/api/json",
{ "parameters": [{ "PARAM1": "value1" }, { "PARAM2": "value2" }] },
"json"
)
.success(function () { alert("success"); })
.error(function (xhr, ajaxOptions, thrownError) { alert("Error\nxhr.status = [" + xhr.status + "]\n xhr.status: [" + xhr.statusText + "]\najaxOptions = [" + ajaxOptions + "]"); })
.complete(function () { alert("complete"); });
Parameters are correct (case sensitive) and all of them are set, not use of default value(s).
Anyone can help?
Thanks!
A few things to check
Did you check the "Trigger builds remotely (e.g., from scripts)" option? If checked, there will be text box to enter your token.
Do you use security? If yes you have to authenticate against Jenkins.
Have a look at https://wiki.jenkins-ci.org/display/JENKINS/Remote+access+API (The statement that you need to use json to trigger parametrized builds is wrong)
I think you have to replace build with buildWithParameters in your URL.
var jqxhr = $.post(
"http://servername:8080/job/jab-name/buildWithParameters/api/json",
{ "parameters": [{ "PARAM1": "value1" }, { "PARAM2": "value2" }] },
"json"
)
.success(function () { alert("success"); })
.error(function (xhr, ajaxOptions, thrownError) { alert("Error\nxhr.status = [" + xhr.status + "]\n xhr.status: [" + xhr.statusText + "]\najaxOptions = [" + ajaxOptions + "]"); })
.complete(function () { alert("complete"); });

Resources