I have a js code (in index.php) as shown below which makes an ajax call to save.php file.
<script>
$(function () {
$('form').submit(function (e) {
e.preventDefault();
$.post({
url: 'save.php',
data: $(this).serialize(),
}).done(response => {
console.log(response);
response = JSON.parse(response);
if (response.message) {
alert(response.message);
}
});
});
});
</script>
The issue which I am facing right now with the code above is when we hit save button I am getting the following error message on the console:
VM68:1 Uncaught SyntaxError: Unexpected token I in JSON at position 0
at JSON.parse (<anonymous>)
at Object.<anonymous> (index.php:1011)
at c (jquery-3.5.1.min.js:2)
at Object.fireWith [as resolveWith] (jquery-3.5.1.min.js:2)
at l (jquery-3.5.1.min.js:2)
at XMLHttpRequest.<anonymous> (jquery-3.5.1.min.js:2)
Here line#1011 is response = JSON.parse(response); from the js code above.
Problem Statement: I am wondering what changes I need to make in the js code above so that on hitting save button I do not get that error message on the console.
If are aware of the error and just want to ignore it/handle it use a try/catch block. That error is usually because response isn't a valid json string so JSON.parse will keep failing.
$(function () {
$('form').submit(function (e) {
e.preventDefault();
$.post({
url: 'save.php',
data: $(this).serialize(),
}).done(response => {
try{
response = JSON.parse(response);
if (response.message) {
alert(response.message);
}
}
catch (e) {
//do something like alert user the request failed
alert('Request to server failed');
}
});
});
More on try/catch from mozilla.
Related
I'm pretty sure response.model.model_to_return is wrong, I try to display on screen the content of the array but my JS structure might be wrong.
JS:
<script>
$(document).ready(function() {
setInterval(function() {
$.ajax({
type: 'GET',
url: "/trafic",
success: function check(response) {
//CODE WORKSPACE //
console.log(response);
$("#variat").empty();
for (var model of response.model.memory_return) {
}
//CODE checkview //
console.log(response);
$("#display").empty();
for (var model of response.model.models_to_return) {
}
},
error: function(response){
//alert('An error occured')
}
});
}, 10000)
})
</script>
Python view:
def trafic(request):
user_msg = request.user
get_Messages = Message.objects.filter(user=user_msg).values()
allm = get_Messages.all()
get_Memory = Memory.objects.filter(user=user_msg).values()
allm2 = get_Memory.all()
c = {"models_to_return": list(allm)}
d = {"memory_return": list(allm2)}
return JsonResponse([c, d], safe = False)
JS error:
Uncaught TypeError: Cannot read properties of undefined (reading 'memory_return')
at Object.check [as success] ((index):613:44)
at i (jquery-3.1.1.min.js:2:27983)
at Object.fireWith [as resolveWith] (jquery-3.1.1.min.js:2:28749)
at A (jquery-3.1.1.min.js:4:14203)
at XMLHttpRequest.<anonymous> (jquery-3.1.1.min.js:4:16491)
I am currently doing ajax with django.
However, the response throws an error.
I send a request to the views using ajax and create a model.
And now we ’re ready to create.
I think there is a problem with the return of views.
The error message I get
fail 200
(index):150 parsererror
(index):151 SyntaxError: Unexpected token a in JSON at position 0
at parse (<anonymous>)
at Ut (jquery-3.3.1.min.js:2)
at k (jquery-3.3.1.min.js:2)
at XMLHttpRequest.<anonymous> (jquery-3.3.1.min.js:2)
The javascript code (jquery)
$('form').on('submit', function(e){
let $submit_input = $(this).find('input')
let $data = $(this).data('group')
console.log($data);
e.preventDefault();
$.ajax({
'url': "{% url 'groups:ajax_post_add' %}",
'type': 'POST',
'data': {
'group': $data,
csrfmiddlewaretoken: '{{ csrf_token }}',
},
'dataType': 'json',
beforeSend: function(xhr, settings) {
$submit_input.attr('disabled', true);
}
}).then((...args) => { // done
const [data, textStatus, jqXHR] = args;
console.log('done', jqXHR.status);
})
.catch((...args) => { // fail
const [jqXHR, textStatus, errorThrown] = args;
console.log('fail', jqXHR.status);
console.log(textStatus);
console.log(errorThrown);
})
});
The python code
#views
#require_http_methods(["POST"])
def GroupRequestAdd(request):
group_id = request.POST.get('group')
group_id = group.objects.get(id=group_id)
request_add = belong.objects.create(user=request.user,group=group_id)
return HttpResponse("ajax is done!")
In short you are returning a string of text from your django view which is not a valid JSON string; therefore your javascript cannot parse it as "valid" json.
The offending line is return HttpResponse("ajax is done!"). Instead change this to return json.
return HttpResponse(json.dumps({'status': 'ajax is done!'}))
Or, modify your jquery to handle html. This an be done by changing the line: 'dataType': 'json', to be 'dataType': 'html',.
The unexpected token you receive is coming from your python script.
Unexpected token a in JSON at position 0
So it says, that the token on position 0 is an a and is not valid JSON.
Looking at your code, you could see that that is correct since you return a string.
return HttpResponse("ajax is done!") // a is your unexpected token at position 0
The dataType property in $.ajax says to the AJAX function what kind of value to expect in the response from the server. In this case you are expecting JSON but receive a string. So the $.ajax function tries to parse the result from JSON but fails.
Change the dataType: 'json' to dataType: 'html' or dataType: 'text' and it will output your response correctly.
Check out the documentation of jQuery on how to use the dataType property.
I'm making an ajax call like this below where I'm returning a view like this
return View("Finish");
This has the entire html page as a string as the response, so I want to replace the page with it, but when I do I receive an error
Unhandled exception at line 82, column 3 in https://localhost:44368/Scripts/jquery-3.1.1.js
0x800a138f - JavaScript runtime error: Unable to get property 'appendChild' of undefined or null reference occurred
Funny thing is it does set the html so I see the correct page on screen, I just see the exception in JQuery as well!
var options = {
url: scope.enumControllers.saveEvent,
type: "post",
data: viewModel
};
$.ajax(options)
.done(function(response) {
if (response.error === true) {
yb.base.eventAlert(response.message, "error");
} else {
$("html").html(response); // error here trying to set the page to the response html string
}
})
.always(function() {
})
.fail(function(jqXHR, textStatus) {
yb.base.eventAlert("Error saving data. Please contact the help desk.", "error");
});
My ajax call looks like this:
$.ajax({
url: self.options.base_url + '/interface/jsonp/auth_user/',
dataType: 'jsonp',
success: function (data) {
self._after_user_auth(data);
},
error: function () {
self._service_unavailable()
}
});
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html>
<head>
<title>Unhandled Exception</title>
</head>
<body>
<h1>Unhandled Exception</h1>
<p>An unhandled exception was thrown by the application.</p>
</body>
</html>
And if there is some error on server-side I get the next response
which rises Uncaught SyntaxError: Unexpected token <
Is it possible to catch that on the client?
I'm not sure I understand you, but you can catch JavaScript error with
try{}catch(){}:
$.ajax({
url: self.options.base_url + '/interface/jsonp/auth_user/',
dataType: 'jsonp',
success: function (data) {
try{
self._after_user_auth(data);
}catch(err){
console.log(err); //catch is fired if inside try js find an error.
}
},
error: function () {
self._service_unavailable()
}
});
catch(err) - err is an object that contain all error information.
some documentation: Try catch
$.ajax({
url: '../api/notifications/deleteNotification?userId=' + userId + '¬ificationId=' + notificationId,
type: 'DELETE',
success: function()
{
CreateNotificationTree(userId);
alert('Delete successful.');
},
failure: function()
{
alert('Delete failed.');
}
});
The function CreateNotificationTree(userId); that is inside the success function of the ajax call above DOES fire. However, the Alert is not firing after. Does anybody know why? I have tried to use multiple browsers as well.
EDIT - found out I'm running into this error when the AJAX call executes:
Uncaught TypeError: Cannot read property 'uid' of undefined kendo.web.min.js:23
(anonymous function) kendo.web.min.js:23
p.extend.each jquery.min.js:2
p.fn.p.each jquery.min.js:2
g.extend._attachUids kendo.web.min.js:23
g.extend.init kendo.web.min.js:22
(anonymous function) kendo.web.min.js:9
p.extend.each jquery.min.js:2
p.fn.p.each jquery.min.js:2
$.fn.(anonymous function) kendo.web.min.js:9
CreateNotificationTree NotificationsTreeView.js:17
(anonymous function) NotificationsTreeView.js:60
k jquery.min.js:2
l.fireWith jquery.min.js:2
y jquery.min.js:2
d
Log the error to your console.
You do not see the alert if ajax fails method as jQuery does not identify the failure method.
Use a error callback to log the error.
Also use console.log instead of alert which is annoying and stops the flow of execution
failure: function(){
alert('Delete failed.');
}
supposed to be
error: function(){
alert('Delete failed.');
}
And use done and fail instead of success and error callbacks as the latter as deprecated as of version 1.8
$.ajax({
url: '../api/notifications/deleteNotification?userId='
+ userId + '¬ificationId=' + notificationId,
type: 'DELETE'
}).done(function () {
CreateNotificationTree(userId);
console.log('Delete successful.');
}).fail(function (jqXHR, status, error) {
console.log("Error : " + error);
});
Use the arguments that are passed to the callbacks and you ll be able to pinpoint the error.