AJAX not working with XAMPP or is it just impossible - ajax

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".

Related

Ajax - understanding of the code

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).

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.

jQuery Mobile ajax request

I am trying to retrieve information from a javascript file in my jQuery mobile website. Ajax is enabled by default, yet when I try xmlHttpRequest.send(), the responseText is the source code for the page rather than a json structure. The initialize() function is run at pageinit, so my thinking is that the json it is retrieving should exist when called. Also, initialize() works fine on the non-mobile variant of the site so I think it has something to do with how JQM handles ajax requests. Thanks in advance for any assistance.
<!DOCTYPE html>
<html>
<head>
var xmlHttpRequest;
var json;
<script type="text/javascript">
function initialize()
{
xmlHttpRequest = (window.XMLHttpRequest) ? new XMLHttpRequest() :
new ActiveXObject("Msxml2.XMLHTTP");
if (xmlHttpRequest == null)
return;
xmlHttpRequest.open("GET", "pick.js", false);
xmlHttpRequest.send();
json = eval('('+ xmlHttpRequest.responseText +')');
}
</script>
......
</head>
<body>
<div data-role="page" id="map-page">
<script type="text/javascript">
$('#map-page').live('pageinit',function(){
initialize();
});
</script>
.....
</div>
</body>
</html>
Since you're using jQuery Mobile (and thusly, jQuery), you should consider using jQuery.ajax -- it handles all of the 'hard stuff' like creating XHR object for you.
For your situation your code would look like this:
function initialize() {
$.get("pick.js", function(data, status, jqXHR) {
//when the call succeeds, do something with the 'data' param
console.log(data);
}, "script");
}

Resources