Sending a variable from JavaScript to Java - javascript

I've created a game that collects a User's time on the browser with JavaScript. What I'd like to do is grab that JavaScript data and send it to the backend, which is written in Java (I'm using a local server running on Tomcat). How can I accomplish this?
I've looked into AJAX and here is what I've come up with...
var myTime = // however long it took for user to win game
var data = {}
data["myTime"] = myTime;
$.ajax({
type : "POST",
url : "/path-to/hosting/save",
data : JSON.stringify(data),
dataType : 'json',
timeout : 100000,
contentType:'application/json',
success : function(data) {
console.log("SUCCESS: ", data);
},
error : function(e) {
console.log("ERROR: ", e);
},
done : function(e) {
console.log("DONE");
}
});
When I finish the game, I receive this error on the console:
statusText:"parsererror"
My initial thought was that I didn't form my JSON correctly, but I am not sure. Any help would be appreciated. Thanks in advance!

As your code it seems like myTime is a single value why you store it in array you can pass that as follows
var myTime = // however long it took for user to win game
//var data = {}
//data["myTime"] = myTime;
$.ajax({
type : "POST",
url : "/path-to/hosting/save",
data : JSON.stringify({
'myTime': myTime
}),
dataType : 'json',
timeout : 100000,
contentType:'application/json',
success : function(data) {
console.log("SUCCESS: ", data);
},
error : function(e) {
console.log("ERROR: ", e);
},
done : function(e) {
console.log("DONE");
}
});

Related

How to solve error parsing in dataTables?

I have a function button that carry user info fullname, after clicking the button, it will send fullname and level to an API to be process and the result should be display in dataTable. Unfortunately, I got this error.
This is console.log for console.log(params). {"task_level":3,"fullname":"Administrator"}
Below is console.log for console.log(params).
Both console log is similar to API's result.
I don't know which is proper.
JS 1st Try (1st Ajax to send the parameter to API and after return success hopefully working but not.
"<button type='button' class='btn btn-dark btn-round' onclick='viewTablePerson(""+value.fullname+"")'>View Project</button>"+
function viewTablePerson(fullname){
var level = 3;
var fullname2 = fullname;
var obj = {
task_level : level,
fullname : fullname2
};
var params = JSON.stringify(obj);
console.log(params)
$.ajax({
url : url_api + '/api/user_task',
crossDomain: true,
type : 'POST',
dataType : 'json',
data: params,
success: function(response){
if (response.status == "Success"){
console.log(response)
$('#viewProgress').DataTable({
ajax: {
url: url_api + '/api/user_task',
crossDomain : true,
type : "POST",
cache : false,
dataType : "json",
contentType: false,
processData: true,
data : params,
timeout: 10000,
},
destroy: true,
columns: [
{ data : "task_name"},
{ data : "task_owner"},
{ data : "task_status"}
],
});
}
},
error: function(e){}
});
}
JS 2nd Try
<button type='button' class='btn btn-dark btn-round' onclick='viewTablePerson(""+value.fullname+"")'>View Project</button>"+
function viewTablePerson(fullname){
var level = 3;
var fullname2 = fullname;
var obj = {
task_level : level,
fullname : fullname2
};
var params = JSON.stringify(obj);
console.log(params)
$('#viewProgress').DataTable({
ajax: {
url: url_api + '/api/user_task',
crossDomain : true,
type : "POST",
cache : false,
dataType : "json",
contentType: false,
processData: true,
data : params,
timeout: 10000,
},
destroy: true,
columns: [
{ data : "task_name"},
{ data : "task_owner"},
{ data : "task_status"}
],
});
}
Documentation says:
When using the ajax option to load data for DataTables, a general error can be triggered if the server responds with anything other than a valid HTTP 2xx response.
So, you have to check server-side response instead of search for problems on the front-end.
Also, in your case make sure
the plugin sends request to the same domain from which the current page is loaded;
browser security system doesn't prevent loading of external scripts - for example on http://localhost you cannot Ajax load a script from http://google.com without special measures;
you are specifying a relative path without a domain name (if you are using a single domain);
JSON data in response is a valid.
If you cannot alter the backend system to fix the error, but don't want your end users to see the alert message, you can change DataTables' error reporting mechanism to throw a Javascript error to the browser's console, rather than alerting it:
$.fn.dataTable.ext.errMode = 'throw';

How to send js variable to Spring controller?

I have this html code
<button onclick="var pdata = $('textarea').froalaEditor('html.get');">Submit article</button>
So I want to send this pdata variable to controller. How do I do this? Or should I use a form?
If you already use jQuery, consider the jQuery.post() method.
$.post("controller/path", pdata)
.done(function(response) {
comsole.log("Response: " + response);
});
You could move this code to a function, for example, like this:
<button onclick="submitArticle()">Submit article</button>
and in JS:
function submitArticle() {
var pdata = $('textarea').froalaEditor('html.get');
$.post("controller/path", pdata).done(function(response) {
comsole.log("Response: " + response);
});
}
Note that according to jQuery docs your pdata should be
A plain object or string that is sent to the server with the request.
$("#button").click(function(){
$.ajax({
type : "POST",
url :"url",
data : {id: $("#field").val()},
timeout : 100000,
success : function(response) {
alert(response);
},
error : function(e) {
console.log("ERROR: ", e);
display(e);},
done : function(e) {
console.log("DONE");
}
});
Hey here is working example of post action ajax+jquery
consider one textfield and one button for example
MyButton
see following ajax call:
function updatData() {
var value= $("#sample").val();
$.ajax({
type : "POST",
url :"url",
data : {id:value},
timeout : 100000,
success : function(response) {
alert(response);
},
error : function(e) {
console.log("ERROR: ", e);
display(e);},
done : function(e) {
console.log("DONE");
}
});
}

Why is my AJAX error not returning my Webmethod exception?

I'm using google chrome for my work.
Following https://stackoverflow.com/a/26003200/7204173 I tried to return an exception from webmethod. But it does not show anything in the console.log. The only thing I got is from network tab the generic error message below :
"An error occurred while updating the entries. See the inner exception for details."
So what I tried is below (ps : I'm sending DML a database using entity framework DbContext) :
public string AddData(myEntity e)
{
using(var context = new MyEntityModel())
{
try
{
context.myEntity.Add(e);
context.SaveChanges();
return "success";
}catch(Exception ex)
{
return "error : " + ex.Message;
}
}
}
Now my Javascript code :
function AddArticle()
{
var e {id : "1", value : "test"};
var DTO = { 'e': e };
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(DTO),
url: "MyPage.aspx/AddData",
success: function (response) {
console.log(response);
},
error: function (xhr, status, error) {
var exception = JSON.parse(xhr.responseText);
alert(exception.Message);
console.log(exception.Message);
}
});
}
So let's say I put it a call a the javascript function behind an input button. Since it is a database, the var e {id : "1", value : "test"}; can't be added twice since id is a primary key. Still I get nothing in the console.log ; the alert box does not even get triggered. But when it succeeds, the console.log displays success as expected.
Any idea of where I shoud be looking for to find my error ?
Have you try to log the others errors args ?
console.log(xhr);
console.log(status);
console.log(error);
You should be able to parse manually logs in the console and find the right path to the variable you want.
Update
console.log(error); was the answer in the case of OP

Jquery filer.js Ajax request not sending updated variable value

so Ive got this jquery plugin which is sending an ajax request to a php file with a variable attached.
However the variable attached to data{type:filetype} is being changed on the page. When the user submits the request to be sent, the new value of the filetype is not being sent.
Any idea why ?
The filetype variable is a global variable :
<script type="text/javascript">
var filetype = "";
</script>
This is the plugin being initiated :
$('#filer_input1').filer({
uploadFile: {
url: "php/fileupload/upload.php",
data: {order:19,
type:filetype},
type: 'POST',
enctype: 'multipart/form-data',
beforeSend: function(){
console.log(filetype);
},
success: function(data, el){
console.log(data);
console.log(el);
},
error: function(el){
},
statusCode: null,
onProgress: null,
onComplete: null
}
}
function which updates the variable :
function setFileType(x){
var text = $("#"+x).html() + ' <span class="caret"></span>';
$("#fileTypeSelect").html(text);
filetype = x;
}
Any help would be greatly appreciated

SyntaxError:JSON.parse:unexpected character at line 1 column 1 of the JSON data

I've been looking all over for the solution but I cannot find anything that works,I keep getting the following error,I have a submit event that will call the function SUValidation with the data thats being
submitted through a text box in php form,I have tried putting contentType: "application/json",//note the contentType defintion looking at other posts but nothing helped..can anyone provide guidance on how to debug this error or at the best provide a solution
Error:-
SyntaxError:JSON.parse:unexpected character at line 1 column 1 of the JSON data
RESPONSE OF SUVALID.py
Just outputs the content of the python script
Hi,
submit event:-
$("#su_validation").submit(function(event) {
console.log("su_validation.submit");
event.preventDefault();
//SUValidation('#su_validation', '#su_validation_table', '#gerrits_su_validation', showDialog, "#su_validation_dialog");
$("#SUValidation_su_validation_table").empty();
var data = { 'product_lines' : [], 'gerrits' : [], 'contacts' : []};
//find all pl's that are checked
data['product_lines'] = ($("#product_line_su_validation").val()).split(",");
data['gerrits'] = ($("#gerrits_su_validation").val()).split(",");
data['contacts'] = ($("#contacts_su_validation").val()).split(",");
console.log(data);
SUValidation(data, '#SUValidation_su_validation_table', '#gerrits_su_validation', "su_validation_form");
});
Function call:-
function SUValidation(data, table_name, gerrit_form, caller) {
console.log("su_validation_form");
console.log(data);
//console.log($(form_name).find('input, select, textarea').serialize());
su_validation_return = null;
//if maintained, we care if they are in ODS
//if not maintained, we don't really mind if they aren't in ODS database
var maintained = null;
console.log("start when");
$.when(
$.ajax({
dataType: "json",
type: "POST",
url: "scripts/suvalid.py",
timeout: 180000,
data: JSON.stringify(data),
success : function(response){
su_validation_return = [];
console.log("python");
console.log(response);
....
}
}
},
error: function (xhr, ajaxOptions, thrownError) {
console.log("error");
//alert(xhr.status);
alert(thrownError);
}
})
).then(function() {
console.log("THEN");
var gerrits = data['gerrits'];
console.log(su_validation_return);
var valid_gerrits = true;
..................

Categories

Resources