How to display additional info on mouseover with ajax and javascript - javascript

I have an e-commerce simulation web app for buying movies and I want a popup small window to appear when a user mouses over the movie's id and display info and give them the option to add that movie to their cart (like how Facebook displays users info when you mouseover one of your friend's names). I have a java servlet that receives the movie's id and gets the proper info from my database and sends it back to the JSP, but form there I don't know how to properly use AJAX or jquery to display the window with the proper info.
SERVLET CODE
int movie_id = Integer.parseInt((String) request.getParameter("movie_id"));
StringBuilder query = new StringBuilder("select * from movies where movies.id =");
query.append(movie_id);
// Perform the query
MySQLHandler sql_handler = new MySQLHandler( );
sql_handler.execute_query( query.toString() );
ResultSet result = sql_handler.get_result();
try {
Movie movie = createMovie(result);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(movie.getTitle());
request.setAttribute("movie", movie);
}
catch(SQLException e) {
e.printStackTrace();
}
}
JAVASCRIPT CODE
function ajaxFunction(movie_id){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
alert(ajaxRequest.responseText);
}
}
alert(movie_id);
var parameter = "movie_id=" + movie_id;
ajaxRequest.open("POST","MoviePopUpWindowServlet", true);
ajaxRequest.setRequestHeader("Content-type"
, "application/x-www-form-urlencoded") //Needed for post request for some reason. //http://www.javascriptkit.com/dhtmltutors/ajaxgetpost2.shtml
ajaxRequest.send(parameter);
}

$.ajax({
url: 'route/to/videoinfo' + specificVideoId,
type: "POST",
contentType: "application/json ;charset=UTF-8",
}).done(function(result){
(if you rendered out the html already just do)
var containerDiv = document.getElementById("#idOfDivToFill")
containerDiv.innerHTML = result
}).fail(function(err){
console.log(err)
})
Someone let me know if this is terrible.

Related

Global Javascript variable from AJAX JSON request

Hi i am using this code for my AJAX JSON request but for some if i try to make jsonObj a global variable and console.log() it always comes up as undefined in the debugger console
To clarify my question, how can I retrieve a global variable from an AJAX JSON request
function loadJSON() {
var data_file = "https://www.tutorialspoint.com/json/data.json";
var http_request = new XMLHttpRequest();
try {
// Opera 8.0+, Firefox, Chrome, Safari
http_request = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
http_request.onreadystatechange = function() {
if (http_request.readyState == 4) {
// Javascript function JSON.parse to parse JSON data
var jsonObj = JSON.parse(http_request.responseText);
// jsonObj variable now contains the data structure and can
// be accessed as jsonObj.name and jsonObj.country.
document.getElementById("Name").innerHTML = jsonObj.name;
document.getElementById("Country").innerHTML = jsonObj.country;
}
}
http_request.open("GET", data_file, true);
http_request.send();
}
<h1>Cricketer Details</h1>
<table class="src">
<tr>
<th>Name</th>
<th>Country</th>
</tr>
<tr>
<td>
<div id="Name">Sachin</div>
</td>
<td>
<div id="Country">India</div>
</td>
</tr>
</table>
<div class="central">
<button type="button" onclick="loadJSON()">Update Details </button>
</div>
The best way to approach this is by using what's called a callback function. A callback function is a function that is invoked when specific event takes place. In your case that event is the data being retrieved from your JSON endpoint (URL).
The proper way to do this is to create a function that will be called when your data is received and will then carry out the remaining logic. If you want to make that data also accessible globally, part of the callback function can update your global variable.
In the updated code below we first declare a global variable globalJSON that holds our data. Before you receive any data (i.e. before you click the button) the value of globalJSON.data will be null. Once the data is received the callback function updateView() is called with the received data. Inside of updateView() we update the global variable globalJSON.data and carry out the remaining logic (i.e. updating the required HTML elements).
You can then use globalJSON.data anywhere else in your code to get the data received when Update Details button was clicked.
// declare your global variable that will get updated once we receive data
var globalJSON = {
data: null
}
// this gets executed the moment you load the page - notice the value is null
console.log(globalJSON.data);
// this gets executed AFTER you receive data - notice call to updateView() inside AJAX call function
function updateView(data) {
// this will update the value of our global variable
globalJSON.data = data;
// this is the rest of the logic that you want executed with the received data
document.getElementById("Name").innerHTML = data.name;
document.getElementById("Country").innerHTML = data.country;
// this will show that the global variable was in fact updated
console.log(globalJSON.data);
}
function loadJSON() {
var data_file = "https://www.tutorialspoint.com/json/data.json";
var http_request = new XMLHttpRequest();
try {
// Opera 8.0+, Firefox, Chrome, Safari
http_request = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
http_request.onreadystatechange = function() {
if (http_request.readyState == 4) {
// Javascript function JSON.parse to parse JSON data
var jsonObj = JSON.parse(http_request.responseText);
updateView(jsonObj);
// jsonObj variable now contains the data structure and can
// be accessed as jsonObj.name and jsonObj.country.
}
}
http_request.open("GET", data_file, true);
http_request.send();
}
<h1>Cricketer Details</h1>
<table class = "src">
<tr><th>Name</th><th>Country</th></tr>
<tr><td><div id = "Name">Sachin</div></td>
<td><div id = "Country">India</div></td></tr>
</table>
<div class = "central">
<button type = "button" onclick = "loadJSON()">Update Details </button>
</div>
If you just want to access jsonObj from outside of the event handler, explicitly place it on the global scope (regardless of whether this is a good idea) you could create jsonObj on window by window.jsonObj = JSON.parse(http_request.responseText);
But you won't have any way of knowing when it's defined outside of the event handler. However, it would fulfill your requirement of being able to console.log(window.jsonObj) (presumably from the developer console). Also you could just console.log(jsonObj) in the eventhandler if you wanted to see the value.
full code:
<html>
<head>
<meta content = "text/html; charset = ISO-8859-1" http-equiv = "content-type">
<script type = "application/javascript">
function loadJSON(){
var data_file = "http://www.tutorialspoint.com/json/data.json";
var http_request = new XMLHttpRequest();
try{
// Opera 8.0+, Firefox, Chrome, Safari
http_request = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
http_request.onreadystatechange = function(){
if (http_request.readyState == 4 ){
// Javascript function JSON.parse to parse JSON data
// if you want to be able to access this property from the developer console
window.jsonObj = JSON.parse(http_request.responseText);
// if you just want to see the value
console.log(JSON.parse(http_request.responseText));
// jsonObj variable now contains the data structure and can
// be accessed as jsonObj.name and jsonObj.country.
document.getElementById("Name").innerHTML = jsonObj.name;
document.getElementById("Country").innerHTML = jsonObj.country;
}
}
http_request.open("GET", data_file, true);
http_request.send();
}
</script>
<title>tutorialspoint.com JSON</title>
</head>
<body>
<h1>Cricketer Details</h1>
<table class = "src">
<tr><th>Name</th><th>Country</th></tr>
<tr><td><div id = "Name">Sachin</div></td>
<td><div id = "Country">India</div></td></tr>
</table>
<div class = "central">
<button type = "button" onclick = "loadJSON()">Update Details </button>
</div>
</body>
Declare a variable at first like var jsonObj= ''; ( Inside your function. This variable is not global from the page context, but from the function context ). access the variable in your function. A problem in your url that you use http://www.tutorialspoint.com/json/data.json but the original site using https protocol. As a result you got an error something like that
Blocked loading mixed active content "http://www.tutorialspoint.com/json/data.json"
So change the url also to https://www.tutorialspoint.com/json/data.json.
Then you can parse the result as you want.
<title>tutorialspoint.com JSON</title>
<body>
<h1>Cricketer Details</h1>
<table class = "src">
<tr><th>Name</th><th>Country</th></tr>
<tr><td><div id = "Name">Sachin</div></td>
<td><div id = "Country">India</div></td></tr>
</table>
<div class = "central">
<button type = "button" onclick = "loadJSON();">Update Details </button>
</div>
<script>
function loadJSON(){
var jsonObj= '';
var data_file = "https://www.tutorialspoint.com/json/data.json";
var http_request = new XMLHttpRequest();
try{
// Opera 8.0+, Firefox, Chrome, Safari
http_request = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
http_request.onreadystatechange = function(){
if (http_request.readyState == 4 ){
// Javascript function JSON.parse to parse JSON data
jsonObj = JSON.parse(http_request.responseText);
// jsonObj variable now contains the data structure and can
// be accessed as jsonObj.name and jsonObj.country.
console.log(jsonObj);
document.getElementById("Name").innerHTML = jsonObj.name;
document.getElementById("Country").innerHTML = jsonObj.country;
}
}
http_request.open("GET", data_file, true);
http_request.send();
}
</script>
</body>

ajax keeps returning my main webpage instead of words in output

I have a problem with my ajax call, ive been searching here and cant find a answer to.
here is what happened the script worked great one second then when i logged in to use it again it just shows me my main index page any time i put http:// inside the text area here is the code.
function is_valid_url()
var ajaxRequest;
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('output');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var text = document.getElementById("text").value;
var queryString = "?text=" + text;
ajaxRequest.open("GET", "textscraper.php" + queryString, true);
ajaxRequest.send(null);
}
here is the html
<textarea id="text" onkeyup="is_valid_url()" placeholder="What do you think?" class="posttext">
</textarea>
any help is appreciated.

Give a javascript alert after submit JSP without refreshing the page

I am entering data into a jsp page and validating it from the database. I need to give an alert on the JSP page if the validation is false without refreshing the page as the user is forced to re-enter all the details when the page is refreshed:
My validation Method:
public boolean accountCifMismatch(String account, String custid) {
Connection conn;
int count = 0;
try {
conn = db.getDbConnection();
String sql = pr.getDBProperty().getProperty("com.crb.accountCifMismtach");
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, account);
ps.setString(2, custid);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
count = rs.getInt(1);
}
DBConnection.closeConn(conn);
System.out.println(MemoryListener.getMemoryDetails());
} catch (Exception asd) {
System.out.println(asd.getMessage());
return false;
}
return count == 0;
}
My servlet call:
Fraud fmd = new Fraud();
if (!fmd.accountCifMismatch(account_no, cust_id)) {
//Continue Processing
} else {
session.setAttribute("accountcifmismtach", true);
session.setAttribute("content_page", "fraud.jsp");
}
and on fraud.jsp I call a javascript:
<script type="text/javascript">
if (${accountcifmismtach == 'true'}) {
alert("Account Number CIF Mismtach");
}
</script>
EDIT I am submitting the form:
<form id="form1" name="form1" method="post" action="do?MOD=BOK&ACT=doFindFraud">
</form>
The alert shows and then the page is refreshed, so the user has to input all the details once more. How can I show the alert without refreshing the page?
If you want to validate the Form without refreshing the Page , You need to use AJAX .
There are many ways to make ajax calls but with Java Programming Language I prefer DWR(Direct Web Remoting)Easy AJAX for java
DWR Way :
http://directwebremoting.org/dwr/documentation/index.html
Other Famous ways listed below :
JQUERY Way
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'process.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
});
JavaScript (No Jquery Required)
function AJAXPost(formId) {
var elem = document.getElementById(formId).elements;
var url = document.getElementById(formId).action;
var params = "";
var value;
for (var i = 0; i < elem.length; i++) {
if (elem[i].tagName == "SELECT") {
value = elem[i].options[elem[i].selectedIndex].value;
} else {
value = elem[i].value;
}
params += elem[i].name + "=" + encodeURIComponent(value) + "&";
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST",url,false);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
return xmlhttp.responseText;
}
Write return false after alert and focus the required input form element in javascript.
Ex: docuemnt.getElementById('requiredInputElement').fous;

javascript & ajax only work with confirm()

the following javascript function only seems to work when i have the final confirm() statement which I had originally in there for debugging purposes. when i take it out, delete_row.php doesn't seem to run. also, and perhaps as a hint/side-note, when i do have the confirm statement in there, it works on all browsers except for safari...
function deleterow(form) {
if (!confirm("Are you sure you want to delete?")) return false;
var queryString = "?ID=";
for (var i = 0; i < document.myForm.rows.length; i++) {
if (document.myForm.rows[i].checked) {
ID = document.myForm.rows[i].value;
ID = ID.slice(0, -1);
queryString += ID;
queryString += "-";
}
}
queryString = queryString.slice(0, -1);
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
var ajaxRequest; // The variable that makes Ajax possible!
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "delete_row.php" + queryString, true);
ajaxRequest.send(null);
confirm('Delete successful!');
}
UPDATE SOLVED
i was checking the status of the ajaxRequest through the following js script change
ajaxRequest.onreadystatechange = function(){ // Create a function that will receive data sent from the server
if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
else{
alert('An error has occurred making the request');
return false;
}
}
and noticed i was getting a status of 0 back from the server. some googling around helped me realize that the error lied in how i was defining the buttons which were calling these functions.
original code was:
<div style='float:left; margin-right:10px;'><input type="submit" onClick="deleterow(document.myForm)" VALUE="Delete ROWs"></div>
fix is:
<div style='float:left; margin-right:10px;'><input type="button" onClick="deleterow(document.myForm)" VALUE="Delete ROWs"></div>
(submit type has to be changed to button type)
delete_row.php doesn't seem to run have you verified this, can you add an alert to if(ajaxRequest.readyState == 4){ I tried your JS though without the form stuff and it seems to work fine, http://jsfiddle.net/6gjy6/ Do you get any JS errors in Google Chromes console? Have you tried doing a basic "GET" request on the browser with the appripriate url ie delete_row.php" + queryString, and seeing how the server responds instead of the AJAX call.
try this:
var queryString = "?ID=";
for (var i = 0; i < document.myForm.rows.length; i++) {
if (document.myForm.rows[i].checked) {
ID = document.myForm.rows[i].value;
ID = ID.slice(0, -1);
queryString += ID;
queryString += "-";
}
}
queryString = queryString.slice(0, -1);
var ajaxRequest;
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
alert("received: " + ajaxRequest.responseText);
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "delete_row.php" + queryString, true);
ajaxRequest.send(null);
​
I'm fairly sure you're supposed to set the onreadystatechange event after calling open, otherwise the handler is cleared.
keep your confirm() statement there while at the top of your js put
window.alert = null ;
and try
k let me check

Use of Ajax to refresh Struts2 datatable

I have created a datatable in Struts2 and also have a feature of adding a record into this table by some action. After the record is inserted we are refreshing the page to get the table refreshed.
I had tried to use Ajax for this purpose and send the new values we have inserted to the Action class by request parameter and in the response we are getting the table refreshed.
My Ajax function is:
function reloadTable(){
var ajaxRequest;
try {
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer Browsers
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser has no AJAX Support!");
return false;
}
}
}
var elem1 = document.getElementById('host0');
var elem2 = document.getElementById('ip0');
var elemTable = document.getElementById('hostTable');
//alert(indexSelected);
//alert(document.getElementById(elem).options[indexSelected].value);
var url = "insertTable.action";
ajaxRequest.open("POST", url, true);
ajaxRequest.onreadystatechange = function()
{
try
{
if (ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
var res = ajaxRequest.responseText;
if (res)
{
//alert("hi"+res.greeting);
document.getElementById("hostTable").innerHTML = res;
//adjustTable();
}
}
}
catch (e)
{
}
};
//alert(selectedCountry);
ajaxRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var hostName = elem1.value;
var ipAddress = elem2.value;
//alert("AJAX CALL"+elem1.value+elem2.value);
//ajaxRequest.send("hostName="+elem1.value+"&ipAddress="+elem2.value);
ajaxRequest.send("hostName="+hostName+"&ipAddress="+ipAddress);
//ajaxRequest.send(null);
}
Content in my Struts.xml is:
<action name="insertTable" method="insertNewData" class="action.LoginAction">
<result name="success">/success.jsp</result>
</action>
Method in my action class:
public String insertNewData(){
populateList();
System.out.println("Hi"+getHostName()+getIpAddress());
userNameList.add(new UserType(hostName,ipAddress));
return SUCCESS;
}
Now I want the list populated in the actionClass method to be reflected in the table by this Ajax call. In this method I am appending the value that I am sending through parameter in the Ajax method. I can fetch the new values in the action class method but while sending the response the whole page is displayed in place of the table.
Thanks,
Sachin
After the record is inserted we are refreshing the page to get the
table refreshed.
Is it like you don't want to refresh the whole page for that. In that case I suggest you to use Struts2 Jquery Plugin. Grid showcase does exactly what you want to do.
For more examples you can visit Online Examples and can request can example if you want something more specific.

Categories

Resources