Ajax - understanding of the code - ajax

I try to understand Ajax. I'd like to understand how the data and commands flow in the code. I have the following code. Please, read my comments in this code. The comments describe, how I understand the code. The problem is marked as PROBLEM!!! Important notice: The code is working, I only try to understand the code.
<!DOCTYPE html>
<HTML>
<HEAD>
<META charset="UTF-8" />
<TITLE>Test02</TITLE>
</HEAD>
<BODY>
<p id="demo">Let AJAX change this text.</p>
<button type="button" onclick="loadDoc()">Change Content</button>
<SCRIPT>
function loadDoc() {
// select right object
function createXhttp(){
var variable;
if (window.XMLHttpRequest) {
// code for modern browsers
variable = new XMLHttpRequest();
} else {
// code for IE6, IE5
variable = new ActiveXObject("Microsoft.XMLHTTP");
}
return variable;
}
var xhttp = createXhttp();
// check the state
xhttp.onreadystatechange = function (){
// if the response is ready and file or url exists
if (xhttp.readyState == 4 && xhttp.status == 200) {
/* display the text in console - but which text if xttp.open
with source file is opened on the next line? (PROBLEM!!!)*/
console.log(xhttp.responseText);
}
};
// use method get and load the content of ajax_info.txt
xhttp.open("GET", "ajax_info.txt", true);
// send the request above
xhttp.send();
}
</SCRIPT>
</BODY>
</HTML>
Thank you for your advice.

but which text if xttp.open with source file is opened on the next line?
Let's take another example.
document.getElementById('some_button').onclick = function () {
console.log(document.getElementById("some_text_box").value);
}
It doesn't matter if the user hasn't typed anything in some_text_box at this point, because the function won't run until some_button is clicked.
Now back to XHR:
xhttp.onreadystatechange = function (){
if (xhttp.readyState == 4 && xhttp.status == 200) {
console.log(xhttp.responseText);
}
};
… it doesn't matter that the request hasn't been sent yet, because the function won't run until the response arrives.
(OK, it will run every time the ready state changes, but the if statement means the meat of it won't run until the response arrives).

Related

How to correctly set the request header in an ajax containing non-alphanumeric characters?

My HTML file contains a form with just a textarea whose contents are sent to a java servlet (called "Compiler"). The textarea text will always be java code, so it might include characters like +, %, =, etc.
I'm using ajax to get and display the response from the servlet.
But using ajax breaks the whole data being sent by the form, because it strips out part of the text or completely ignores the characters I mentioned above.
This is my html file:
<html>
<head>
<script type="text/javascript">
function objetoAjax(){
http_request= false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/xml');
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
return http_request;
}
function devolver_resultado(){
var llamadaAjax = objetoAjax();
var codigo = document.getElementById('codigo').value;
llamadaAjax.open("POST",'Compiler',true);
llamadaAjax.onreadystatechange = function() {
if(llamadaAjax.readyState == 4){
document.getElementById("resultado").innerHTML = llamadaAjax.responseText;
}
};
llamadaAjax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
llamadaAjax.send('codigo='+codigo);
}
</script>
</head>
<body>
<form action="Compiler" method="post">
<textarea rows="18" cols="70" id="codigo" name="codigo"></textarea>
<input type="submit" value="Compile" onclick="devolver_resultado(); return false;">
</form>
<div id="resultado">
</div>
</body>
</html>
I've debugged the javascript to see if the problem was where I assign the textarea value to the "codigo" variable:
var codigo = document.getElementById('codigo').value;
(screenshot)
But this variable is being correctly set, so I suspect the request is being incorrectly encoded (screenshot).
I'm new to ajax, but I assume this is controlled by llamadaAjax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
From this page I get that I should encode the form as multipart/form-data. I tried adding the encoding type to the form: but this didn't help.
So, two questions here:
1) Is actually this line the faulty one? llamadaAjax.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
If so, how do I fix it?
2) If that's not where the bug is, what else could be happening? (remember that removing all the ajax and leaving a plain form that calls my "Compiler" servlet works as expected, so the servlet is not buggy).
Thanks!
SOLVED.
All I needed was to encode the text before sending it:
llamadaAjax.send('codigo='+encodeURIComponent(codigo));

A simple example of using AJAX with CodeIgniter?

Here I have a simple, working, AJAX example of a webpage that displays data from a text file, without having to refresh the page, through a simple button command.
ajax_test.php
<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>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
I am trying to get this to work in the exact same way, except through CodeIgniter. My pages are displayed using the following coding.
pages.php
<?php
// To avoid outside users from accessing this file
if(!defined('BASEPATH')) exit('No direct script access allowed');
class Pages extends CI_Controller
{
// Default method if one has not been requested within the URL
public function view($page = "home")
{
if(!file_exists('application/views/pages/'.$page.'.php')) // If the page does not exist
{
// Whoops, we don't have a page for that!
show_404();
}
$data["main_url"] = $this->config->item("base_url")."z_my_folders/";
$data["title"] = ucfirst($page); // Capitalize the first letter
$this->load->view("templates/header", $data);
$this->load->view("pages/".$page, $data);
$this->load->view("templates/footer");
}
}
All this does is displays the webpage when the "view" method is called (for example, pages/view/ajax_test) whiles carrying the server's main URL as a string in order to allocate files such as images, CSS, and the jQuery library through the header.
header.php
<html>
<head>
<link href="<?php echo $main_url; ?>design.css" rel="stylesheet" type="text/css">
<title>Kurtiss' Website - <?php echo $title ?></title>
<script type="text/javascript" src="<?php echo $main_url; ?>jquery/jquery-1.10.2.min.js"></script>
</head>
The ajax_test.php file displays in CodeIgniter accordantly, however when the button is pressed, nothing happens. Again, the file works fine when it is not in CodeIgniter, however I am trying to make it so that it can.
I have tried researching it, except all I can find are complex examples where users are connecting to databases, creating complex login forms, registration forms, chat rooms, etc. I just want a simple example like this one that says "Yes, this is AJAX, and it works with CodeIgniter."
Many thanks.
I have edited the code as followed.
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
else
{
alert("ERROR");
}
}
When testing it in CodeIgniter, the alert message pops up four times, so it might have something to do with the xmlhttp.readyState.
Now I know what the problem was; it just couldn't find the text file. In order for it to work, I had to either relocate the text file into the CodeIgniter's main directory, or specify where the text file was located.
Thanks for your help guys.

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 not working with XAMPP or is it just impossible

I'm still relatively new to AJAX and am trying to figure out why my simple test is not working. From what I read AJAX will not work under one domain, and other words pop up like cross-site and remote server. Anyways my problem is is that I'm not sure if my code is wrong or simply what I'm trying to do is impossible. I created a simple ajax request to submit data when I click on the button. Here is the code for the first script.
<html>
<head>
<script type="text/javascript" >
function load(thediv, thefile) {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById(thediv).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', thefile, true);
xmlhttp.send();
}
</script>
</head>
<body>
<input type="submit" onclick="load('adiv', 'hello.php');">
<div id="adiv"></div>
</body>
</html>
Here is the code for the file hello.php
<?php
echo 'aaa';
?>
AJAX is just an http request done in the background. But yes, there are security restrictions that prevent you doing a normal ajax request to any arbitrary server.
What your code is missing is actually setting the URL that you're placing the request to. You've got hello.php as a parameter to your load() function, but you never actually USE it. So you're doing an AJAX request to... "nowhere".

server crashes when i use onreadystatechange

I am trying to create a chat for my website.
To load the new data, i run a function every 1.5''.
If i use asynchronous mode, my website is fast, my server does not crash, but browser freezes until the response.
When i use synchronous mode, my server crashes after a while, and i have to restart Apache (! ?).
I thought that i was requesting too much data and my (virtual) server crashes, but why in asynchronous mode works fine ?
function loadchat() {
xmllive.open('GET','live.php', false);
xmllive.send(null);
myelemen('dcdd').innerHTML = xmllive.responseText;
}
function loadchatv() {
xmllive.onreadystatechange=function() {
if (xmllive.readyState==4 && xmllive.status==200){
myelemen('dcdd').innerHTML = xmllive.responseText;
}
}
xmllive.open('GET','live.php', true);
xmllive.send();
Thank you for your answer, MMM. Since your response, i read about your suggestions.
(http://dsheiko.com/weblog/websockets-vs-sse-vs-long-polling).
I figured that, in Long Pooling the server makes a loop until finds new data and only then browser receives and makes a new request.
So, tell me please, what do you think about this solution (simplified):
/////////// html file //////////////
<script type="text/javascript" charset="utf-8">
var xmlff;
if (window.XMLHttpRequest) {
xmlff=new XMLHttpRequest();
} else {
xmlff=new ActiveXObject("Microsoft.XMLHTTP");
}
function waitForMsg(){
xmlff.onreadystatechange=function() {
if (xmlff.readyState==4 && xmlff.status==200){
document.getElementById('messages').innerHTML = xmlff.responseText ;
setTimeout('waitForMsg()', 1000 );
}
}
xmlff.open('GET','msgsrv.php' ,true);
xmlff.send();
}
</script>
</head>
<body>
<div id="messages">
</div>
<script type=text/javascript>
waitForMsg()
</script>
</body>
</html>
/////// php file ///////////
<?
do {
sleep(3);
$result = mysql_query("SELECT message FROM chat ");
while ($row = mysql_fetch_array($result)){
$msg .= $row[0];
}
} while (mysql_num_rows($result) == 0);
header("HTTP/1.0 200");
print $msg;
?>
Thanks in advance.

Resources