xmlhttp.responseText not outputting to innerHTML - javascript

I'm trying to familiarize myself with Ajax as I will need to use it continually for work. I'm working through the W3Schools tutorial trying things with my Apache2 server. I have a file called ajax_info.txt on the server (under /var/www (ubuntu)). I'm making a call to it and with Firebug I see I get a good response (4 & 200) but it isn't outputting the contents of the file to the DOM. Here's the code:
<!DOCTYPE html>
<html>
<head>
<script>
var xmlhttp;
var url = "http://192.168.0.5/ajax_info.txt";
function loadXMLDoc(url, cfunc) {
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 = cfunc;
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function myFunction() {
loadXMLDoc(url, function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
});
}
</script>
</head>
<body>
<div id="myDiv">
<h2>Let AJAX change this text</h2>
</div>
<button type="button" onclick="myFunction()">Change Content</button>
</body>
</html>
I'm not exactly sure what it is I'm doing wrong. The w3schools tutorial isn't exhaustive by any stretch. I plan on buying a book, but I'd love to learn these simple GET calls as it will get me headed in the proper direction. Any suggestions would be greatly appreciated.

function ajax(x) {
var a;
if (window.XMLHttpRequest) {
a = new XMLHttpRequest();
} else if (window.ActiveXObject) {
a = new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert("Browser Dosent Support Ajax! ^_^");
}
if (a !== null) {
a.onreadystatechange = function() {
if (a.readyState < 4) {
//document.getElementById('cnt').innerHTML = "Progress";
} else if (a.readyState === 4) {
//respoce recived
var res = a.responseText;
document.getElementById('center_scrolling_div').innerHTML = res;
eval(document.getElementById('center_scrolling_div').innerHTML);
}
};
a.open("GET", x, true);
a.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
a.send();
}
}

Related

How to load a script in a php file called from a Ajax Request?

I have this JavaScript:
<script>
if (str == "") {
document.getElementById("txtHint1").innerHTML = "";
return;
} else {
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 (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint1").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "/npsmart/umts/action_plano/?q=" + query1, true);
xmlhttp.send();
}
</script>
And this JavaScript call a page called getuser.php.
This is the code of getuser.php:
<!DOCTYPE html>
<html>
<body>
<p id="dumb"></p>
<script>
document.getElementById("dumb").innerHTML = "WORK";
</script>
</body>
</html>
What I would like is only to change the paragraph content, called dumb, to WORK. But when I call the page and it loads, my paragraph content keep null.
It's like my Ajax Call Request don't execute the Script Tag.
EDIT:
I have already solved my problem with this simple but genious solution:
function showUser() {
if(query_num == 2){
if (str == "") {
document.getElementById("txtHint1").innerHTML = "";
return;
} else {
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 (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint1").innerHTML = this.responseText;
eval(document.getElementById("runscript").innerHTML);
}
};
xmlhttp.open("GET","/npsmart/umts/action_plano/?q="+55555,true);
xmlhttp.send();
}
And in my getuser.php file:
<script type="text/javascript" id="runscript">
document.getElementById("dumb").innerHTML = "WORK";
</script>
I just putted the : eval(document.getElementById("runscript").innerHTML); in my function and then in the php file I called this script using this:
<script type="text/javascript" id="runscript">
So thanks everybody =)
Hope this post can help other people.
JS is not executed automatically from a script embedded in the response.
Since getuser.php is a PHP script there's no need to use JS and have the browser set the paragraph content. Use PHP itself:
<!DOCTYPE html>
<html>
<body>
<p id="dumb"><?php echo 'WORK'; /* or anything else */ ?></p>
</body>
</html>
Otherwise you'll have to use JS eval on the returned AJAX response to have the browser run the JS returned from your script. But I recommend against this.

Ajax calls in symfony framework

I wanna make ajax calls in symfony2. I already done with ajax with flat php and i have no idea how to set up in this symfony framework.
<html>
<head>
<script>
function showBook(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
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("txtHint").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
}
function showAuthor(str){
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
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("txtHint").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","getAuthor.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form action="">
Book name: <input type="text" id="txt1" onkeyup="showBook(this.value)">
<br><br>
Author name:<input type="text" id="txt1" onkeyup="showAuthor(this.value)">
</form>
<br>
<div id="txtHint"><b>book info will be listed here...</b></div>
</body>
</html>
Where should i pass this request?? to controller??
how to set routes??
is there any way to use flat php instead of controller??
You would pass the request to a controller action exposed using a route:
http://symfony.com/doc/current/book/routing.html
Then in your html code, if you are using twig and including javascript in a script tag, you can do
xmlhttp.open("GET","{{ path("route_name", {"parameter_name":"parameter_value"}) }}");
If you want to access the route in an attached .js file, you can use FOSJsRoutingBundle to generate the route url
If you are in a form, you can do something like :
$(document).submit(function () {
var url = $('form').attr('action');
var data = $('form').serialize();
$.post(url, data, function (data) {
window.location.href = data.redirect;
})
.fail(function () {
$('form').replaceWith(data.form);
});
});
You just need to send the correct url :
$(document).on('click', 'a', function () {
var url = window.location.href;
$.get(url, function (data) {
$('.container').replaceWith(data);
});
});
It is also possible to use a routing generate, simply add:
"friendsofsymfony/jsrouting-bundle": "dev-master" to your composer.json.
AppKernel.php :
new FOS\JsRoutingBundle\FOSJsRoutingBundle()
Then config it in your routing.yml :
fos_js_routing:
resource: "#FOSJsRoutingBundle/Resources/config/routing/routing.xml"
And finally use "expose" arg in your routing :
#Route("/{table}/index", name="beta.index", options={"expose"=true})
I use annotation routing
In your JS :
var url = Routing.generate('beta.index', { 'table': 'foo' });
Hope it'll help you :)

Cannot click on the content which is loaded through ajax function

Currently, I cannot load the second content using ajax. Actually, I have loaded the first content using ajax. In order to go to the second content, i need to call the ajax function but after i click to load the second content using ajax it does not work. I have checked my code, its working fine if i directly call the second ajax function, unless i call the first ajax function after that the ajax is not working again. Are there any ways to solve this problem.
This is the first ajax code:
function showMusic(str) {
if (str == "") {
document.getElementById("albums").innerHTML = "";
return;
} else {
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("albums").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","getAlbums.php?q="+str,true);
xmlhttp.send();
}
}
The above function works. The above function is at another php file
This is the second ajax code:
$(document).ready(function(){
function showArtistDetails(str) {
if (str == "") {
alert("hi");
document.getElementById("artist").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
alert("hi1");
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
alert("hi2");
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("artist").innerHTML = xmlhttp.responseText;
alert("hi3");
}
};
xmlhttp.open("GET","getArtist.php?title="+str,true);
alert("hi4");
xmlhttp.send();
alert("hi5");
}
}
$("#clickme").click(showArtistDetails);
});
This is the php code which is at another php file:
echo "<td id=\"clickme\">" . $row['CDTitle'] . "</td>";
I have been trying to solve this for the past 2 days but i am unable to solve it. Some are saying its a bug. But i really i dont know what causes this problem. Thanks in advance.

AJAX: Why does $_REQUEST on server side not contain the variable passed from JS in URL by GET method?

I have three divs saved in an array as simple_html_dom objects. I needed to change a CSS property of two of them on the click of a button. That's easy, but then I also need to make that change in the CSS property (in the simple_html_dom object stored in the aforementioned array) in the PHP script on the server side.
So I figured from my web search I needed AJAX for this. So I read up this tutorial, and I am following this example, and doing something like:
On the client side:
function xyz(var divIdOne, var divIdTwo) {
document.getElementById(params.divIdOne).style.display = "none";
document.getElementById(params.divIdTwo).style.display = "block";
document.getElementById(params.divIdTwo).style.border = "5px solid red";
var xmlhttp;
if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest();}
else { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }
xmlhttp.open("GET","myfile.php?pass_back="+"pass_back",true);
xmlhttp.send();
}
On server side:
foreach($_REQUEST as $requestkey => $requestvalue) {
echo $requestkey.': '.$requestvalue;
}
if (array_key_exists('pass_back', $_REQUEST)) {
foreach ($array_of_divs as $div) {
if ($div->id=$divIdOne) {
$div->style='display:none';
} else if ($div->id=$divIdTwo) {
$div->style='display:block';
}
}
} else {echo 'FALSE!';}
The first foreach loop prints other variables but does not print pass_back. The next if block does not execute at all. The else block executes. This means that $_REQUEST clearly does not contain pass_back. Can anyone pinpoint why, or what I did wrong?
I fail to see the error. How do you check that you're not sending the data properly? I suggest using this piece of code in order to check what your server is receiving from your request:
function xyz() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log(xmlhttp.responseText);// Let's see what the server is echoing
}
}
xmlhttp.open("GET","myfile.php?pass_back="+"pass_back",true);
xmlhttp.send();
}
Please, let us know the output.
I would recommend that you use jquery and firebug, and first get rid of the following problem: why is passback variable not received.
Create the file: test.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<script src="https://code.jquery.com/jquery-2.1.1.js"></script>
<title>Html page</title>
</head>
<body>
<script>
(function($){
$.post("myfile.php", {
passback: "pooo"
}, function(d){
console.log(d);
});
})(jQuery);
// or if you cannot use jquery
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) {
// do something with the response, if you need it...
// document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "myfile.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("passback=pooo");
// src: http://www.w3schools.com/ajax/ajax_xmlhttprequest_create.asp
</script>
</body>
</html>
Then create the file: myfile.php
<?php
if(isset($_REQUEST['passback'])){
echo "ok";
}
else{
echo "oops";
}
Next, download firefox, and download the firebug extension (or you can use chrome's console alternatively). The goal here is to see what is being passed through the network.
Launch test.php in a browser, open the firebug console (or chrome's console),
and debug until you see the "ok" message.

Simple AJAX example - load data from txt file

I'm trying to do a basic AJAX tutorial to read data from a file, hello.txt, into my webpage. hello.txt and my current html webpage are in the same directory. Does anyone know what I'm doing wrong? Nothing happens when I load the page.
<!DOCTYPE html>
<head><title>Ajax Test</title>
<script type="text/javascript">
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "hello.txt", true);
xmlHttp.addEventListener("load", ajaxCallback, false);
xmlHttp.send(null);
function ajaxCallback(event){
alert( "Your file contains the text: " + event.target.responseText );
}
</script>
</head>
<body>
</body>
</html>
here is a function i always use for simple async get ajax:
1.use onload as it's shorter to write and as you don't need to add multiple eventhandlers.
2.don't do syncronous ajax.
js
function ajax(a,b,c){//url,function,just a placeholder
c=new XMLHttpRequest;
c.open('GET',a);
c.onload=b;
c.send()
}
function alertTxt(){
alert(this.response)
}
window.onload=function(){
ajax('hello.txt',alertTxt)
}
example
http://jsfiddle.net/9pCxp/
extra info
https://stackoverflow.com/a/18309057/2450730
full html
<html><head><script>
function ajax(a,b,c){//url,function,just a placeholder
c=new XMLHttpRequest;
c.open('GET',a);
c.onload=b;
c.send()
}
function alertTxt(){
alert(this.response)
}
window.onload=function(){
ajax('hello.txt',alertTxt)
}
</script></head><body></body></html>
Here is your answer.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var allText = this.responseText;
alert(allText);
}
};
xhttp.open("GET", "filename.txt", true);
xhttp.send();
The below code may be useful for someone...
<!DOCTYPE html>
<html>
<body>
<h1>Load Data from text file </h1>
<button type="button" onclick="loadDoc()">Change Content</button>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "info.txt", true);
xhttp.send();
document.getElementById("demo").innerHTML = xhttp.responseText;
}
</script>
</body>
</html>
Open an empty .PHP file or .ASPX file (or just any server-side language that can run javascript)
Paste this code between "head" tags.
<script>
var xmlhttp;
function loadXMLDoc(url, cfunc) {
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 = cfunc;
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function myFunction() {
loadXMLDoc("hello.xml", function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
});
}
</script>
As you see, javascript is referring to "hello.xml" file to get information from.
Open an empty XML file inside the project folder you have created in. Name your XML file as "hello.xml"
Paste this code to your XML file.
<?xml version="1.0" encoding="utf-8"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
Run your php (or .aspx) file on localhost.
Click on button, your page must acquire the XML data into your website.
function Go() {
this.method = "GET";
this.url = "hello.txt";
if (window.XMLHttpRequest && !(window.ActiveXObject)) {
try {
this.xmlhttp = new XMLHttpRequest();
}
catch (e) {
this.xmlhttp = false;
}
// branch for IE/Windows ActiveX version
}
else if (window.ActiveXObject) {
try {
this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
this.xmlhttp = false;
}
}
}
if (this.xmlhttp) {
var self = this;
if (this.method == "POST") {
this.xmlhttp.open("POST", this.url, true);
}
else {
//remember - we have to do a GET here to retrive the txt file contents
this.xmlhttp.open("GET", this.url, true);
}
this.xmlhttp.send(null);
//wait for a response
this.xmlhttp.onreadystatechange = function () {
try {
if (self.xmlhttp.readyState == 4) {
if (self.xmlhttp.status == 200) {
if (self.xmlhttp.responseText != null) {
self.response = self.xmlhttp.responseText;
alert(self.xmlhttp.responseText);
}
else {
self.response = "";
}
}
else if (self.xmlhttp.status == 404) {
alert("Error occured. Status 404: Web resource not found.");
}
else if (self.xmlhttp.status == 500) {
self.showHtmlError("Internal server error occured", "Status: " + self.xmlhttp.responseText);
}
else {
alert("Unknown error occured. Status: " + self.xmlhttp.status);
}
}
}
catch (e) {
alert("Error occured. " + e.Description + ". Retry or Refresh the page");
}
finally {
}
};
}
}
//Use the function in your HTML page like this:
Go();
</script>

Categories

Resources