passing variables through parameters AJAX PHP JAVASCRIPT - 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.

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, php and mysql connection issues

Am fetching data from database using ajax but it is failing. The data should be displayed at the div I have declared in the main page called 'display'. The query runs but nothing is printed on the div. Here are my codes:
//ajax:
<script>
function Jobs(str) {
if (str == "") {
document.getElementById("display").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("display").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST","search.php?q="+str);
xmlhttp.send();
}
}
</script>
//php
?php $q = intval($_GET['q']);?>
<?php
include('includes/conn.php');
$row="SELECT DISTINCT title,id FROM jobs WHERE dept='$q' AND state=0 ORDER BY id";
$query=mysqli_query($conn,$row) or die(mysqli_error($conn));
while($row=mysqli_fetch_array($query))
{
echo $row['title'];
}
mysqli_close($conn);
?>
Sample ajax example codes
addfield.php file:
<html>
<head>
<script>
function Jobs(str) {
if (str == "") {
document.getElementById("display").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("display").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST","search.php?q="+str);
xmlhttp.send();
}
}
</script>
</head>
<body>
<p><b>Start typing a name in the input field below:</b></p>
<form>
First name: <input type="text" onkeyup="Jobs(this.value)">
</form>
<p>Suggestions: <span id="display"></span></p>
</body>
</html>
search.php code:
<?php
echo $q = $_REQUEST["q"];
?>

Ajax , Cannot read property 'documentElement' of null

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

php created select tag with ajax

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();
}

AJAX Silent Update from database

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:

Categories