Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How can I update a database from JavaScript?

Status
Not open for further replies.

celia05es

Programmer
Jan 10, 2002
81
US
Hello,
I have a jsp file. An array (generated from a database) is printed on the screen.
Next to each element, there are two arrows (up and down). The user can move up/down an element from the list.
By doing this, two things must happen:
- The elements are moved on the screen (I can do that)
- The database must be updated in order to reflect the changes (the table is sorted by entry_order.... and the entry_order has been modified).
how can I do it?


In the jsp file, I have a bean defined where I have my database operations.

Thanks for your help.
 
You can't update the database with Javascript only. Javascript is client-side (it runs on the computer of the user), the database is server-side (it runs on the computer of the server).

To communicate with the server-side, you need server-side scripting, like PHP or .ASP. Javascript can pass variables to PHP/.ASP by posting them in a <form>.
 
Thanks for your response.... I am using Apache Tomcat 5.5.9.
Do I need something special in order to used PHP? Do I need to download something?
Once I learn how to use PHP, how can I call a PHP script from JavaScript?
 
I am running my application on a Unix machine.
What do you suggest I should use ASP or PHP? I am sorry if the question seems "stupid" but I don't know either of them!
 
This a little out of the scope of this forum, but if you're using jsp (Java Server Pages) and beans (I understand EJBs), I'd continue the Java way with another JSP or a servlet.

Cheers,
Dian
 
Thanks for your answer....I have a problem with using another JSP though....
Let me try to explain.... I have a sort of matrix (let's say 3 columns and 4 lines) shown on the screen.
In front of each line, the user has "DOWN" and "UP" buttons.
Now, if the user presses the UP button for instance, the current line and the above line are automatically switched.
The database needs to be updated (for order reason) but I don't want any page to be reloaded.
I can't use PHP or ASP since, as you say I am already using jsp and the download is not worth it only for this.

Can I call a servlet from JavaScript?
 
A call to a servlet is just another request, it will enforce a new navigation.

Cheers,
Dian
 
Look into using AJAX for this (google).

Using javascript you can send a form (that you can construct on-the-fly) via an AJAX object (which can be GET or POST). You wouldn't even be interested in the callback response - just the submission of the updated data.

This will solve your problem and push the actions back to the server. You would need to code a JSP to accept the form submission and update the database as you see fit.

I have used a similar technique to create a working solution that updated a database. It works on Safari, Firefox, IE (Win), Netscape, and Opera (that I have tested). Requires javascript to be turned on.

Hope that helps out!
Jeff

Cheers,
Jeff

[tt]Jeff's Page [/tt][tt]@[/tt][tt] Code Couch
[/tt]
 
Thank you. It might help me later if we decide to use PHP...
which is not the case for the moment !!!!

Unfortunately I can't think of anything else to solve my problem!!!!... do you?
 
Thank you. It might help me later if we decide to use PHP...
I don't know if that was in response to my suggestions or not! Might I just take a moment to add that my suggestions are not server-environment specific. They will work with ASP, PHP, CFM, Perl, JSP, and anything else that can process a form submission.

Cheers,
Jeff

[tt]Jeff's Page [/tt][tt]@[/tt][tt] Code Couch
[/tt]
 
Sorry!!! Mea culpa!!!! I misread what you wrote.... I read PHP instead of JSP!!!!!!
So, your suggestion seems great!!!! I will look into google for AJAX!!!!

Once again thank you!!!
 
Once more thing about AJAX.... If I send a form from JavaScript using an AJAX object.... though I am not expecting a response, would I get a page reload?
I mean, once the user has moved an item UP or DOWN, would he see a page reload when the db is updated?
 
would I get a page reload?
Nope [smile]

You send the form off via the AJAX object, and you forget about it (from the front end). In your instance you don't care about the postback (which does happen, but you can ignore). The page will never reload.

Back-end you would code a page to recieve the form contents and do your database activity... and dump out an empty page. If you were visiting the page using a browser, you would see a blank page returned.

Of course you can handle the postback as well... but for your uses this would be a nightmare [smile]

Cheers,
Jeff

[tt]Jeff's Page [/tt][tt]@[/tt][tt] Code Couch
[/tt]
 
OK. I have sent a form via an AJAX object. The form will call a foo.jsp.
The problem is that I am interested in the callback response since I have to make sure the db has been updated without errors. The function updating the db returns a string[]. If the first element of the array is not "0", the second element will be the error message.... and I need to know the error message if an error has occured.

I can submit the file all right.... but when I try to get the response.... using:
Code:
...
if (http_request.readyState == 4)
  {
    if (http_request.status == 200)
    {
       alert("response="+http_request.responseText);
    }
    else
    {
       alert('There was a problem with the request.');
    }

I get the whole jsp file!!!!
What am I doing wrong?
I thought that in order to get the result, I only had to write the result!! but it does not work!!!

The jsp file is :
Code:
<html>
<head>
...
<jsp:useBean id="fconn" class="util.Functions" scope="session"/>
....
<body>
<%
.....
String[] ier=conn.update_tuple(url,user,pwd,table,data,type);
%>
<%=ier[0]%>|<%=ier[1]%>  // output I am interested in 
</body>
</html>

 
Make the JSP so that it only outputs the text (no markup) that you want to capture:
Code:
<jsp:useBean id="fconn" class="util.Functions" scope="session"/>
<%
.....
String[] ier=conn.update_tuple(url,user,pwd,table,data,type);
%>
<%=ier[0]%>|<%=ier[1]%>
Something like that anyway.

Cheers,
Jeff

[tt]Jeff's Page [/tt][tt]@[/tt][tt] Code Couch
[/tt]
 
Hi again,
Well, I have called my jsp with AJAX..... now I am having problem when I try to read the form parameters!

I have:
Code:
...
function moveUpList(lineIndex,col)
{
....
document.forms["attributes"].data.value=array_up.join(',');
document.forms["attributes"].type.value=type_up.join(',');
document.forms["attributes"].data1.value=array_down.join(',');
document.forms["attributes"].type1.value=type_down.join(',');

makeRequest('movea.jsp');
}
...
function makeRequest(url)
{
  http_request = false;

  if (window.XMLHttpRequest)  // Mozilla, Safari,...
  {
......
}
....
<form  method="post" name="attributes" action="">
<table>
.....
<input type="image" tabindex=<%=ind+2%> onClick="moveUpList('<%=line%>','<%=col%>')" src="img/arrow.up.gif"
.....
<input type=hidden name="data">
<input type=hidden name="type">
<input type=hidden name="data1">
<input type=hidden name="type1">
<input type=hidden name="table" value=<%=table%>>
</table>
...

movea.jsp:
Code:
String ss = (String) existingSession.getAttribute("adm.ss");
...
String table=request.getParameter("table");

The table value is null.
Now, if I call movea.jsp using:
Code:
document.forms["attributes"].action="moveUpdate.jsp";
document.forms["attributes"].submit();
Everything works... and table has a value

What am I doing wrong?
 
I have tried to add parameters to the url and it works fine.
It is a bit heavy though. Is there another way of doing it?
Why can't I access form parameters?
 
You need to build up the data to be sent by gathering each form value and creating the header manually. Here is an example from one of my projects:
Code:
	http = getHTTPObject();
	var _data = "test1=true";
	_data    += "&test2=" + escape(document.getElementById('testInput').value);
	_data    += "&test3=420;
	var _url = 'path/to/file.jsp';
	http.open('post', _url, true);
	http.onreadystatechange = sendMessageResponse; // name of my callback
	http.setRequestHeader("Content-Type","application/x-[URL unfurl="true"]www-form-urlencoded;[/URL] charset=UTF-8");
	http.send(_data);
I have a form field with id "testInput" and I'm escaping it's contents - a good idea :)

Hopefully this is all you are missing in the puzzle?

Cheers,
Jeff

[tt]Jeff's Page [/tt][tt]@[/tt][tt] Code Couch
[/tt]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top