Maybe this question is frequent in the forums, but After days of searching the forum without success, I decided to ask for help.
I am trying to send to my web service an array of objects in JSON format, but without success, I always get a 500 error on the server side, I try different ways (especially found here) but I keep getting the same error.
the json format I get form a jquery plugin that transforms a table into JSON code.
this is the message from the navegator
Message: "Invalid web service call. Missing value for parameter: 'totalKilos'."
And this is my JSON Code
{
"lista": [
{
"idSolVenta": "1",
"rutEmpresa": "123456789",
"idDetalleSolicitud": "1",
"idCategoria": "3",
"idSubcategoria": "8",
"CantidadKilos": "123456"
},
{
"idSolVenta": "1",
"rutEmpresa": "123456789",
"idDetalleSolicitud": "1",
"idCategoria": "3",
"idSubcategoria": "8",
"CantidadKilos": "123456"
}
]
}
//and more, it's dinamic
And this is my Ajax code
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://localhost:63160/WebServiceDetalleSolicitudVenta.asmx/insertarSolicitudVenta",
data:salida,
//crossDomain: true,
dataType: "json",
beforeSend: function (x) {
if (x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
success: function () {
alert("SUCCESS!");
},
error: function (msg, source, lineNo, columnNo, error) {
alert("Error: " + msg +
"\nScript: " + source +
"\nLine: " + lineNo +
"\nColumn: " + columnNo +
"\nStackTrace: " + error);
}
I am really desperate, I hope you can help me find an answer
thank you very much to all
Related
In index.js I have:
$("#weather_form").on("submit", function(event){
event.preventDefault();
$.ajax({
url: "/weather/",
type: "POST",
data: {type_of_person: "1",
exercise: "2",
unit: "3",
zip_postal: "4"},
dataType: "json",
contentType: "json",
success: function (data){
alert("success");
},
error: function(xhr,errmsg,err) {
alert("errmsg: " + errmsg + "\nerr: " + err + "\nxhr.status: " + xhr.status + "\nxhr.responseText: " + xhr.responseText);
}
});
});
I'm getting the following error:
So we know it's going into the error function of the AJAX call because of the popup. But why?
I specifically hard-coded the JSON values to pass.
The view that processes the AJAX data:
class weather(base.TemplateView):
template_name = "weather/index.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["form"] = forms.input_form()
return context
#staticmethod
def post(request, *args, **kwargs):
form = forms.input_form(request.POST)
if form.is_valid():
# process the data
type_of_person = form.cleaned_data["type_of_person"]
exercise = form.cleaned_data["exercise"]
unit = form.cleaned_data["unit"]
zip_postal = form.cleaned_data["zip_postal"]
results_matrix = interface.get_results_matrix(type_of_person, unit, exercise, zip_postal)
return http.JsonResponse({"results_matrix": results_matrix.tolist()}, status=200)
else:
return http.JsonResponse({"error": form.errors}, status=400)
Things I've tried, but to no avail:
data: JSON.stringify({type_of_person: "1", exercise: "2", unit: "3", zip_postal: "4"})
I think the form could not read data as you are sending contentType of json. Just removing that line should work. Also, you have to add csrf header to post request. So:
$.ajax({
url: "/weather/",
type: "POST",
data: {
"csrfmiddlewaretoken": $('[name=csrfmiddlewaretoken]').val(),
"type_of_person": "1",
"exercise": "2",
"unit": "3",
"zip_postal": "4"
},
dataType: "json",
// contentType: "json", remove this
success: function (data){
alert("success");
},
error: function(xhr,errmsg,err) {
alert("errmsg: " + errmsg + "\nerr: " + err + "\nxhr.status: " + xhr.status + "\nxhr.responseText: " + xhr.responseText);
}
});
Well, it doesn't make sense to call success if you're receiving a 400 status code from the server.
Your data is valid in frontend and goes to the server, but it does not pass backend validations (or the backend fails to accept it properly) and therefore it returns you 400 Bad Request.
Any error code that is between 200-299 and different than 304 is considered an error when making an jQuery AJAX call.
I have an application that sends a message through JSON via ajax. This is the JS object:
var message = {
"message_by": colmn[0].innerHTML,
"message_date": new Date(),
"message_recipients": [
{
"phone_number": colmn[1].innerHTML,
"recipient_name": colmn[2].innerHTML
}
],
"message_text": colmn[3].innerHTML,
"subscriber_name": "John Doe"
};
Which is then posted like so:
var url = "http://url/api/sendMessage";
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(message),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (data, status, jqXHR) {
console.log(data);
console.log(status);
console.log(jqXHR);
//alert("success..." + data);
alert("Success. Message sent.");
},
error: function (xhr) {
//alert(xhr.responseText);
alert("Error. Try again.");
}
});
The stringified message could look like this for example:
var message = {
"message_by": "Brian",
"message_date": new Date(),
"message_recipients": [{
"phone_number": "0700111222",
"recipient_name": "Timothy"
}, {
"phone_number": "0800222111",
"recipient_name": "Winnie"
}],
"message_text": "Hello! You are invited for a cocktail at our auditorium. ",
"subscriber_name": "John Doe"
}
Now to the problem. The messages are posted to the api just fine but recently noticed some messages failing and discovered the failed messages had 100 message recipients or more. It works fine up to 99. I asked a colleague and he said there weren't any limit restrictions set on the api.
Is there a way I could limit the object size to 99 and push the remainder to a new object but still have it as part of the same ajax post? Is there any other creative way around this?
There is no such limit.
If you want to restrict your message recipients to 99 you can do as follows
validateMessege(message){
var length = message.length;
var messegeRep = message.message_recipients.slice()
for(var i = 0; i < length; i+=99){
message.message_recipients = messageRep.slice(i, i+99)
// Your post request here
}
}
I am getting this error in chrome console while trying to request a response from a government private API test server that I'm working against. It says syntax is wrong but I don't see the missing bracket at all.
Edge console gave extra error text
BAD REQUEST - The request could not be processed by the server due to invalid syntax.
Otherwise Edge is the same error as in chrome:
{"Message":"The request is invalid.",
"ModelState":{"message":[
"The key is invalid JQuery syntax because it is missing a closing bracket\r\nParameter name: key"]}},
"status":400,
"statusText":"Bad Request"}
I'm just writing a test request trying to post an xml form to the expected message inbox on the testserver. (the government testserver not mine)
I've tried alot of variations plus looking at the api documentation for possible explanations.
Here is the code:
<script>
$(document).ready(function() {
var postData = "";
var xmltext = "";
$.get('TiltakUtenAnsvarsrett.xml', function(tiltakutenansvarsrettXML) {
xmltext = tiltakutenansvarsrettXML;
//xmltest = xmltext.replace(/"/g, '\\"');
console.log("Dette er xmltext variablen" + xmltext);
//console.log("Dette er xmltext variablen stringified" + JSON.stringify(xmltext));
}, 'text');
$("#formtext").click(function() {
this.postData = {
"Type": "FormTask",
"ServiceCode": "4373",
"ServiceEdition": "1",
"_embedded": {
"forms": [{
"Type": "MainForm",
"DataFormatId": "5508",
"DataFormatVersion": "41083",
"FormData": xmltext
}
],
"attachments": [{
"Filename": "String example",
"Attachmenttype": "String example 2",
"Data": "Base64 encoded"
}]
}
};
$.ajax({
url: "https://xxx.xxxx.xx/api/my/messages",
headers: {
"Accept": "application/hal+json",
"ApiKey": "xxxxxxx",
},
xhrFields: {
withCredentials: true
},
type: "POST",
data: JSON.stringify(this.postData),
success: function(data, status, jqHxr) {
console.log("====== Returned messages ======");
console.log(JSON.stringify(data));
}.bind(this),
error: function(jqHxr, textStatus, errorThrown) {
console.log("Kaster feil status");
console.log("jqHxr er: " + JSON.stringify(jqHxr) + "\n");
console.log("Status er: " + textStatus + "\n");
console.log("Erroren er: " + errorThrown + "\n");
console.log("postData er: " + JSON.stringify(this.postData) + "\n");
console.log("Responsetext er: " + jqHxr.responseText);
console.log();
}.bind(this)
});
});
});
</script>
Google searches gave only a few cases of this error message not enough to go on.
If the service is expecting a JSON, add contentType json
type: "POST",
contentType:"application/json",
data: JSON.stringify(this.postData),
success: function(data, status, jqHxr) {
You close bracket '}' to fast.
This is fixed code:
{"Message":"The request is invalid.",
"ModelState":{"message":[
"The key is invalid JQuery syntax because it is missing a closing bracket\r\nParameter name: key"]},
"status":400,
"statusText":"Bad Request"}
You can test json on this page:
http://www.jsoneditoronline.org/
i'm trying to change information from a feature from an arcgis service via rest and json. I have made a function that will be called but the result is giving me no idea what to do.
I'm using openlayers3 as well and i know it has the function feature.setProperties but i`m not sure how to actually put that towards a service. i have checked this example to understand it:
http://openlayers.org/en/latest/examples/vector-esri-edit.html?q=arcgis
but sadly i do not, because i can't create the payload variable.
But if there is a way to do it with openlayers3 i`m even happier.
The code i use is:
export function changeFeature(feature) {
var str = {};
str = feature.getProperties();
for (var s in str) {
if (typeof str[s] === 'object') {
} else {
str[s] = document.getElementById(''+s + '1').value;
feature[s] = document.getElementById(''+s + '1').value;
}
};
console.log(str);
$.ajax({
type: "POST",
url: "http://192.168.216.56:6080/arcgis/rest/services/test/MyMapService/FeatureServer/0/applyEdits",
data: str,
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (data, status, jqXHR) {
alert("success..." + data);
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
And the console will give me this:
Object { geometry: Object,
objectid: "56400",
relcp86d_: "0",
relcp86d_i: "564",
symbol: "4",
polygonid: "0",
scale: "1",
angle: "0",
omschrijvi: "Rosmolen" }
which looks okay but then it throws me this error:
TypeError: event is undefined[Meer info]
here is an Esri documentation to use Applyedit: http://help.arcgis.com/en/arcgisserver/10.0/apis/rest/fsedits.html
so to update a feature, you have to send a json with two objects :
one is the geometry, which contains the X,Y coordinates of the feature
the other is the attributes, with the OBJECTID key-value pair, and other attributes pair to update.
I'm trying to filter the json array through ajax and not sure how to do so.
{
posts: [{
"image": "images/bbtv.jpg",
"group": "a"
}, {
"image": "images/grow.jpg",
"group": "b"
}, {
"image": "images/tabs.jpg",
"group": "a"
}, {
"image": "images/bia.jpg",
"group": "b"
}]
}
i want it so that i can only show items in group A or group B.
how would i have to change my ajax to filter through the content?
$.ajax({
type: "GET",
url: "category/all.js",
dataType: "json",
cache: false,
contentType: "application/json",
success: function(data) {
$('#folio').html("<ul/>");
$.each(data.posts, function(i,post){
$('#folio ul').append('<li><div class="boxgrid captionfull"><img src="' + post.image + '" /></div></li>');
});
initBinding();
},
error: function(xhr, status, error) {
alert(xhr.status);
}
});
Also, how can I can I make each link process the filter?
Group A Group B
Sorry for all these questions, can't seem to find a solution..
Any help in the right direction would be appreciated.
Thanks!
You'll need to write a filter function, more than likely:
function filterGroup(obj, filteredGroup) {
var resultObj = $.extend({},obj);
for (var i in obj) {
if ( obj.hasOwnProperty(i) ) {
if ( obj[i].group && obj[i].group !== filteredGroup ) {
delete resultObj[i];
}
}
}
return resultObj;
}
Then you'd just run your data through that filter. You'll also probably want to switch to a POST with a bunch of JSON like this.
$.ajax({
type: "POST",
url: "category/all.js",
dataType: "json",
cache: false,
data: {"posts": filterGroup(posts, 'a')},
contentType: "application/json",
success: function(data) {
$('#folio').html("<ul/>");
$.each(data.posts, function(i,post){
$('#folio ul').append('<li><div class="boxgrid captionfull"><img src="' +
post.image + '" /></div></li>');
});
}
});
Most of this code is hypothetical since I don't know exactly what you're doing, but it should get you close. Just don't expect to be able to copy/paste it. This assumes you actually named your data variable as posts for instance.
To make a link run code, you'll need to attach a click handler and identify each link. I'll assume you added a classname to each (filterA and filterB):
$('.filterA').click(function(){
filterGroup(someDataObject, 'a');
return false;
});
$('.filterB').click(function(){
filterGroup(someDataObject, 'b');
return false;
});