I have my servlet sending the following response to a JS ajax call:
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
out.print("start");
out.close();
and the call from the web page has the following code:
function update() {
var xmlhttp = new XMLHttpRequest();
var id = '${user.id}';
var height = (window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight);
height = height-40;
var params = "action=update&id=" + id + "&height=" + height;
xmlhttp.open("POST", "/Anabasis/UserControl", true);
xmlhttp.setRequestHeader("Content-type",
"application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var answer = xmlhttp.responseText;
if(answer=="start"){
window.location.href = "/project/page1.jsp";
} else {
window.location.href = "/project/page2.jsp";
}
}
};
xmlhttp.send(params);
}
setTimeout(update, 10000);
If start is send back by the Servlet, the browser should be redirected to another page. This may be done without the user's doing anything since the JS request is send every 10 seconds.
Now the result is that I do not get the answer to page but just a black page with the text: "start"
Can anyone tell me what to add in order to asure that the answer gets back to the JS function?
It's better to forward your request according to your requirement, like:
RequestDispatcher rd=request.getRequestDispatcher("./project/page1.jsp");
rd.forward(request, response);
I have found the solution, sorry for the question. The code actually works fine, just in some case the Servlet gets not called by this update function but by another form from the same page. So of course the answer is not send to the function, explaining the misbehaviour.
Is there any guide on best practices concerning Servlet-Webpage communication? I guess I shall need that very much.
Related
I wrote a PHP application that makes an AJAX call (XMLHttpRequest) and is called every 5 seconds. The page called makes a database query. However, I need a variable from the main page and am unable to find a solution to attach it to the Ajax call.
Using $_GET seems a bit too insecure to me. Is there another way here?
This is my first expierence with ajax so please dont be to hard with me :)
Here is my Ajax Call
const interval = setInterval(function() {
loadText() }, 5000);
function loadText(){
//XHR Objekt
var xhr = new XMLHttpRequest();
// OPEN
xhr.open('GET', 'ajax/table_view.php?role=<?php echo $role.'&name='.$_SESSION['name'].'&org='.$_SESSION['org'];?>', true);
xhr.onload = function() {
if(this.status == 200){
document.getElementById('table_view_div').innerHTML = this.responseText; }
})
if(this.status == 404){
document.getElementById('apps').innerHTML = 'ERROR';
}
}
xhr.send();
// console.log(xhr);
}
Ill hope i provided enough Information
WIsh u all a great weekend
You do not need sending session variables at all: those are already known to the called page, because it can share the session information of the calling page.
// OPEN
xhr.open('GET', 'ajax/table_view.php?role=<?= $role ?>'
is enough, provided that "table_view.php" issues a session_start() command.
I have fixed your code; It's here:
(Note: \' means that the character ' doesn't closing the string.)
const myInterval = setInterval(function(){loadText();}, 5000);
function loadText(){
//XHR Objekt
var xhr = new XMLHttpRequest();
// OPEN
xhr.open('GET', 'ajax/table_view.php?role=<?php echo $role.\'&name=\'.$_SESSION[\'name\'].\'&org=\'.$_SESSION[\'org\']; ?>', true);
xhr.onload = function(){
if(this.status == 200){
document.getElementById('table_view_div').innerHTML = this.responseText;
}
if(this.status == 404){
document.getElementById('apps').innerHTML = 'ERROR';
}
}
xhr.send();
}
I am making a Pokedex API as a side project and I can not display the data needed to display in the different text boxes. I am using a GET request to request the height, weight, type, and ability.
<script>
$("button").click( function(){
var pokemonName = $('pokemon').val(pokemon);
event.preventDefault();
getPokemonData(pokemonName);
})
function getPokemonData(pokemonName){
var request = new XMLHttpRequest()
//GET request with link
request.open('GET','https://pokeapi.co/api/v2/pokemon/' + pokemonName, true);
// request for data
request.onload =function(){
var data = JSON.parse(this.response)
if(request.status >= 200 && request.status <= 400)
{
// outputs data
$(pokemonheight).val(response.height)
$(pokemonweight).val(response.weight)
$(pokemonAblity).val(response.ability)
$(pokemonType).val(response.type)
}
else
{
alert ("Error");
}
request.send();
}
}
</script>
</html>
I have tried setting a variable that would be equal to the response JSON element and then input that into the value of the textbox.
I do not have anything returned as expected or input displayed in the console if declared.
Issue(s)
There were a few issues with your code:
var pokemonName = $('pokemon').val(pokemon); you are setting the value of some element named pokemon (not valid) here
var data = JSON.parse(this.response); where is this.response being set? Shouldn't we be receiving response in the callback?
request.send(); is inside of the onload event, so the request never gets sent
Critiques
My main critique here is that you included a fairly large library (jQuery), and didn't utilize it to make the request. $.ajax is well documented and cleans up a lot of the intricacies of XMLHttpRequest.
The solution
$("button").click(function() {
var pokemonName = $('#pokemon').val();
//event.preventDefault();
getPokemonData(pokemonName);
})
function getPokemonData(pokemonName) {
var request = new XMLHttpRequest()
//GET request with link
request.open('GET', 'https://pokeapi.co/api/v2/pokemon/' + pokemonName, true);
// request for data
request.onload = function(response) {
var data = JSON.parse(response.currentTarget.response)
if (request.status >= 200 && request.status <= 400) {
// outputs data
console.log(data)
} else {
alert("Error");
}
}
request.send();
}
<input id="pokemon" value="12" />
<button>search</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Taking all the above issues into account, I was able to get a working example of what it should ultimately look like.
Hope this helps!
I have an anchor link with no destination, but it does have an onClick event:
<li><a href onClick='deletePost()'> Delete </a> </li>
I understand that I cannot directly execure PHP code blocks in JavaScript due to the nature of PHP and it being a server side language, so I have to utilize AJAX to do so.
When the delete link is clicked, I need it to execute this query (del_post.php)
<?php include("connect.php");
$delete_query = mysqli_query ($connect, "DELETE FROM user_thoughts WHERE id = 'id' ");
?>
I have tried to understand AJAX using similar past questions, but due to being relatively new, I cannot completely grasp it's language. Here is what I have tried:
function deletePost() {
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
xmlhttp.open("GET", "del_post.php", false);
xmlhttp.send();
}
}
}
But clicking the link just changes the URL to http://localhost/.
I believe the (main) problem is your empty "href" attribute. Remove that, or change it to href="#" or old school href="javascript:void()" (just remove it, imo).
It's been a while since I used XMLHttpRequest and not something like jQuery's .ajax, but I think you need to do it like so (mostly you need to .open/send before you watch for the state change):
var xmlHttpReq = new XMLHttpRequest();
if (xmlHttpReq) {
xmlHttpReq.open('GET', 'your-uri-here.php', true/false);
xmlHttpReq.onreadystatechange = function () {
if (xmlHttpReq.readyState == 4 && xmlHttpReq.status == 200) {
console.log('success! delete the post out of the DOM or some other response');
}
else {
console.log('there was a problem');
}
}
xmlHttpReq.send();
}
Can you please provide your : del_post.php file?
Normally you can show a text or alert in a
<div id="yourname"></div>
by using callback in an AJAX request :
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("yourname").innerHTML = xmlhttp.responseText;
}
This response is coming from your PHP file for example :
function remove_record(ARG){
if ($condition==true)
echo "TRUE";
else
echo "FALSE";
}
You should remove href attribute from anchor tag and style the element with CSS.
Also, your script should look like this:
<script>
function deletePost() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
// Do something if Ajax request was successful
}
};
xhttp.open("GET", "del_post.php", true);
xhttp.send();
}
</script>
You are trying to make the http request inside the callback.
You just need to move it outside:
function deletePost() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET", "del_post.php", false);
xmlhttp.send();
}
Removing the href attribute will prevent the refresh. I believe that is valid in HTML5.
Ok... I'm just a hobbyist, so please forgive me any inaccuracies in the typing but this works: A format I use for an ajax call in an <a> element is:
<a href="javascript:" onclick="functionThatReallyCallsAjax()">
So that I have more flexibility(in case I need to check something before I send the ajax). Now, for an ajax call you need:
What file to call
What to do with the response from the file you called
What to do if an I/O error happens
So we have this function - not mine, leeched amongst thousands from somewhere - probably here :) - and probably well known, my apologies to the author, he is a genius: This is what you call for the ajax thing, where 'url' is the file you want to 'ajax', 'success' is the name of the function that deals with results and error is the name of the function that deals with IO errors.
function doAjaxThing(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req.readyState == 4) {
return req.status === 200 ?
success(req.responseText) : error(req.status);
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
You will naturally need to include the success+error functions:
function dealWithResponse(textFromURL)
{
//textFromURL is whatever, say, a PHP you called in the URL would 'echo'
}
function ohNo()
{
//stuff like URL not found, etc.
alert("I/O error");
}
And now that you're armed with that, this is how you compose the real call inside the function you called at the <a>:
function functionThatReallyCallsAjax()
{
//there are probably many scenarios but by having this extra function,
//you can perform any processing you might need before the call
doAjaxThing("serverFile.php",dealWithResponse,ohNo);
}
One scenario might be when you need to pass a variable to the PHP you didn't have before. In this case, the call would become:
doAjaxThing("serverFile.php?parameter1=dogsRock",dealWithResponse,ohNo);
And now not only you have PHP sending stuff to JS, you have JS sending to PHP too. Weeeee...
Final words: ajax is not a language, its a javascript 'trick'. You don't need to fully understand what the first 'doAjaxThing' function does to use this, just make sure you are calling it properly. It will automatically 'call' the 'deal WithResponse' function once the response from the server arrives. Notice that you can continue doing your business (asynchronous - process not time-tied) till the response arrives - which is when the 'deal WithResponse' gets triggered -, as opposed to having a page stop and wait (synchronous - time tied) until a response arrives. That is the magic of ajax (Asynchronous JAvascript and Xml).
In your case you want to add the echo("success") - or error! - in the PHP, so that the function 'dealWithResponse' knows what to do based on that info.
That's all I know about ajax. Hope this helps :)
I am trying to get real path in link megaupload but always but this dont work.
function getRealURL(){
var st = new String("");
var req = new XMLHttpRequest();
req.open("GET","http://www.megaupload.com/?d=6CKP1MVJ",true);
req.send(null);
req.send(null);
req.onreadystatechange = function (aEvt) {
if (req.readyState == 4) {
if(req.status == 302){
//SUCESSO
st = req.responseText;
}
}
};//funcao
element.getElementById("id").setAttribute("value", st);
}
i need this link:
Redirect to: http://www534.megaupload.com/files/c2c36829bc392692525f5b7b3d9d81dd/Coldplay - Warning Sign.mp3
insted of this:
http://www.megaupload.com/?d=6CKP1MVJ
XMLHttpRequest follows the redirect automatically by default so you don't see the 302 response. You need to set nsIHttpChannel.redirectionLimit property to zero to prevent it:
req.open("GET","http://www.megaupload.com/?d=6CKP1MVJ",true);
req.channel.QueryInterface(Components.interfaces.nsIHttpChannel).redirectionLimit = 0;
req.send(null);
Not that the link you use here redirects anywhere but this is the general approach. Btw, instead of looking at the response text for redirects you should look at req.getResponseHeader("Location").
I have a jsp page where I'm trying to send multiple (two currently) ajax requests at once, but I only seem to get the second response. This guy described my problem exactly, but his solution didn't work for me.
Here is my js code:
function createRequestObject(){
var req;
if(window.XMLHttpRequest){
//For Firefox, Safari, Opera
req = new XMLHttpRequest();
} else if(window.ActiveXObject){
req = new ActiveXObject("Microsoft.XMLHTTP");
}
else{
//Error for an old browser
alert('Browser error');
}
return req;
}
function sendRequest(method, url, d){
var http = createRequestObject();
var div = d;
if(method == 'get' || method == 'GET'){
http.open(method, url, true);
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200){
var response = http.responseText;
if(response){
document.getElementById(div).innerHTML = response;
}
}
};
http.send(null);
}
}
And here is how I call that code:
QC1 Status: <div id='qc1'>blah</div>
<br />UAT2 Status: <div id='uat2'>blah2</div>
<a onclick="sendRequest('GET','index.jsp?qc1.properties=true','qc1'); " href="#">qc1</a>
<a onclick="sendRequest('GET','index.jsp?uat2.properties=true','uat2'); " href="#">uat2</a>
<a onclick="sendRequest('GET','index.jsp?qc1.properties=true','qc1'); sendRequest('GET','index.jsp?uat2.properties=true','uat2'); " href="#">both</a>
When I call one at a time they work as expected, but the "both" link only updates with the second request, even though I know it runs the index.jsp code for both.
EDIT: Ok, after fixing the obvious mistake that BalusC pointed out, it works. Fixed it in this post too.
You're indeed sending two requests on the same URL and updating the same div. Shouldn't the first one go to the qc1 one and update the qc1 one?