Ajax , Cannot read property 'documentElement' of null - javascript

I was watching the New Boston tutorial on Ajax training and I wrote the same code as the tutor of the course did. But the code doesn't work in my computer.
In Google chrome
Uncaught TypeError: Cannot read property 'documentElement' of null
message = xmlHttp.responseXML.documentElement.firstChild.data;
In Firefox
not-well formed bookname.php:5:8
echo '<response>';
index.html
<body onload="process()">
<h1>Users information</h1>
Enter user_name you would want to know about:
<input type="text" id="userInput" />
<div id="underInput" />
</body>
bookname.php
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<response>';
$name = $_GET['userName'];
$nameArray = array('Mehrshad', 'Alex', 'Tom', 'Aydin');
if(in_array($name, $nameArray)
{
echo 'I do know '. $name . '!';
}
else if($name == '')
{
echo 'Enter a name you want to know about';
}
else
{
echo 'Sorry we don\'t have user "'. $name . '" '
}
echo '</response>';
?>
bookname.js
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject()
{
var xmlHttp;
if(window.ActiveXObject)
{
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
xmlHttp = false;
}
}
else
{
try{
xmlHttp = new XMLHttpRequest();
} catch(e) {
xmlHttp = false;
}
}
if(!xmlHttp)
{
alert('can\'t create that object hoss!')
}
else
{
return xmlHttp;
}
}
function process()
{
if(xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
{
username = encodeURIComponent(document.getElementById('userInput').value);
xmlHttp.open("GET", "bookname.php?userName=" + username, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}
else
{
setTimeout('process()', 1000);
}
}
function handleServerResponse()
{
if(xmlHttp.readyState == 4)
{
if(xmlHttp.status == 200)
{
message = xmlHttp.responseXML.documentElement.firstChild.data;
document.getElementById("underInput").innerHTML =
'<span style="color: blue"' + message + '</span>';
setTimeout('process()', 1000);
}
else
{
alert('Something went wrong!');
}
}
}

your php code is invalid because:
you're missing ; in echo 'Sorry we don\'t have user "'. $name . '" ';
end parentheses ) is missing in if(in_array($name, $nameArray))
> is missing in document.getElementById("underInput").innerHTML = '<span style="color: blue">' + message + '</span>';

I was also running the same code but it was showing same error as mentioned above. Please suggest the solution because I didn't make the above-mentioned mistakes still it says Uncaught TypeError: Cannot read property 'documentElement' of null at XMLHttpRequest.handleServerResponse.

http_request.overrideMimeType('application/xml'); was working for me when IAm fixing between IE to chrome migration

Related

Extra content at the end of the document - Ajax

When I run my code this error appears :
This page contains the following errors:
error on line 2 at column 1: Extra content at the end of the document
Below is a rendering of the page up to the first error.
I made my code in two files: javascript and php like this:
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<response>';
$food = isset($_GET['food']);
$foodArray = array('tuna', 'bacon', 'beef');
if(in_array($food, $foodArray)){
echo 'We do have'.$food;
}
elseif($food==''){
echo 'Enter a food';
}else{
echo 'We dont sell'.$food;
}
echo '</response>';
?>
<html>
<head>
<script src="index.js"></script>
</head>
<body onload="process()">
<form method ="get" action="index.php"><input type="text" id="userInput"/></form>
<div id="underInput"></div>
</body>
</html>
and
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject(){
var xmlHttp;
if(window.ActiveXObject){
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
xmlHttp = false;
}
}else{
try{
xmlHttp = new XMLHttpRequest();
}catch(e){
xmlHttp = false;
}
}
if(!xmlHttp){
alert("Error")
}else{
return xmlHttp;
}
}
function process(){
if(xmlHttp.readyState == 0 || xmlHttp.readyState == 4){
food = encodeURIComponent(document.getElementById("userInput").value);
xmlHttp.open("GET", "index.php?food=" + food,true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}else{
setTimeout('process()', 1000);
}
}
function handleServerResponse(){
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
xmlResponse = xmlHttp.responseXML;
xmlDocument = xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.dataa;
document.getElementById("underInput").innerHTML = '<span style="color:blue">' + message + '</span>';
setTimeout('process()', 1000);
}else{
alert("Error1");
}
}
}
Can somebody help?
Thanks
The error comes because of html code.
Make different php file. Dont add html code in that
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<response>';
$food = isset($_GET['food']);
$foodArray = array('tuna', 'bacon', 'beef');
if(in_array($food, $foodArray)){
echo 'We do have'.$food;
}
elseif($food==''){
echo 'Enter a food';
}else{
echo 'We dont sell'.$food;
}
echo '</response>';
?>
do changes in html file use keyup or any other function dont use onload functin
<html>
<head>
<script src="xml.js"></script>
</head>
<body>
<form method ="get" action="test.php">
<input type="text" id="userInput" onkeyup = "process();"/>
</form>
<div id="underInput"></div>
</body>
</html>
codepad

AJAX call the PHP script not outputting any results

I am trying to update my list of tweets via AJAX. I have ran the script on the page and know that script works, and I have a console.log line in my ajax call so I know that is getting hit as well.
setInterval(function () {sendRequest()}, 5000);
function sendRequest(){
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){
console.log("yay");
}
}
xmlhttp.open("GET","getTweets.php",true);
xmlhttp.send();
}
My AJAX should run every 5 seconds, and the hit the PHP script to return new results that have been stored in the database. My PHP looks like:
$conn = mysqli_connect("localhost", "*", "*", "*");
if (!$conn) {
echo("Connection failed: " . mysqli_connect_error());
}
$query = "SELECT * FROM tweets;";
$results = mysqli_query($conn, $query);
while($list = mysqli_fetch_assoc($results)){
echo '<div class="tweet-containter">';
echo '<img class="user-img" alt="user-img" src="images/gb.png">';
echo '<h3 class="tweet-username">#'.$list['username'].'</h3>';
echo '<p class="tweet-body">'.$list['tweetBody'].'</p>';
echo '<p class="tweet-body">Tweeted: '.$list['datePosted'].'Retweet: <i class="fa fa-retweet" id="retweet4" onclick="retweetAJAX()"></i> Like: <i class="fa fa-thumbs-up" id="likes4" onclick="likeAJAX()"></i> Dislike: <i class="fa fa-thumbs-down" id="dislikes4" onclick="dislikeAJAX()"></i></p>';
echo '</div>';
}
This goes for those that do not understand ReadyState codes. You should know the following codes for ReadyState:
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
And Status Code
200: "OK"
404: Page not found
with that said, try doing this:
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if(xmlhttp.status == 200){
console.log(xmlhttp.responseText);
} else if(xmlhttp.status == 400) {
alert('There was an error 400')
} else {
alert('something else other than 200')
}
}
}
ryandonohue,
PHP is a Hyper-Text Processor. PHP runs on your server & the results are generated before the page is loaded. You should not be using PHP to output results like HTML elements, it is much more appreciated if you use JavaScript to manipulate the Document Object Model (DOM).
Though, for your intermediate purposes you might not notice an immediate difference.
For PHP5 you should look into the usage of PHP-PDO http://php.net/manual/en/class.pdo.php to prevent SQL injection.
Modification:
function getall($table, $values, $conditions = null, $limit = null, $ascdesc = null){
$values_str = "";
foreach($values as $key => $value){
$values_str .= $value . ", ";
}
$cond_str = "";
$hascond = false;
if($conditions != null){
$hascond = true;
foreach($conditions as $key => $value){
$cond_str .= $key . "='" . $value . "' AND ";
}
$cond_str = rtrim($cond_str, " AND ");
}
$values_str = rtrim($values_str, ", ");
$cond_str = " WHERE (" . $cond_str . ")";
$orderby = "";
$hasorder = false;
if($ascdesc != null){
$hasorder = true;
foreach($ascdesc as $key => $value){
$orderby = " ORDER BY " . $value . " " . $key;
break;
}
}
$sql = "SELECT " . $values_str . " FROM " . $table . " " . (($hascond)? $cond_str: "") . (($hasorder)? $orderby: "") . (($limit)? " LIMIT " . $limit: "");
//echo $sql;
$sql_prep = (new PDO('mysql:host=localhost;dbname=' . 'database', 'username', 'Password'))->prepare($sql);
$sql_prep->execute();
return $result = $sql_prep->fetchAll(PDO::FETCH_ASSOC);
}
initialization: ( returns an array so you need to json encode)
getall('table',
Array(
'*'
),
null, 5, null);
AJAX:
function ajax(file,type, params, func){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//xmlhttp.responseText
func(xmlhttp.responseText);
}
}
if(type.toLowerCase() != "post"){
xmlhttp.open(
type, file + "?" + params_to_get(params),
true
);
xmlhttp.send();
}else{
xmlhttp.open(
type, file,
true
);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(params_to_get(params));
Since you have an error code of readystate of 4 with a status of 500 i would say the issue is more with the compatibility of MYSQLi or the way your table is set up with your database.
check out this POST for more information about headers:
Ajax call to PHP is returning nothing

passing variables through parameters AJAX PHP JAVASCRIPT

I'm trying to write a simple AJAX code to get it to search through a simple array, and output the results to the screen, and it works before I tried to pass the variables through the parameter, but now it isn't passing the variables through the parameters for some reason. Please take a look:
functions.js:
var xmlHttp = createXmlHttpRequestObject();
//****************************************************************AJAX
function createXmlHttpRequestObject() {
var xmlHttp;
if (window.ActiveXObject) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
xmlHttp = false;
}
} else {
try {
xmlHttp = new XMLHttpRequest();
} catch (e) {
xmlHttp = false;
}
}
if (!xmlHttp)
alert("Not xmlHttp!")else
return xmlHttp;
}
//****************************************************************AJAX
function process(IDName, passTo, output) {
if (xmlHttp.readyState == 0 || xmlHttp.readyState == 4) {
get = encodeURIComponent(document.getElementById(IDName).value);
xmlHttp.open("GET", passTo + get, true);
xmlHttp.onreadystatechange = handleServerResponse(output);
xmlHttp.send(null);
} else {
setTimeout('process()', 1000);
}
}
//****************************************************************AJAX
function handleServerResponse(output) {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data;
document.getElementById(output).innerHTML = message;
setTimeout('process()', 1000);
} else {
alert('xmlHttp.status does not equal 200!');
}
}
}
foodstore.php:
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<response>';
$food = $_GET['food'];
$foodArray = array('tuna','bacon','beef','ham');
if(in_array($food,$foodArray))
echo 'We do have '.$food.'!';
elseif ($food=='')
echo 'Enter a food';
else
echo 'Sorry punk we dont sell no '.$food.'!';
echo '</response>';
?>
test5.html:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="functions.js"></script>
</head>
<body onload="process('userInput','foodstore.php?food=','underInput')">
<h3>The Chuff Bucker</h3>
Enter the food you would like to order:
<input type="text" id="userInput" />
<div id="underInput" />
</body>
</html>
Try adding console.log(variable) on different stages to check the current state of variables, probably you are having problems with the get variable with the encodeURIComponent or maybe it isn't entering to that if on process function.

xmlhttp response Text

I am trying to update a particular div of my web page without reloading the complete page. Instead on response complete web page gets inserted in the targetid. I am using a javascript function to do so. Here are my code of php from where javascript function is called.
if($check_like==0)
{
// if user has not liked this post
$divid_like = $postid.'like';
echo "<div id='$divid_like'><a href='#' onClick=\"ajax_post('Ajax.php?action=Like-Status','postid=$postid','$divid_like',0);\" name='Like'> Like </a> </div>";
//echo "<a href='action.php?action=Like-Status&postid=$postid' name='Unlike'> Like </a>";
echo "<a href='#' onClick='' > Comment </a>";
echo "<a href='#' onClick='' > Share </a>";
}
Here is my javascript function :
<script language="JavaScript">
function ajax_post(url , args , targetid, add)
{
var xmlhttp;
if(window.XMLHttpRequest)
{
// works for all browser abve IE7, chrome and firefox
xmlhttp = new XMLHttpRequest();
}
else
{
//for IE5 and IE6 which i don't think i nedd to handle still
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if(!xmlhttp)
document.getElementById(targetid).innerHTML = "somesdlkvnoisnvoanfvnfnerroor";
xmlhttp.open("POST",url, false);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
//xmlhttp.setRequestHeader("Content-length", args.length);
//xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.onreadystatechange=function()
{
var xhr = event.target;
if(xhr.readyState==4 && xhr.status==200)
{
if(add==0)
{
document.getElementById(targetid).innerHTML = xhr.responseText;
}
else
{
document.getElementById(targetid).innerHTML+= xhr.responseText;
}
}
else
{
document.getElementById(targetid).innerHTML = "somebigbigbigrroor";
}
};
xmlhttp.send(args);
}
Ajax.php file being called to process data:
<?php
include_once("Includes/master_login.inc");
include_once("Includes/connect_to_database.php");
include_once("Includes/Users.php");
include_once("Includes/Friends.php");
include_once("Includes/current_page_url.php");
include_once("JavaScript/XML.js");
include_once("profile_display.php");
include_once("Includes/Status_Likes_Comment.php");
include_once("Includes/message.php");
include_once("Includes/NewsFeed.php");
include_once("sendmessage.php");
$action = $_GET["action"];
$uid = $_SESSION['uid'];
//if(!user_online($uid)){$action=0;}
if($action=="Add-Friend") { add_friend($uid,$_POST["uid"]); if($_POST["refresh"]="profile") echo display_profile($_POST["uid"]); }
if($action=="Respond-Friend-Request") {friend_accept($_POST["uid"],$uid); if($_POST["refresh"]="profile") echo display_profile($_POST["uid"]); }
if($action=="Like-Status") { like_status($uid,$_POST["postid"]); echo "Unlike"; }
if($action=="Chat-Send") {add_message($uid,$_POST["to"],$_POST["message"]); echo display_message($uid,$_POST["to"]);}
//if($action=="Chat-Send") {echo $_POST["message"]; delay(1000);}
?>
On liking the status instead of being replaced by Unlike complete page gets loaded in this div.

I am trying to fetch image from database using ajax in php

here's my code i am trying to fetch image from Data Base using ajax but its not working please hep me out . image uploading working properly when i am trying to fetch image using anchor tag but it show my image on another page . but i want on same page at window load time.
getImage.php
if(filter_has_var(INPUT_GET, "image_id") !== false && filter_input(INPUT_GET, 'image_id', FILTER_VALIDATE_INT) !== false)
{
$image_id = filter_input(INPUT_GET, "image_id", FILTER_SANITIZE_NUMBER_INT);
try {
$dbh = new PDO("mysql:host=localhost;dbname=flipbook", 'root', '');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT image, image_type FROM testblob WHERE user_id=$image_id";
/*** prepare the sql ***/
$stmt = $dbh->prepare($sql);
$stmt->execute();
/*** set the fetch mode to associative array ***/
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$array = $stmt->fetch();
if(sizeof($array) == 2)
{
header("Content-type: ".$array['image_type']);
echo $array['image'];
}
else
{
throw new Exception("Out of bounds Error");
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
catch(Exception $e)
{
echo $e->getMessage();
}
}
else
{
echo 'Please use a real id number';
}
}
index.php
<body onload="showUserProfilePic(<?php echo $_SESSION['current_user_id'];?>)">
<div id="txtHint">Child Picture will be listed here.</div>
<script>
function showUserProfilePic(str) {
//alert(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","getImage.php?image_id="+str,true);
xmlhttp.send();
}
}
Try using
$sql = "SELECT image, image_type FROM testblob WHERE user_id='" . $image_id . "';
and where is your tag?

Categories