AJAX is not passing hard-coded data - javascript

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.

Related

pass data from array JSON to ajax

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

Error: The key is invalid JQuery syntax because it is missing a closing bracket

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/

django ajax call return 403 bad request

I'm trying to compile project https://github.com/kannan4k/django-carpool
please refer this project repo for this issue.
and end up with following error during ajax call.
Failed to load resource: the server responded with a status of 400 (BAD REQUEST).
I know this is because of ajax post request & CSRF tokens.
following is my setting.
1. disable "django.middleware.csrf.CsrfViewMiddleware"
2. in new_trip page I have a button (Postdata)so this button sends an ajax request.
My View:-
#login_required
def save_journey(request):
if request.is_ajax() and request.method == "POST":
try:
res = json.loads(request.body)
cords = res['cords']
cords = [[x['d'], x['e']] for x in cords]
distance = res['distance']
start_place = res['start']
end_place = res['end']
clusters = clusterize_latlngs(cords, distance)
time = datetime.datetime.strptime(res['time'], "%m/%d/%Y %H:%M")
Trip.objects.create(user=request.user, time=time, cluster=json.dumps(clusters), travel_distance=distance,
start_place=start_place, end_place=end_place)
return HttpResponse()
except:
return HttpResponseBadRequest()
else:
return HttpResponseNotAllowed(['POST'])
Ajax call (home.js)
function postData() {
radius = 0;
var url = "/save_journey/";
var dataType = 'json';
if (type == 'r') {
radius = $('#radius').val();
url = "/get_results/";
dataType = 'html';
}
var data = JSON.stringify({
cords: myroute,
time: document.getElementById('dateStart').value,
start: document.getElementById('startPlace').innerHTML,
end: document.getElementById('endPlace').innerHTML,
radius: radius,
distance: distance
});
$.ajax({
type: "POST",
url: url,
dataType: dataType,
data: data,
success: function (data) {
if (type == 'r') {
window.location.href = "/search_results/";
}
else {
window.location.href = '/trip_success/';
}
},
error: function () {
console.log('Error getting options list...')
}
});
console.log(data);
}
this code is not able to call /save_journey/ URL.
I tried many answers from stack overflow & didn't figure out what is the problem .
You should never disable csrftoken unless you're absolutely sure about what you're doing. It's an important part of the security features implemented in Django.
Here is an example of how you can use Ajax with Django with csrftoken:
You can use Ajax Post to send JSON to Django and then handle the arguments as a dict(). Here is an example:
In browser (JQuery/JavaScript):
function newModule() {
var my_data = $("#my_element").val(); // Whatever value you want to be sent.
$.ajax({
url: "{% url 'modules' %}", // Handler as defined in Django URLs.
type: "POST", // Method.
dataType: "json", // Format as JSON (Default).
data: {
path: my_data, // Dictionary key (JSON).
csrfmiddlewaretoken:
'{{ csrf_token }}' // Unique key.
},
success: function (json) {
// On success do this.
},
error: function (xhr, errmsg, err) {
// On failure do this.
}
});
In server engine (Python):
def handle(request):
# Post request containing the key.
if request.method == 'POST' and 'my_data' in request.POST.keys():
# Retrieving the value.
my_data = request.POST['my_data']
# ...
Hope this helps.

No indication jquery ajax call completes

I have the following ajax call
function update_ledger_amount(id) {
$.ajax({
type: "POST",
url: "/ledgeritems/UpdateAmount",
data: "Id=" + id + "&Amount=" + $('#ledger_edit_amount_input_' + id).val(),
success: function (str) {
var result = str.split('|');
alert(str);
if (result[0] == 'success') {
set_display_message('Item updated', 'success');
load_ledger_month($('#BankAccountId').val(), $('#StartDate').val());
}
else {
alert('bad');
set_display_message(result[1], 'error');
}
},
error: function (request, status, error) {
alert(error);
}
});
}
The problem I'm having is that I get no alerts on success or error. Watching the traffic via firebug I can see the response is a simple
success
I believe the problem could have to do with the content-type of the response, it shows as text/javascript. I'm thinking maybe I need to do something different to handle that content type.
use dataType as json and send the response as json in your controller(php).. you can do that by ...echo json_encode(array('success'=>'success'))
JQUERY
$.ajax({
type: "POST",
url: "/ledgeritems/UpdateAmount",
data: "Id=" + id + "&Amount=" + $('#ledger_edit_amount_input_' + id).val(),
dataType:'json',
success: function (str) {
alert(str.success); //in mycase.. you can do your stuff here
/*var result = str.split('|');
alert(str);
if (result[0] == 'success') {
set_display_message('Item updated', 'success');
load_ledger_month($('#BankAccountId').val(), $('#StartDate').val());
}
else {
alert('bad');
set_display_message(result[1], 'error');
}*/
},
error: function (request, status, error) {
alert(error);
}
});
PHP
.....
echo json_encode(array('success'=>'success'));
this sends success as json and you can get that in success function of ajax
put a try catch block in your success handler. I guess it is failing at this line
ar result = str.split('|');
You're doing a POST ajax not GET. The data part of the ajax should be in the form of:
data: { name: "John", location: "Boston" }
Remove the line
type = "POST",
because you want to append params to the url with your request.
As of jQuery 1.8 success, error and complete are deprecated, use done, fail and allways instead.
http://api.jquery.com/jQuery.ajax/#jqXHR
The syntax for a POST would be like:
data = {id:"something", Amount:"someval"};

Javascript 'Namespaces' and jQuery AJAX

I'm using the recommendations laid down here (http://www.odetocode.com/articles/473.aspx) to write a JavaScript AJAX webchat system using simulated Namespacing and prototyping.
In one of my prototype methods I'm calling the $.ajax method in jQuery. What I then want to do is pass the returned JSON data into a method inside my JavaScript webchat namespace.
The problem seems to be because I've created an instance of my JavaScript webchat, I can't directly call a method inside it because I need to address it through the instance.
The key part in the code below is
success: function(data, textStatus) {
this.GetUpdate_Success(data)
},
I'm thinking because we're inside the $.ajax() method, that this no longer refers to our WebchatV3 object.
The full JavaScript code is shown below:
/// <reference path="/JavaScript/jquery-1.3.2-vsdoc2.js" />
// Simulated 'namespace'
var AvonAndSomerset = {}
// Chatroom run time data
AvonAndSomerset.WebchatV3 = function(memberId, passcode) {
this.Members = new Array(); // Members in the chatroom
this.Questions = new Array(); // The questions queue in the chatroom
// Details about the current user
this.currentMember = new AvonAndSomerset.WebchatV3.Member(memberId, passcode, null, null, null, null, null);
// Set-up AJAX defaults
$.ajaxSetup({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json"
});
}
AvonAndSomerset.WebchatV3.prototype = {
// Get latest Member,Quetsion,Transcript and Room data from server
GetUpdate: function(StartUp) {
$.ajax({
url: "JSON.aspx/Members_GetChanges",
data: "{ MemberID: " + this.currentMember.memberId + ", Passcode: \"" + this.currentMember.passcode + "\", ReturnAll: " + StartUp + " }",
success: function(data, textStatus) {
this.GetUpdate_Success(data)
},
error: function(result) {
alert('Members_GetChanges() failed: ' + result.responseText);
}
});
},
// Callback - on success of GetUpdate()
GetUpdate_Success: function(data) {
alert('The AJAX call was successful!');
},
// Does the MemberID exist in the local array?
Members_DoesExist: function(MemberID) {
alert('Searching for ' + MemberID);
alert(this.Members.length);
}
The easiest way to fix this is to create a variable that references this at the proper scope required. this and scope work differently in javascript then most languages, in this case it is referring to the object being passed into the function.
// Get latest Member,Quetsion,Transcript and Room data from server
GetUpdate: function(StartUp) {
//here
var self = this;
$.ajax({ url: "JSON.aspx/Members_GetChanges",
data: "{ MemberID: " + this.currentMember.memberId + ", Passcode: \"" + this.currentMember.passcode + "\", ReturnAll: " + StartUp + " }",
success: function(data, textStatus) {
self.GetUpdate_Success(data)
},
error: function(result) {
alert('Members_GetChanges() failed: ' + result.responseText);
}
});
},
Try
success: function(data, textStatus) {
AvonAndSomerset.WebchatV3.GetUpdate_Success(data)
},
That may work.

Categories