How to send javascript variable to php using ajax? - php

The scenario is , below is the html file through which i want to display the content of a text file at div id="myDiv".
The file will be read by php . The php content is given below.
I am unable to get the content from the text file . Please tell me what should be added in the ajax part to correct the program.
<html>
<head>
<script type="text/javascript">
function ajaxRequest(tb) {
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=statechange()
{
if (xmlhttp.readyState==4 && XMLHttpRequestObject.status == 200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","http://localhost/TBR/getdata.php?tb="+tb,true);
xmlhttp.send();
}</script>
</head>
<body>
<div >
<div id="myDiv">Text from file should come here.</div>
<button type="button" onclick="ajaxRequest(myfile.txt)">Change Content</button>
</div>
</body>
</html>
Below is the PHP file
<?php
$tbName = $_GET['tb'];
$file = "/home/$tbName";
$f = fopen("$file", "r");
echo "<ul>";
while(!feof($f)) {
$a= fgets($f);
echo "<li>$a</li><hr/>";
}
echo "</ul>";
?>

Fix quotes
onclick="ajaxRequest('myfile.txt')"
make sure you use encodeURIComponent() on tb
xmlhttp.open("GET","http://localhost/TBR/getdata.php?tb="+encodeURIComponent(tb),true);
Test your php page in the browser: does http://localhost/TBR/getdata.php?tb=myfile.txt provide the data you want?
If so test the function gets called. (Place an alert or debug the code and place a breakpoint within the function, or use console.debug if your browser supports it)
If the function gets called then your event handler is working correctly, if not try to rewrite it or attach it differently like onclick="ajaxRequest('myfile.txt');" though I suspect the missing semicolon isn't the problem.
If that is called you can try to see if the ajax call is carried out my inspecting the network traffic. Any decent browser will let you do that (hit f12 and look for the network tab). You should be able to see the request and response if the ajax request is being issued and responded to.
Supposing that is all working fine, ensure that your event ajax event handler is getting called. I suspect there is an issue here because you are not setting the event handler to a function...
xmlhttp.onreadystatechange = function statechange()
{
if (xmlhttp.readyState==4 && XMLHttpRequestObject.status == 200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
And failing all of that your data insert code isn't working.

<button type="button" onclick="ajaxRequest('myfile.txt')">Change Content</button>
Remember to quote the string in the onclick.
Here's a fixed version:
<html>
<head>
<script type="text/javascript">
function ajaxRequest(tb) {
if (window.XMLHttpRequest){
var xmlhttp= new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status == 200){
document.getElementById("myDiv").innerHTML=xmlhttp.responseText; }
}
xmlhttp.open("GET","http://localhost/TBR/getdata.php?tb="+ encodeURIComponent(tb),true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<div id="myDiv">Text from file should come here.</div>
<button type="button" onclick="ajaxRequest('myfile.txt')">Change Content</button>
</body>
</html>
What was wrong:
the presence of XMLHttpRequest was tested, but the function was not wrapped in an if, making that useless.
The variable names were a little mismatched - double check that
EncodeURI Component, as mentioned below
The proper syntax for a callback function is window.onload = function(){ alert('func!'); } not window.onload = alert(){ alert('load!'); }
That should be it, unless there's a problem with the PHP Script, try testing that out by visiting the URL directly.

Related

Really basic AJAX

I'm just starting out with AJAX. I'm trying to create a test where I enter some text into a text input box, click a submit button on a form, and have that text display on my page. The immediate error that I am getting is a 404 error ( www.mysite.com/ajaxFunction() ), but I'm sure that there are others yet to be discovered. Can anyone please help me correct this to get me started out with AJAX? I'm spinning my wheels trying to get started. Also, please realize that I am calling a php script since this is what my ultimate goal will require, which is why I'm not just using JavaScript itself. Thanks!
Here is the html:
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
</head>
<body>
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
window.onload = function ajaxFunction() {
document.myform.action = getFeedback();
}
function getFeedback() {
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("feedback").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","scripts/handle_feedback.php",true);
xmlhttp.send();
}
//-->
</script>
<div id="leftsidebox"></div>
<div id="textboxdiv">
<form name="myform">
Text Here: <input type="text" name="textbox" id="name" />
<button type="submit">Submit</button>
</form>
</div>
<div id="feedback">
</div>
</body>
</html>
handle_feedback.php
<?php
$mytext = $_REQUEST['textbox'];
return $mytext;
?>
EDIT: Here is my latest html code. I made the change to the php (switching 'return' to 'echo')
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
window.onload = function ajaxFunction() {
document.myform.onsubmit = getFeedback;
}
function getFeedback() {
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("feedback").innerHTML=xmlhttp.responseText;
}
}
var textvalue = document.getElementById("name").value;
xmlhttp.open("GET","scripts/handle_feedback.php?textbox="+textbox,true);
xmlhttp.send();
}
//-->
</script>
<div id="textboxdiv">
<form name="myform">
Text Here: <input type="text" name="textbox" id="name" />
<button type="submit">Submit</button>
</form>
</div>
<div id="feedback">
</div>
scripts/handle_feedback.php
<?php
$mytext = $_REQUEST['textbox'];
echo $mytext;
?>
This won't do what you're expecting it to do:
document.myform.action = getFeedback();
You're probably expecting it to make it call getFeedback when the form is submitted. That's not actually what happens. When the browser tries to run that code, it will realize: “oh, hey, we're assigning action. But wait, on the right hand side, there's a function call! I've got to evaluate that function call in order to find the return value to set action to!” And so your browser dutifully calls getFeedback immediately. Since getFeedback doesn't return anything, it sets action to undefined. Boy, that was helpful.
If we want a JavaScript function to be called when the form is submitted, setting action is not the right way to do it. So what is the right way? An event listener. The most common way of attaching an event listener is using addEventListener, but since your use case is rather simple, we're going to use a simpler, often neglected way: setting onsubmit:
document.myform.onsubmit = getFeedback;
Note that we do not have parentheses after getFeedback. This is intentional. We want to set onsubmit to the getFeedback function itself, not its return value.
You're also using textbox without defining it. Sure, it exists in the document, but that doesn't mean it's a variable available in the script. To access it, you'll need to first get the element and then get that element's value:
document.getElementById('name').value
Another thing that might be getting you is the same origin policy. Rather than using a complete URL to open, just pass a relative URL:
xmlhttp.open("GET", "something.php" /* ... */, true);
It should be echo not return. return is used in function to return the data.
<?php
$mytext = $_REQUEST['textbox'];
echo $mytext;
?>
Also you have to send the parameter to php file
xmlhttp.open("GET","scripts/handle_feedback.php?textbox=your_value",true);
First point : you missed request parameters from client end.
Send parameters in querystring for GET request.
var textvalue = document.getElementById("name").value;
xmlhttp.open("GET","scripts/handle_feedback.php?textbox="+textvalue ,true);
for more reference read here.
And second point is :
'return' statement is used with functions/methods. Since you don't have any function here, so instead of that use 'echo' or 'print' statement.
<?php
$mytext = $_REQUEST['textbox'];
echo $mytext;
?>

AJAX not working with text box

I'm learning AJAX and created this simple code. I type in something in the text box and it should return with the word something pop up on screen. This was able to work when I clicked on a button but now that I changed it to a text box it no longer works. Here is the first file that contains the XML HTTP Request data and HTML code.
<html>
<head>
<script type="text/javascript">
function load() {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('results').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', 'test_ajax_return.php', true);
xmlhttp.send();
}
</script>
</head>
<body>
<form id="search" name="search">Type a name:
<br>
<input type="text" name="search_text" onkeydown="load();">
</form>
<div id="results"></div>
</body>
</html>
And here is the second file that I want to open when the user types in something in the text box.
<?php
echo 'something';
?>
[SOLVED] : Thanks to Matt for Javascript Console. Found out some comments that I edited out effected the code after all. I didn't think HTML comments could do that. Lesson learned.
Open up your javascript console (F12 in Chrome) and see if there are any errors (indicated by a red X on the bottom of the popup).
You most likely have javascript errors that you're not catching.
I just copied the code to my machine, it works perfectly.
As an idea though, maybe your browser's being funny about onkeydown. Try onKeyDown instead.

about using ajax

I'm displaying the cotntent of a text file on web page(say between <div id='text'></text>)
this file's content is edited by any user who view the page, I already use ajax to write to the file and display to the current user, but if there are any users browsing the page at the same moment they have to refreh the page to see the new edited content.
I want to know how to use ajax to make the part that contain the file content remain updated continmuosly without refreshing the page
<script type='text/javascript'>
function change(){
if (window.XMLHttpRequest) xhr=new XMLHttpRequest();
else xhr=new ActiveXObject("Microsoft.XMLHTTP"); //IE5
xhr.onreadystatechange=function()
{
if (xhr.readyState==4 && xhr.status==200)
{
if(xhr.responseText=="empty") return;
document.getElementById("space").innerHTML=xhr.responseText;
}
}
var str=document.getElementById('msg').value;
document.getElementById("msg").value="";
xhr.open("GET","response.php?q="+str,true);
xhr.send();
}
</script>
<center>
<div id='space'>nothing</div>
<input type='text' name='msg' id='msg'>
<input type='button' onClick='change()' value='Click'>
</center>
The simplest way to accomplish the "server push" effect is through polling.
In your case, you can add this functionality by adding a simple Javascript statement:
window.onload = function()
{
setInterval("change();", 5000);
};
This code will call change(); every 5000 ms.
You could use setInterval() to perform a periodic AJAX query to check for updates. Then, if needed,update the content on the page.

Javascript via Ajax

How can i start javascript via ajax ?
html file
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>FusionCharts 3.0 Dashboard</title>
<script language="JavaScript" src="../FusionCharts.js"></script>
<script language="JavaScript" src="../PowerMap.js"></script>
<script type="text/javascript">
function loadXMLDoc()
{
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("ajax").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","test.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="chart3" align="center"></div><br />
<div id="ajax"></div>
<input type="button" onclick="loadXMLDoc()" value="test" />
</body>
</html>
php file
<?
$html = '<script type="text/javascript">
window.onload = function start() {
onClick();
}
function onClick() {
var myChart = new FusionCharts("../Charts/HLinearGauge.swf", "chart3", "580", "80", "0", "0");
myChart.setDataXML("<chart bgColor=\'FBFBFB\' bgAlpha=\'100\' showBorder=\'0\' chartTopMargin=\'0\' chartBottomMargin=\'0\'\n\
upperLimit=\'30\' lowerLimit=\'0\' ticksBelowGauge=\'1\' tickMarkDistance=\'3\' valuePadding=\'-2\' pointerRadius=\'5\'\n\
majorTMColor=\'000000\' majorTMNumber=\'3\' minorTMNumber=\'4\' minorTMHeight=\'4\' majorTMHeight=\'8\' showShadow=\'0\'\n\
pointerBgColor=\'FFFFFF\' pointerBorderColor=\'000000\' gaugeBorderThickness=\'3\'\n\ baseFontColor=\'000000\'\n\
gaugeFillMix=\'{color},{FFFFFF}\' gaugeFillRatio=\'50,50\'>\n\
<colorRange>\n\
<color minValue=\'0\' maxValue=\'5\' code=\'FF654F\' label=\'z\'/>\n\
<color minValue=\'5\' maxValue=\'15\' code=\'F6BD0F\' label=\'x\'/>\n\
</colorRange>\n\
</chart>");
myChart.render("chart3");
}
</script> ';
echo $html;
?>
For a start, you're defining a window.onload event AFTER the page has loaded - by the time the user clicks the button, that event will have been fired long ago
If you're using jQuery, change the window.onload = function start() to $(document).ready(function(), then add a ");" at the end of the function.
For Prototype, use document.observe("dom:loaded", function()
Though it'd probably make more sense to just call the function, or even just remove the function and execute the statements straight
As for the JS not executing - I've experienced that niggle before, it's because innerHTML doesn't run any JS that's inserted. If you're using jQuery, try $('ajax').append(xmlhttp.responseText), or Element.insert($('ajax'), xmlhttp.responseText) for Prototype.
Though judging by the fact you've implemented the AJAX call yourself, you're probably not using any libraries. In that case, it'd be easier to make your PHP file return just the JS without the tags, then just eval(xmlhttp.responseText)
If you don't want to do that, then you'll need to loop through all of the script tags in the response X(HT)ML and eval their contents 'manually'
Using Javascript frameworks make things really easy. For example, if you use jQuery, you can do what you want this way:
$.getScript("test.php");
It gives you some advantages... for instance, you won't have to worry about problems with memory leaks in IE. It will work on most of the web browsers and it will make your code easier to read.
You probably have to call the function you want, i.e. onClick, manually after setting the innerHTML.
All of that javascript you have in the PHP file, you need to put that into the html file. Well, that's the way I'd do it at least. Otherwise, you'll have to use jQuery's live() function to call those javascript functions you have in the PHP file.
For instance, your script tag in the html file should look like this
<script type="text/javascript">
function Function4PHPHTML() {
var myChart = new FusionCharts("../Charts/HLinearGauge.swf", "chart3", "580", "80", "0", "0");
myChart.setDataXML("<chart bgColor='FBFBFB' bgAlpha='100' showBorder='0' chartTopMargin='0' chartBottomMargin='0'\n
upperLimit='30' lowerLimit='0' ticksBelowGauge='1' tickMarkDistance='3' valuePadding='-2' pointerRadius='5'\n
majorTMColor='000000' majorTMNumber='3' minorTMNumber='4' minorTMHeight='4' majorTMHeight='8' showShadow='0'\n
pointerBgColor='FFFFFF' pointerBorderColor='000000' gaugeBorderThickness='3'\n baseFontColor='000000'\n
gaugeFillMix='{color},{FFFFFF}' gaugeFillRatio='50,50'>\n
<colorRange>\n
<color minValue='0' maxValue='5' code='FF654F' label='z'/>\n
<color minValue='5' maxValue='15' code='F6BD0F' label='x'/>\n
</colorRange>\n
</chart>");
myChart.render("chart3");
}
function loadXMLDoc()
{
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("ajax").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","test.php",true);
xmlhttp.send();
}
</script>
Then, you have the AJAX, retrieve only HTML from that PHP file.. So that after you click that DIV and populate whatever, you already have the existing Javascript ready for the new html.
The only way to do this is by, through some way or another, eval()ing the script that you're loading in via AJAX, in the AJAX call. Scripts are normally only evaluated if they're there on pageload, and new content loaded in via the DOM/AJAX isn't evaluated for scripts (for one thing, onload() fired a long time ago) so you have to manually call any scripts you're AJAXing in.
As has been mentioned above, frameworks make this easier - the evalScripts flag in Prototype, or just the evalScripts function, are really nice for this in my experience, and jQuery's live() or getScript are also an option.
If you're not using a framework, you'll have to do it manually, by calling eval() on the script that you're trying to load via AJAX. So your code would look something like this:
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("ajax").innerHTML=xmlhttp.responseText;
eval(xmlhttp.responseText);
}
}
You may not even need to set the innerHTML if the Javascript is all you're using it for. A caution: using eval() should as a rule make you wary due to the possibility of injection attacks. The frameworks above do some sanitizing and safety checks to more safely execute the scripts, but it's still a risky proposition.
If you can, you should consider rewriting your code to have the AJAX return JSON or some other data structure, and move the actual javascript into the recieve function (where I inserted the eval() above), to avoid such risks. In your code, depending on why you need to have the Javascript in the other file, you could probably easily pass the parameters you're generating the script for in a JSON array, and call the new FusionCharts() and mychart.render() within your AJAX call. That would look something like this:
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("ajax").innerHTML=xmlhttp.responseText;
cd = JSON.parse(xmlhttp.responseText);
var myChart = new FusionCharts(cd.chartPath, cd.chartID, cd.chartWidth, cd.chartHeight, 0, 0);
myChart.setDataXML(cd.dataXML);
myChart.render(cd.chartID);
}
}
With your AJAX returned being:
{
chartPath: "../Charts/HLinearGauge.swf",
chartID: "chart3",
chartWidth: "580",
chartHeight: "80",
dataXML: "<chart bgColor=\'FBFBFB\' bgAlpha=\'100\' showBorder=\'0\' chartTopMargin=\'0\' chartBottomMargin=\'0\'\n\ upperLimit=\'30\' lowerLimit=\'0\' ticksBelowGauge=\'1\' tickMarkDistance=\'3\' valuePadding=\'-2\' pointerRadius=\'5\'\n\ majorTMColor=\'000000\' majorTMNumber=\'3\' minorTMNumber=\'4\' minorTMHeight=\'4\' majorTMHeight=\'8\' showShadow=\'0\'\n\ pointerBgColor=\'FFFFFF\' pointerBorderColor=\'000000\' gaugeBorderThickness=\'3\'\n\ baseFontColor=\'000000\'\n\ gaugeFillMix=\'{color},{FFFFFF}\' gaugeFillRatio=\'50,50\'>\n\ <colorRange>\n\ <color minValue=\'0\' maxValue=\'5\' code=\'FF654F\' label=\'z\'/>\n\ <color minValue=\'5\' maxValue=\'15\' code=\'F6BD0F\' label=\'x\'/>\n\ </colorRange>\n\ </chart>"
}
Try to use jquery.live()

Ajax responds with empty string when triggered via form onsubmit in Firefox, but working fine in Internet Explorer

Ajax responds with an empty string when triggered via form onsubmit in Firefox, but it is working fine in Internet Explorer and Opera (works in Firefox if sent by a submit button instead of form onsubmit).
I am simply calling a php file with the ajax GET and the php file response with - echo $response = "something";. Then the response value is alerted. I am getting it work in IE but in Firefox the response is an empty string (checked by typeof()).
code is 4 files: index.php, ajax-connect.js, cbb.js, cbb.php
index.php
<html> <head> <script src="ajax-connect.js"></script> <script src="cbb.js"></script>
</head> <body>
<form name="condtactform1" method="get" action="" onSubmit="contactfunction()">
<input type="submit" name="hissubmit" id="hissubmit" value="submit"> </form>
</body> </html>
ajax-connect.php
/* Create a new XMLHttpRequest object to talk to the Web server */
var xmlHttp = false;
/*#cc_on #*/
/*#
if (#_jscript_version >= 5)
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
xmlHttp = false;
}
}
#end
#*/
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest();
}
cbb.js
function contactfunction() {
var url = "cbb.php";
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = updatecontact1;
xmlHttp.send(null);
}
function updatecontact1() {
if (xmlHttp.readyState == 4) {
var responsae = xmlHttp.responseText;
alert(responsae);
}
}
cbb.php
<?php $response = "something"; echo $response; ?>
If i trigger ajax by submit button instead of the form submit then it works fine in firefox like:
<form name="condtactform1" method="get" action="">
<input type="submit" name="hissubmit" id="hissubmit" value="submit" onFocus="contactfunction()"> </form>
Any idea why it is doing this?
Thanks.
I think part of the problem is that you aren't stopping the normal action of the submit. That it is working at all is probably based on how the return values of the last function executed is handled, though its hard to tell. Try adding a "return false" to your contactFunction();
If that doesn't work, I'd invest some time in retrofitting it to use a javascript framework for the AJAX (jQuery, MooTools, Prototype, etc.) rather than going down the route of debugging the cross browser differences. A jQuery solution would look like:
<form name="condtactform1" method="get" action="cbb-full.php">
<input type="submit" name="hissubmit" id="hissubmit" value="submit">
</form>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
<script>
<script type="text/javascript">
$(function() {
$('#hissubmit').click( function() {
$.get( 'cbb.php', function(response) {
alert(response);
});
return false;
});
});
</script>
Note that the form ought to post to a url that will generate a full response if javascript isn't enabled.

Categories