I can't solve this "parsererror" ajax error - javascript

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.

Related

JSON Parse error when submitting AJAX post to Spring Boot Controller using Thymeleaf

I have a form that I am submitting using AJAX:
var formData = JSON.stringify($('#supportrequest').serializeArray());
$.ajax({
type: "POST",
url: "/updatesupportrequest?bugid=" + $('#requestnum').val(),
data: formData,
success: function(){
console.log("success");
},
error: function(xhr, status, error) {
console.log(xhr);
console.log(status);
console.log(error);
},
complete: function(){
console.log("complete");
},
dataType: "json",
contentType : "application/json"
});
This is picked up by my Spring Boot controller:
#PostMapping("/updatesupportrequest") // Called by the form
public String createSupportRequest(#RequestParam(name = "bugid") int bugid, #RequestBody String requestBody,
Model model) {
System.out.println(bugid);
DatabaseWriteResponse response = writeToDatabaseService
.writeToDatabase(WriteToDatabaseService.PROCEDURE_UPDATESUPPORTREQUEST, requestBody);
System.out.println(response.getResponse());
if (response.getResponse().equals(DatabaseWriteResponse.SUCCESS)) {
return "supportrequest";
}
else {
model.addAttribute("response", response.getResponse());
model.addAttribute("errorMsg", response.getMsg());
return "error";
}
}
The actual saving of the data works just fine. The problem is that the controller returns the "supportrequest.html" page. AJAX then throws a parse error:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
Looking at the xhr.responseText, we get the page back:
responseText: "<!--\r\n TODO\r\n - Dev page has some different fields \r\n\r\n\r\n -->\r\n\r\n<!DOCTYPE HTML>\r\n<html>\r\n<head>\r\n<title>Support Center</title>\r\n<meta http-equiv=\"Content-Type\" content=\"text/html;
I either need the page to redirect properly (which works fine on Get, just not Post) or to be able to return an empty JSON string and trigger the AJAX success function. I don't particular care which - I can handle the result either way. I just can't get either option to work. What am I doing wrong?
If you want to return JSON in a #Controller class, then annotate the return type of the method with #ResponseBody.

Data is empty when passing a variable from JS to PHP with Ajax

I'm trying to pass a simple string variable with an onclick event, the request is successful but I get an empty response on the console, and the xvar variable is no coming through so I get the "NO DATA" p tag. This is my first time using Ajax so I tried to make it very simple to start. Here's my code:
JS
var xvar = 'D';
$('.test').click( () => {
$.ajax({
data: { xvar : xvar },
type: "POST",
url: 'test.php',
success: function(data, textStatus, XMLHttpRequest)
{
console.log('Success: '+data)
},
error: function(XMLHttpRequest, textStatus, errorThrown){
console.log("The request failed."+errorThrown);
}
});
});
test.PHP
$xvar = (isset($_POST['xvar'])) ? $_POST['xvar'] : '<p>NO DATA</p>';
echo $xvar;
I'm using JQuery 3.5.1 that is included with Wordpress. I'll appreciate any feedback.
EDIT
I managed to get the response on test.php as seen
here:
But I when I try to render the value with print_r is not shown.
$res = $_POST;
print_r($res);
On the data of your Ajax, try to add the quotes in the key of the data. Like this:
data: { "xvar" : xvar },

Ajax call is throwing an Invalid Character error

I am working on a Java application using Struts 1.2. I am facing a blocking error when I make an AJAX call to a Struts action.
The struts action, getInfos.html, is called successfully but after that when I make the AJAX call I get the following error in the console:
Invalid Character/parsing error
The data variable is a correct JSON format. Why would it trigger this error?
I've gone through all the similar questions online but I don't know why it's triggering an invalid character error.
$.ajax({
type: "POST",
url: "getInfos.html",
dataType: "json",
async: false,
cache: false,
data: {
Code: "code1",
type: "type",
mand: "mand",
signature: "signature"
},
success: function(data) {
console.log('succes');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log('my error is : ' + errorThrown);
}
});
In the execute method that is handling the ajax request, i am calling the attributes using the request
final String code = (String) request.getAttribute("code");
final String signature = (String) request.getAttribute("signature");
final String type= (String) request.getAttribute("type");
/*
Making a call to a webservice using the attributes bellow,
using **response** Object
*/
if (reponse != null &&
(CodeReponseHttp.OK.equals(reponse.getCodeReponse()))) {
jsonObj.put(SUCCESS_CALL, true);
} else {
jsonObj.put(SUCCESS_CALL, false);
}
return new JsonResult(jsonObj);
But they are set to null; which means that the ajax data is not passed into the request, when I debug the execute method and I explicitly set values to these attributes everything works fine.
new JsonResult(jsonObj) is a generic class with a constructor that accepts a JSONObject
Like Rory McCrossan Comment it could be the response you got is not a json and your code expect a json response
When i comment dataType param it work fine
$.ajax({
type : "POST",
url : "getInfos.html",
//dataType : "json",
async: false,
cache: false,
data: JSON.stringify({
Code : "code1",
type : "type",
mand : "mand",
signature : "signature"}),
success : function(data){
console.log('succes');
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
console.log('my error is : ' + errorThrown);
}
});
The problem had been solved, after debugging, the response type was not a JSON since there is a redirection to an error page if an exception is thrown, the exception was thrown because the data attributes were null, and it turned out that they are parametres not attributes, so getting the parameters solved the problem.
request.getParameter("code");
thank you all for your collaboration.

Getting an AJAX GET request to work with Express.js

I am using node.js and Express.js on the back end, and am trying to make a server call from the client via AJAX.
So I have this POST request that works fine with AJAX:
node.js/Express.js:
app.post('/createNewThing', function(req, res) {
var userInput = req.body.userInput;
if (userInput) {
res.send('It worked!');
}
});
Client Side/AJAX request:
var userInputForm = $('#userInputForm.val()')
$.ajax({
url: "/createNewThing",
type: "POST",
data: "userInput=" + userInputForm,
dataType: "text",
success: function(response, status, http) {
if (response) {
console.log('AJAX worked!);
}
}
});
The userInputForm comes from an HTML form.
This POST request works fine. But I want to change this to a GET request. If I change app.post to app.get, and change type in the AJAX call to GET, I get this 500 error:
GET /createNewThing?userInput= 500
When you make a GET request, the data appears in the query string (of the URL in the request headers). It doesn't appear in the request body. There is no request body.
When you try to read from the request body, you are trying to access a property of an undefined object, which triggers an exception and cause an internal server error.
This answer explains how to read a query string:
var id = req.query.id; // $_GET["id"]
So
var userInput = req.query.userInput;
I think var userInputForm = $('#userInputForm.val()') will get error or get wrong data..This may be the reason for the error. Due to userInputForm may not be a string and concatenate with userInput=
Actually it is bad data.
And for the data in ajax, you should modify data from data: "userInput=" + userInputForm,
to:
data: {
userInput: userInputForm
},
dataType: "json"
And var userInputForm = $('#userInputForm.val()')
to var userInputForm = $('#userInputForm').val();
At last, you could modify as bellow, I believe it works:
var userInputForm = $('#userInputForm').val();
$.ajax({
url: "/createNewThing?userInput=" + userInputForm,
type: "GET",
success: function(response, status, http) {
if (response) {
console.log('AJAX worked!);
}
}
});

JSON, Syntax error : unexpected token I(...)

I've a such js-function, which sends data to file, which contains a function, which sends back JSON-response:
function deleteCategory(id){
console.log(id);
$.ajax({
url: '<?php echo $cfg['options']['siteurl']; ?>/gears/ajax.deletePkgCatAsideMenu.php',
type: 'POST',
dataType: 'JSON',
data: {idItem:id},
success: function(data) {
console.log(data);
if (data.type=='error') {
notify(data.type, data.type, data.text);
} else{
document.location.reload();
}
},
error: function(v1,v2,v3) {
alert('Ошибка!\nПопробуйте позже.');//in english it will be: alert('Error!\nTry again later.');
console.log(v1,v2,v3);
}
});
}
In the end of that file these actions take place:
$q = 'DELETE FROM `pkg_cat_aside_menu` WHERE pkg_cat_ddlist_id='.$idItem;
$db->query($q);
exit(json_encode(array('type'=>'ok','text'=>'Удаление произведено!')));
//or in english: exit(json_encode(array('type'=>'ok','text'=>'Deleted!')));
This is a response text:
"int(13) {"type":"ok","text":"\u0423\u0434\u0430\u043b\u0435\u043d\u0438\u0435 \u043f\u0440\u043e\u0438\u0437\u0432\u0435\u0434\u0435\u043d\u043e!"}"
And error syntax error: unexpected token i(...)
I think, it take place, because I did actions with data base (delete), which response a deleted record number (13), and it has been included to json-respose. How to fix it?
int(13) makes me think that you have a var_dump( $idItem ); somewhere earlier in your PHP code, which is causing the response to be invalid.

Categories

Resources