Ajax call is throwing an Invalid Character error - javascript

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.

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 },

TypeScript : Ajax call call always calling Error rather than success on success

In typescript I have a DataAccess Class so that all Ajax calls are routed through a single object to save repetition of code in a lot of places within my application.
In using this approach I have needed to use call backs to get the response back to the calling class so that the success and error can be handled accordingly.
This is the typescript
ajaxCall(retVal, retError) {
$.ajax({
type: this.callType,
data: this.dataObject,
dataType: this.dataType,
url: this.url,
contentType: this.contentType,
traditional: this.traditional,
async: this._async,
error: retError,
success: retVal
});
}
This is the compiled Javascript
AjaxDataAccessLayer.prototype.ajaxCall = function (retVal, retError) {
$.ajax({
type: this.callType,
data: this.dataObject,
dataType: this.dataType,
url: this.url,
contentType: this.contentType,
traditional: this.traditional,
async: this._async,
error: retError,
success: retVal
});
};
return AjaxDataAccessLayer;
This calls through to the ASP.Net MVC controllers perfectly fine, however the problem that I have is regardless of Success or Error the call back is always retError.
This is the calling Typescript
var _this = this;
var dataAccess = new DataAccess.AjaxDataAccessLayer(Fe.Upsm.Enums.AjaxCallType.Post,
Fe.Upsm.Enums.AjaxDataType.json,
"../../PrintQueue/DeletePrintQueueItems",
jsonObj);
dataAccess.ajaxCall(data => {
// success
new Fe.Upsm.Head().showGlobalNotification("Selected Items Deleted");
_this.refreshPrintQueueGrid();
(window as any).parent.refreshOperatorPrintQueueCount();
}, xhr => {
// failure
alert("An Error Occurred. Failed to update Note");
});
When stepping through and looking at this the Status is OK and the response is 200.
So, Problem (as mentioned above) always calling xhr \ retError regardless of success.
Question: How do I get it to go into the right call back?
In your error handler, you were not passing all the parameters, so you are only checking whether the request finished successfully. However, there can be errors after that, like when the response is processed. You can handle errors betters like this:
dataAccess.ajaxCall(data => {
// success
new Fe.Upsm.Head().showGlobalNotification("Selected Items Deleted");
_this.refreshPrintQueueGrid();
(window as any).parent.refreshOperatorPrintQueueCount();
}, (xhr, errorText, errorThrown => {
// failure
console.log(xhr, errorTest, errorThrown);
alert("An Error Occurred. Failed to update Note");
});
Based on the discoveries using this method, the error is that your controllers are returning empty responses, so you're getting an exception when jQuery tries to parse them, because an empty string is not valid JSON.

How to pass safely text with URLs as a parameter to a CodeIgniter controller?

I'm trying to send from JavaScript, by using jQuery, via AJAX, a string that might contain one or more URL's.
That text will be recieved by a CodeIgniter controller.
I'm having some errors. Sometimes it's a 404 error or other times is a 406 error depending on the way I send the data.
Right now I send it like this:
var dsPost = encodeURIComponent(base64_encode(postContent));
$.ajax({
url: "/posts/createTextPost/" + dsPost,
type: "POST",
data: "userIdWall" + "=" + userIdWall,
success: function(data, textStatus, jqXHR) {
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
The base64_encode fn is the phpjs implementation.
In the CI controller I do this:
public function createTextPost($dsPost) {
$dsPost = base64_decode(urldecode($dsPost));
}
The thing is, the data can be saved to the database but I can't understand why the 404 error.
Any ideas?
Thanks.
base64_encode() function sometimes add / in encoded string so the Codeigniter action method behaving like second paramameter
In case Encoded String like: qwqw221#1223/dds*(ewfd)
than issue with ci
string part after "/" char behaving like 2nd param
'*' is not allowed char
So you should use GET query string instead of CI param
Like
url: "/posts/createTextPost/?crypt=" + dsPost
And get query sting in CI controller action
public function createTextPost() {
$dsPost = base64_decode(urldecode($this->input->get("crypt")));
}
I would recommend to add the dsPost to your data in the AJAX call, instead of adding it as a parameter to the url:
$.ajax({
url: "/posts/createTextPost/",
type: "POST",
data: { "dsPost": dsPost, "userIdWall", userIdWall },
success: function(data, textStatus, jqXHR) {
// Yippie!
},
error: function (jqXHR, textStatus, errorThrown) {
// Bhuhuhu....
}
});
...and then update your CI controller to work with the posted object instead of the input parameter:
public function createTextPost() {
$dsPost = base64_decode( urldecode( $this->input->post('dsPost') ) );
userIdWall = $this->input->post('userIdWall');
}
You have to send the content through ajax data like below.
$.ajax({
//double check your url setting in this way in case you have diffrent setting for index.php then remove the index.php
url: "<?=base_url()?>.index.php/posts/createTextPost/",
type: "POST",
data: {
"dsPost": dsPost,
"userIdWall", userIdWall
},
success: function(data, textStatus, jqXHR) {
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
then in your controller
public function createTextPost() {
$dsPost = base64_decode( urldecode( $this->input->post('dsPost') ) );
$userIdWall=$this->input->post('userIdWall');
I hope it will help.
So, thanks for the ideas but the answer can be found here:
PHP/Apache Error:406 Not Acceptable
I quote the answer given there:
Your website is generating error if any user input item is starting
with either http:// or https:// .
When I try with a link starting with http:// I got a 406 Not
Acceptable :
http://onkore.us/?blah=http://www.google.com
It is fine when I try this :
http://onkore.us/?blah=www.google.com

Uncaught TypeError: Cannot use 'in' operator to search for '' in JSON string

I've use token input in my website, and here's how I initialize the token input:
$(document).ready(function () {
var populateValue = document.getElementById('<%= hiddentokenPrePopulate.ClientID%>').value
$("#<%= tokenEmployee.ClientID%>").tokenInput("../Employee/getEmployeeDetails.ashx", {
deleteText: "X",
theme: "facebook",
preventDuplicates: true,
tokenDelimiter: ";",
minChars: 3,
tokenLimit: 1,
prePopulate: populateValue
});
});
The script was stuck on this line:
prePopulate: populateValue
When I remove this line, there won't be any javascript error, but I need this as I need to pre-populate the token input. The populateValue is:
[{
"id": "11566",
"name": "Smith - White"
}]
There was a javascript error:
Uncaught TypeError: Cannot use 'in' operator to search for '47' in [{"id":"11566","name":"Smith - White"}]`
How can I fix this error?
You need to parse the string in your populateValue variable to an object:
prePopulate: $.parseJSON(populateValue)
Or alternatively, in plain JS:
prePopulate: JSON.parse(populateValue)
You may get this error if you are using a string as an array. Say that if you got a json from an ajax, and you forgot to parse the result, and using the result as an array. The remedy is as above, to parse the json before using it.
Your server side code means .CS page where you have written your WebMethod, should always return .ToList() means array of json
Here is my .CS page code:
WebMethod
public static string PopulateDetails(Guid id){
var prx = new ProductProxy();
var result = prx.GetFirstorDefault(id); // this method is having List<ClassObject> return type
return JsonConvert.SerializeObject(result);
}
Then in my jQuery post method:
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "Productjq.aspx/PopulateDetails",
data: JSON.stringify({id: id}), // This is Id of selected record, to fetch data
success: function(result) {
var rspns = eval(result.d); // eval is used to get only text from json, because raw json looks like "Id"\"1234"
$.each(rspns, function() {
$('#<%=txtProductName.ClientID %>').val(this.Name);
});
},
error: function(xhr, textStatus, error) {
alert('Error' + error);
}
});
I was getting this error as well.
C# Api returning Serialized Dictionary data.
return JsonConvert.SerializeObject(dic_data);
return new JavaScriptSerializer().Serialize(dic_data);
Kept on getting this error message, until i just returned the Dictionary data directly without trying to Serialize
return dic_data;
No more errors on the browser side. Not sure why.

Categories

Resources