Spring DWR engine.js failing unknown error - javascript

We have a web application that is using Spring framework 5.1.7.RELEASE, JDK 1.8 and DWR 3.0.2 deployed in WAS 8.5. We have a JSP web page; that displays some statistical information to its user; web page was working fine like in years and all of a sudden it started failing to load. When we debugged the issue; we narrow it down to dwr's ajax request; and it failed in engine.js with an unknown error. What we figured; we will provide the information in answer to this question. Code snippet is below, and it continue to fail on line '3' below i.e. controllerClass.someMethod call. selectObj1 and selectObj2 are array type of objects.
if (document.getElementById("someCheckBox").checked) {
//Below controllerClass is the name of JS class produced by DWR but actually it's a Java class (i.e. object used below)
controllerClass.someMethod("Value1", selectObj1, selectObj2, 'Value2', 'Value1', function(data) {
if (data != null) {
hideView("viewOne",false); //user defined function call
fillData("viewName",data[0]); //user defined function to fill the returned data
valueRet1 = data[1];
someConst = "X";
displayNavCon(pageNumber); //user defined function to control the navigation on web page
} else {
alert("No Data Found!!!");
recordCount=0;
}
});

When it comes to DWR and it start's failing with an error in engine.js; I think DWR needs to put some improvements there. Because most of the time error is/was unknown. So in above case - we were passing some data in DWR's ajax call using selectObj1 like an array and selectObj2 like an array, how data being constructed haven't changed in years; then we noticed that there was a decimal value being passed in selectObj1 that has comma in it, we removed the comma before giving data to DWR's ajax call and Bingo! it worked. Code fix is below;
//we are omitting the construction of other object being passed in i.e. selectObj2
var indexBrkLp = 0;
if (priceVal != null){
while (priceVal.includes(",")){
indexBrkLp++;
priceVal = priceVal.replace(",", "")
if (indexBrkLp > 5){
break;
}
}
}
var selectObj1={
val2:(val2 == null? "": val2),
priceVal :(priceVal == null? "": priceVal)
};
if (document.getElementById("someCheckBox").checked) {
//Below controllerClass is the name of JS class produced by DWR but actually it's a Java class (i.e. object used below)
controllerClass.someMethod("Value1", selectObj1, selectObj2, 'Value2', 'Value1', function(data) {
if (data != null) {
hideView("viewOne",false); //user defined function call
fillData("viewName",data[0]); //user defined function to fill the returned data
valueRet1 = data[1];
someConst = "X";
displayNavCon(pageNumber); //user defined function to control the navigation on web page
} else {
alert("No Data Found!!!");
recordCount=0;
}
});
Conclusion - If you see engine.js is failing, then it might not just be something wrong in your code; it could be data that it don't like or could be some other config related to DWR.

Related

undefined result javascript

I have a simple javascript code, that validate when you write a order number and generates tags with javascript(with bootstrap-tagsinput js):
var order = $('#order_number').val();
if ($.inArray(order, $('#input_order_tags').val()) >= 0) {
$('#input_order_tags').tagsinput('add', order);
return;
}
var params = {
email: email,
order_code: order
}
AjaxServices.validateOrderNumberByEmail(params, function(error, result) {
if (error)
alert(error);
else
$('#input_order_tags').tagsinput('add', result.order);
});
This works fine but, every time trigger the error message when send a order number:
Console chrome debug:
How I can avoid the error of alert?
This is not a javascript issue. Server-side in you application you use order_code in one of the calls which returns the error message you see in the ajax call. Debug the offending call server-side, see which call returns that error and adjust your code so it works properly.
There might be two possibilities
client side issue ( javascript error) if so, its because the field order_number is disabled field.
as mentioned in this link
undefined index on javascript dynamic variables when passing to php form
If so, remove that disabled and use read-only and check if it works, without any error.
Server side issue( ajax call) if so, server side code which performs on call of that ajax call is causing that issue.

Cannot set property of undefined -- inserting text with javascript

I am currently trying to insert some text in a specific spot at a website, http://kawowii.com , however, I keep getting error messages. These error messages seem to originate from the section I am trying to select using javascript (variables txtClasses and styleClasses). The error messages are
Uncaught TypeError: Cannot set property 'textContent' of undefined
So, the variables seem to be undefined but I don't understand why. I have looked at the other answers and still cannot determine what is wrong.
Right now, I have
window.onload = function() {
var txtClasses = document.querySelectorAll("div.coord-control.leaflet-control");
txtClasses[0].textContent = "Server: UP Location:"
}
and I tried this
window.onload = function() {
var styleClasses = document.querySelectorAll(".coord-control leaflet-control");
function insertAfter1(referenceNode, newNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
var brk = document.createElement("br");
insertAfter1(styleClasses[0], brk);
var div = document.createElement("div");
var textNode = document.createTextNode("Server: UP")
div.appendChild(textNode);
insertAfter1(brk, div);
}
My end goal is to change the website, kawowii.com , such that before Location :, it reads Server: UP using javascript.
I executed document.querySelectorAll("div.coord-control.leaflet-control"); on the website you provided, and it does in fact show an array with that element.
I think div.coord-control.leaflet-control is being inserted dynamically (perhaps after an AJAX request completes).
Therefore, you need to put your controlling logic inside the callback of the request:
whateverRequestIsInsertingThatElement.then(function() {
var txtClasses = document.querySelectorAll("div.coord-control.leaflet-control");
txtClasses[0].textContent = "Server: UP Location:"
});
I don't know if you're using promises or if the async method you're using provides a callback, but onload will happen in parallel with your async request, so you need to query for the dynamic element in the callback of the async request.
Not sure which API you're using to generate the map on your website, but usually any calls for location data will happen asynchronously (like the Google Maps API, for example). You can only manipulate dynamically generated DOM elements once the data has arrived.
Edit
You can see that the client is initially getting the configuration data from the route up/configuration. I would suggest looking for where that async call is being made in your source code, and then call querySelectorAll in its success handler.
I also see that in some of your sources, $.ajax is being called, so I assume somewhere in there, $.ajax is being called to the up/configuration route on your server.
So what I imagine happening is this:
You are querying your page for a your leaflet control but its returning an array of nothing. So when you try and access txtClasses[0] its undefined (since txtClasses.length == 0).
// this illustrates your problem
try {
// I am manually creating an empty array (your results)
var txtClasses = []
// this throws the error
txtClasses[0].bad = "throws an error";
} catch (e) {
// this just displays the error for you to see
document.getElementById("log").innerHTML += e.toString()
}
<div id="log"></div>
If you are expecting something back, you should check your selector is actually working (what I like to do is open up a web console and type my code right in there).
I noticed your selector changed in the first and second example too so make sure you read more about css selectors here.

Why am I getting this Internal Server Error in the Laravel Framework?

I have come across a situation that doesn't make much sense to me. Just as some background information, I'm using the Laravel framework. The page in question calls a query when the page is requested using Laravel's '->with('var', $array)' syntax. This query (which I will post later) works perfectly fine on page load, and successfully inserts dummy data I fed it.
I call this same query via an Ajax $.post using jQuery, on click of a button. However, when I do this $.post and call this query, I get an Internal Server Error every time. Everything is exactly the same, information passed included; the only difference seems to be whether or not it is called on page load or via the $.post.
Here is the error:
Below is the code that performs the query on page load:
routes.php sends the HTTP get request to a file called AppController.php
routes.php
AppController.php
The page is then made with the following array acquired from DeviceCheckoutController.php
Which then goes to DeviceCheckout.php
I am able to echo $test on the page, and it returns the ID of a new row every time the page is reloaded (which obviously mean the 'insertGetId' query worked). However, I hooked this query up to the page load just to test. What I really want to happen is on click of a button. Here is the code for that:
$("#checkoutFormbox").on('click', '#checkoutButton', function() {
var checkoutInformation = Object();
var accessories = [];
var counter = 0;
var deviceName = checkoutDeviceTable.cell(0, 0).data();
$(".accessoryCheckbox").each(function() {
//add accessory ID's to this list of only accessories selected to be checked out
if($(this).val() == "1")
{
accessories[counter] = $(this).data('id') + " ";
}
counter++;
});
checkoutInformation['deviceID'] = $(".removeButton").val(); //deviceID was previously stored in the remove button's value when the add button was clicked
checkoutInformation['outBy'] = '';
checkoutInformation['outNotes'] = $("#checkOutDeviceNotes").val();
checkoutInformation['idOfAccessories'] = 2;
checkoutInformation['dueDate'] = $("#dueDate").val();
if($("#studentIdButton").hasClass('active'))
{
checkoutInformation['renterID'] = 0;
checkoutInformation['emplid'] = 1778884;
console.log(checkoutInformation);
$.post("http://xxx.xxx.xxx.xxx/testing/public/apps/devicecheckout-checkoutdevices", {type: "checkoutDeviceForStudent", checkoutInformation: checkoutInformation}, function(returnedData) {
alert(returnedData);
});
}
});
Which is also then routed to AppController.php, specifically to the 'checkoutDeviceForStudent' part of the switch statement:
And then back to that query that is shown previously in DeviceCheckout.php
Finally, here is my DB structure for reference:
Any explanation as for why this would be happening? Also, any Laravel or other general best practice tips would be greatly appreciated as I'm inexperienced in usage of this framework and programming overall.
Sorry for such a long post, I hope there is enough information to diagnose this problem. Let me know if I need to include anything else.
Edit: Included picture of error at the top of the page.
Everything is exactly the same, information passed included
No, it isn't. If it was exactly the same you wouldn't be getting the error you're getting.
These sorts of issues are too difficult to solve by taking guesses at what the problem might be. You need to
Setup your system so Laravel's logging errors to the laravel.log file
Setup you PHP system so errors Laravel can't handled are logged to your webserver's error log (and/or PHP's error log)
Put Laravel in debug mode so errors are output the the screen, and the view the output of your ajax request via Firebug or Chrome
Once you have the actual PHP error it's usually pretty easy to see what's different about the request you think is the same, and address the issue.
I found a resolution to my problem after some advice from a friend; much easier than I anticipated and much easier than any solution that has been offered to me here or other places.
Essentially, what I needed to do was place a try, catch clause in my model function, and then if an exception is encountered I store that in a variable, return it, and use console.log() to view the exception. Here is an example to emulate my point:
public function getUserFullname($userID)
{
try
{
$myResult = DB::connection('myDatabase')->table('TheCoolestTable')->select('fullName')->where('userID', '=', $userID)->get();
return $myResult;
}
catch(Exception $e)
{
$errorMessage = 'Caught exception: ' . $e->getMessage();
return $errorMessage;
}
}
And then on the View (or wherever your model function returns to), simply console.log() the output of your POST. This will display the results of the successful query, or the results of the Exception if it encountered one as opposed to an unhelpful Internal Server Error 500 message.

Consuming a web service using JS and HTML

I am looking to create a client browser interface which will utilise the dictionary web service at Glosbe API. The user should be able to enter a word or a phrase into an input component and submit it without the page reloading. The returned data needs to be displayed on the page in a usable format so that they are able to find and read the meanings.
I've attempted this by creating a web service through Netbeans but I'm unsure whether this is the right method. Is it as simple as creating a HTML page and using javascript to call the api for Glosbe?
Any help would be highly appreciated.
You can use an XMLHTTPRequest from javascript to poll a web service. The XHR object is great for allowing you to make a request to a page or submit a form without having to refresh the page. When the request is made, it can be done asynchronously to allow the page to continue with other events and then handle the response and update the HTML. There are tons of resources on google that can instruct you on implementing an XHR object and the proper error handling along with sample code.
As far as the returned data being displayed in a usable format, that would need to be done by your JS when the response comes back. You can parse the response for the data you want and build the appropriate HTML element through JS to update your UI.
HTML
<input type='text' id='word'>
<input type='buton' onclick='sendMessage()'>
JS
function sendMessage()
{
var XHRrequest=new XMLHttpRequest();
XHRrequest.onabort = function() {
};
XHRrequest.onloadend = function (evt) {
};
XHRrequest.onreadystatechange = function() {
if (XHRrequest.readyState == 4 && XHRrequest.status == 200) {
//parse XHRrequest.responseText for response and build object
//this is where you update your UI with an HTML element
}
else if (XHRrequest.readyState == 4 && XHRrequest.status!=0) {
console.log("Error: returned status code " + XHRrequest.status + " " + XHRrequest.statusText + "\r\n" + XHRrequest.responseText);
//error handling for failed response
}
};
XHRrequest.ontimeout = function() {
alert("Error: event timed out");
};
XHRrequest.open("POST", WEBSERVICE_URL_HERE, true);
XHRrequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
XHRrequest.send("word="+document.getElementById('word').value); \\request data goes here
}

Accessing return value from bean function using JSF 2.0 Ajax response?

I'm builiding a scheduling application using JSF 2.0 where users can add items to a calendar then edit those objects.
I'm using AJAX quite extensively to keep the page from refreshing.
The problem I am having is to get a return value from the function that is called using AJAX.
<!-- ... form to fill -->
<h:commandButton value="Insert">
<f:ajax execute="formField1 formField2..."
listener="#{myBean.insert()}" onevent="processSave"/>
</h:commandButton>
This successfully calls my JavaScript function processSave().
myBean.insert() returns the id of the newly inserted row in the database
public String insert() {
//... inserting data into database
id = {id from database is obtained here}
System.out.println("I have the ID here : " id); //this works
return id;
}
I've been trying to get this from the response object within JavaScript in the processSave() function.
processSave(data) {
if(data.status == "begin") {
// ation done here
} else if(data.status == "complete") {
// more actions done here
} else if(data.status == "success") {
//I am trying to get the ID here
//I've tried looking into data.responseXML, but to no avail.
}
}
Is what I am trying possible using the current technologies?
I think it would be possible to have a field in the page updated using the render component of the AJAX call, then use Javascript to go get the value. But I'm thinking this wouldn't be as clean?
Thank you!
It is possible. And more easily done with primefaces.
Follow this example, you may find something useful there.

Categories

Resources