I am trying to update a paragraph from my html document using ajax but its not working and there is not error.
It simply does not change the value of the paragraph.
Is there an error in my code?
Thank you.
PHP/XML:
<?php
header('Content-Type :text/xml');
echo '<?xml version="1.0"encoding="UTF-8"standalone="yes"?>';
echo '<response>';
$connect = mysql_connect("****","***","****");
mysql_select_db("****");
$query = mysql_query("SELECT * FROM questions WHERE number=1");
$query2 = mysql_fetch_array($query);
echo $query2['q1'];
echo '</response>';
?>
javascript
<script>
var xmlHttp = createXmlHttpRequstObject();
function createXmlHttpRequstObject() {
var xmlHttp;
try {
xmlHttp=new XMLHttpRequest();
} catch(e) {
xmlHttp=false;
}
if(!xmlHttp)
alert("NOPE");
else
return xmlHttp;
}
function refresh() {
if(xmlHttp.readyState==4||xmlHttp.readyState==0){
xmlHttp.open("GET","ref.php",true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
} else {
setTimeout('refresh()',1000);
}
}
function handleServerResponse(){
if(xmlHttp.readyState==4){
var xmlResponse = xmlHttp.responseXML;
var xmlDocumentElement = xmlResponse.documentElement;
var message= xmlDocumentElement.firstChild.data;
document.getElementById("choice1").innerHTML=message;
setTimeout('refresh()', 1000);
}
}
</script>
HTML:
Related
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
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.
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.
Good day this is my code of index
<!DOCTYPE html>
<html>
<body>
<script>
function show_month(var) {
if (windows.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","month.php?q="+var,true);
xmlhttp.send();
}
</script>
<?php
$from = (date('Y'));
$to = 2050;
echo '<form>';
echo '<select name="year" onchange="show_month(this.value)">';
for($y = $from; $y <= $to; $y++) {
echo "<option value=$y>{$y}</option>";
}
echo '</select>';
echo '<form>';
?>
<div id="txtHint"><b>here will be info</b></div>
</body>
</html>
and here is code of my month.php
<!DOCTYPE html>
<html>
<body>
<?php
$q = $_GET['q'];
echo $q;
if ($q == 2015) {
echo "actual year";
}
else {
echo "unactual year";
}
?>
</body>
</html>
As you see I created select tag with php so I can make multiple options of year just by using loop and I want that if I select year 2015 javascript should print message actual year but it isn't working I think that problem is somewhere in select or sending value can someone more intelligent than me look into this code and tell me whats is wrong?
Your js code does not have the response code. Also you have a few other errors in your code which will cause issues for you.
show_month(var) you cannot have var as this specific to JS, change it to something else.
windows.XMLHttpRequest This is window not windows.
In order to show what you need use;
alert(xmlhttp.responseText);
in your response if.
<script>
function show_month(t) {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","month.php?q="+t,true);
xmlhttp.send();
}
</script>
and finally you don't need <!DOCTYPE html> in your month.php if you are just returning text (most likely you will never need a reason for it).
Your js code is missing code to handle server response
<script>
function show_month(var) {
if (windows.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","month.php?q="+var,true);
xmlhttp.send();
}
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?