ajax javascript function refresh - ajax

I think my question is odd… I’m learning here, and would like to use AJAX & JSP to display some other JSP pages in order.
i.e. click button: page1.jsp displayed, click button again: page2.jsp displayed, …
I got the JSP to add the ‘1’ after page and JSP does increment the variable. But it does not change the value past page 1…
It increments correctly in the function if I do a location.reload(), but that of course brings me back to page one…
I’m sure there are other ways to do this, but I simply want this to work using JSP… Any ideas
<!DOCTYPE html>
<html>
<head>
<%! int n = 0;%>
<script>
function loadDoc() {
<% n = n+1; %>
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","page<%=n%>.jsp",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv"><h2>Using AJAX to display next page</h2></div>
<button type="button" onclick="loadDoc()">Change Page</button>
</body>
</html>

n is 0 each time. You need to save n. Try using a
<input type="hidden" value="0" id="countvariable" />
in your html somewhere.
Then inside loadDoc() put
var n = 1 + parseInt(document.getElementById("countvariable").value);
document.getElementById("countvariable").value = n;
This should hold your variable. Also, the parseInt is a must otherwise javascript will append the 2 together and you will get 10 as n instead of 1.
Updated: If you want to go back after a certain amount of pages then add this to the end.
if(n == 2)
{
document.getElementById("countvariable").value = 0;
}

Related

Make an really simple ajax example work

I am learning ajax but I have a problem even just trying the example given in w3 tutorial.
When I click the Button there is no change on my page. I don't know what is missing to make it work. Do I need put on my mamp server?
Thank you for your help
Here is the code:
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","ajax_info.html",false);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
To run the above code there is no need to start your server.
First check if you have created ajax_info.html file or not.
Place ajax_info.html in the same folder where the present code file is placed.
Maybe try a "GET" instead of a "POST" xmlhttp.open("GET","ajax_info.html",false);. Also W3School's example is NOT IDEAL and scales VERY POORLY once you add more AJAX calls. I recommend switching to a simpler library such as jQuery or AngularJS (bit more advanced) ASAP in order to handle your AJAX calls

Ajax not giving results under wampserver

I've been trying to figure out why the content in my very simple ajax file isn't working for the past hour or so.
I'm using wamp server, so I deployed my file under the www folder and ran it from the localhost, no results. I also tried to run it as an independent html file, no results as well.
I'm using Google chrome. I ran an example code from the web (it was embedded in the webpage), it worked perfectly, but after copy-pasting it, didn't work. Why?
Are there any settings I should make sure of in either my browser or server?
Please help! I can't seem to find the problem
here's the code:
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
}
</script>
</head>
<body>
Your code has no issues.
just add a div with id myDiv inisde the body tag
<div id="myDiv"></div>
then make sure the ajax target page exists. (ajax_info.txt)
then invoke the loadXMLDoc function onload of the page
<body onload="loadXMLDoc()">
the resultant code might look like this.
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
}
</script>
</head>
<body onload="loadXMLDoc()">
<div id="myDiv"></div>
</body>
</html>
if still myDiv doesnt get the ajax response, check the firebug/chrome inspector console for any errors.

How to send data to 'post.php' using AJAX? (without Jquery)

I'm newbie on this webdeveloper matters. I have already made a form where i've used Ajax (JQuery lib) to create a chat box.
Now, i wanna try to do something similar without using Jquery to understand how Ajax works. First i just want to write my messages on log.html using AJAX, so then i can read them later. But i dont understand why i can't send my textarea data into post.php.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Teste</title>
<script type="text/javascript">
function sendXMLDoc(){
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
var message=document.getElementById('msg').value;
xmlhttp.open("POST", "post.php", false);
xmlhttp.onreadystatechange = function() {//Call a function when the state changes.
if(xmlhttp.readyState == 0 ) {
alert("UNSENT");
}
if(xmlhttp.readyState == 1 ) {
alert("OPENED");//check if the data was revived successfully.
}
if(xmlhttp.readyState == 2 ) {
alert("Headers Received");//check if the data was revived successfully.
}
if(xmlhttp.readyState == 3 ) {
alert("Loading response entity body");//check if the data was revived successfully.
}
if(xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
alert("Data transfer completed");//check if the data was revived successfully.
}
}
}
xmlhttp.send(message);
}
</script>
xmlhttp.send(data) : Why im not sending my data to post.php?
Post.php is where i write my log.html (but i cant send my messages and i dont understand why):
<?php
$text = $_POST['message']; // WHY I CAN'T RECEIVE MY POSTED MESSAGE?
$fp = fopen("log.html", 'a');
fwrite($fp, "<div>\n(".date("g:i A").")<br>".$text."<br>\n</div>\n");
fclose($fp);
?>
And this is my form.html
<body>
<h1>Insert text on log.html</h1>
<form method="post" onsubmit="sendXMLDoc();">
<textarea name="message" maxlength="196" rows="8" ></textarea>
<br>
<input type="submit" value="Send"/>
</form>
</body>
have you taken a look at this link ?
It seems to have a complete explanation on how to build an AJAX request with PHP and MySql.
EDIT:
The problem in your code is both on your post.php, which has incorrect syntax (lacking double quotes before the last <br>), and should be something like :
post.php
<?php
$text = $_POST['message'];
$fp = fopen("log.html", 'a');
fwrite($fp, "<div>\n(".date("g:i A").")<br>".stripslashes(htmlspecialchars($text))."<br>\n</div>\n");
fclose($fp);
?>
and with the request header, which should have the content-type set (see code below)
I based this answer on w3.org.
The final html here presented shall help you understand how Ajax requests behave on different browsers. Try it out.
It seems though that for Firefox to load the request, you need to do something when the Status is OPENED (1), and I don't quite understand why.
Try this code on different browsers to see the different approaches to XMLHttpRequest.
<!DOCTYPE html>
<html>
<head>
<script language="javascript" type="text/javascript">
function sendXMLDoc(obj){
var message=obj["message"].value;
var data = "message=" + message;
var xmlhttp;
try{
// Opera 8.0+, Firefox, Safari
xmlhttp = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
url = "http://localhost/AjaxPhp/post.php"
xmlhttp.open("POST", url , true);
xmlhttp.onreadystatechange = display_data;
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send(data);
function display_data() {
if(xmlhttp.readyState == 1 ) {
alert("OPENED");//check if the data was revived successfully.
}
if(xmlhttp.readyState == 2 ) {
alert("Headers Received");//check if the data was revived successfully.
}
if(xmlhttp.readyState == 3 ) {
alert("Loading response entity body");//check if the data was revived successfully.
}
if(xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
alert("Data transfer completed");//check if the data was revived successfully.
}
}
}
}
</script>
</head>
<body>
<h1>Insert text on log.html</h1>
<form method="post" onsubmit="sendXMLDoc(this);">
<textarea name="message" maxlength="196" rows="8" ></textarea>
<br>
<input type="submit"/>
</form>
</body>
</html>
I don't truly understand the whys, but according to w3, the order of the requests should, in my understanding, be :
OPENED (after invoking the open method), HEADERS_RECEIVED (after setRequestHeader), LOADING (request body received). DONE (Data transfer completed, after send) .
Chrome handles the post.php but doesn't present any alert box (maybe its my popup settings, maybe not)
IE shows only the OPENED alert message
Firefox goes "Headers Received", "Data transfer completed","OPENED", "Data transfer completed".
Hope this helps understanding it a little bit more. Always go check w3.org for the ultimate source on the web. It might not be very user-friendly and intuitive, but provides some tips on the whys and the shoulds.

AJAX example not working locally

I copied the example from http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first and saved it locally to test.html on my computer. Yes I did make an ajax_info.txt file too, but when I click the button nothing happens, and on w3schools works fine. Any ideas?
Here is the copied code:
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
Is your machine \ environment setup to serve that text file over HTTP i.e. when you press the button the client - i.e. your browser will do a GET HTTP to a server i.e. you localmachine running a web server (iis/apache etc) or remote box if configured
Does your ajax_info.txt file have the contents of:
< p>AJAX is not a new programming language.< /p>
< p>AJAX is a technique for creating fast and dynamic web pages.< /p>
There is no space in < p> and < /p>. I put it in just for formatting purpuses.
Side note: when you learn the fundamentals of ajax, you will find it much easier to work with jQuery's versions of it. Much simpler!!!!

AJAX script not working in Firefox

I have written an AJAX script to read information from a database and inject it into a .php file as HTML. It works in IE8, Safari, Chrome but not Firefox. No errors displayed or anything, it just doesn't execute at all.
Here's the code:
function queryDatabase(query)
{
alert();
var xmlhttp;
if (window.XMLHttpRequest)
{
alert();
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{
alert();
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{
content.innerHTML = xmlhttp.responseText;
}
else
{
content.innerHTML = "<center><span style=\"color: #ff7e00; font-size: 30px;\">LOADING...</div></center>";
}
}
xmlhttp.open("GET",query,true);
xmlhttp.send(null);
}
(The alerts were for testing purposes but none of them show up in Firefox)
Here's the divs it's used on:
<div onClick="queryDatabase('latestquery.php')" style="cursor: pointer;">TEST</div> <div onClick="queryDatabase('testtagquery.php')" style="cursor: pointer;">TEST</div>
Any help is appreciated :)
Thanks
Sam
Well for a start you can't do alert() in Firefox - the argument isn't optional. Change it to alert(0) and see what happens the.
Secondly, I don't see where you set content - is that a global variable you've got initialised somewhere?
You can check for script errors in Firefox by bringing up the Error Console (Tools -> Error Console or Ctrl + Shift + J).
To help even more, install firebug.
Edit: if content is just the id of an element you need to do document.getElementById(content).innerHTML = ...;
The best advice I can give you is to start using a javascript framework that implements the AJAX functionality for you and makes it much easier to write code using it.
Using jQuery this would look like:
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js">
</script>
<script type="text/javascript">
$(function() {
$('#div1').click( function() {
queryDb(this,'lastestquery.php');
});
$('#div2').click( function() {
queryDb(this,'testtagquery.php');
});
});
function queryDB(div,url) {
$(div).load( url );
}
</script>
<div id="div1" style="cursor: pointer;">TEST</div>
<div id="div2" style="cursor: pointer;">TEST</div>
Note that I would probably also use a CSS class to assign the cursor as well.
<div id="div1" class="clickable">TEST</div>
Loaded via a CSS file
.clickable {
cursor: pointer;
}
Here's the lastquery.php file if this helps:
<?php
$con = mysql_connect("localhost","root","***");
mysql_select_db("main", $con);
//GET MOST RECENT POST ID
$last_id_query = mysql_query("SELECT * FROM articles");
$last_id_result = mysql_fetch_array($last_id_query);
$last_id = (int)$last_id_result['id'] - 2;
//USE MOST RECENT POST ID TO GENERATE LAST 5 ARTICLES SUBMITTED
$result = mysql_query("SELECT * FROM articles WHERE id > '$last_id' ORDER BY id DESC");
while($row = mysql_fetch_array($result))
{
echo "<div id=\"centralcontent\"><div class=\"articleheading\"><strong>".$row['title']."</strong></div><div class=\"tag\"> in ".$row['tag']."</div><div class=\"articleinfo\">".$row['date']."</div>";
echo "<div class=\"articlecontent\">".$row['content']."</div></div>";
}
mysql_close($con);
?>
Edit: This worked on the face of it, but it looks now like it was not the actual solution.
Taking your code above and moving the xmlhttp.open call to before you set the state change function worked for me. Like this:
xmlhttp.open("GET",query,true);
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{
content.innerHTML = xmlhttp.responseText;
}
else
{
content.innerHTML = "..";
}
}
xmlhttp.send(null);

Resources