My AJAX file does not work - php

I just make a simple AJAX application so that my html page can get some data from the php file through the ajax.js file, I have already put them in the server, so when I access localhost/mypage, it should be executed, however it seems there are some problems therefore things do not happen as my expected way.
Here is my html file:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<META http-equiv="Content-Type" Content="text/html; Charset=UTF-8">
<title>
My Portal
</title>
<link rel="stylesheet" href="style.css" type="text/css"/>
<script type="text/javascript" src="ajax.js"></script>
</head>
<body onload="load()">
<div id="header">
<img src="images/logo.gif" id="logo" alt="Logo"/>
<a href="http://www.google.com">
<img src="images/logo2.png" id="logo2" align="right" alt="google Ltd"/>
</a>
</div>
<div id="container">
<div id="function"></div>
<div id="Display"></div>
<div id="View"></div>
</div>
<div id="footer">
</div>
</body>
</html>
And below is the js file:
function load(){
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("function").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test.php", true);
xmlhttp.send();
}
At last is the php file:
<?php
print "<h1>hgfkegfalhgj</h1>";
?>
I expect it should print out the above char string in my page, however, nothing can be shown, can anyone tell me where is the problem? I have checked that I have already enabled javascript in my browser, so I am quite sure my html file can call the function in js file.

I don't know PHP but you must set content type to text/plain . Like :
header('Content-Type: text/plain');

Your code works for me.
The problem can be any of the following:
1) Check the path to test.php (I would suggest using absolute path in xmlhttp.open() )
2) Your server may not be returning the page correctly (Try opening test.php, and check the output)
You can use browser plugins like firebug, to analyze the ajax request and response, it can give you a better insight.

instead of onLoad function in body tag try with
<script>
window.onload = function(){
load();
};
function load(){
//your code
}
</script>
or try with script load() function before body. I think it will solve your problem.
Also Try to change id, preferably keywords should not be used as id (function id change it to something else)

Related

Make PHP and JAVASCRIPT work together.

I have a simple php if statement that checks for an error return on a form submit basically.
<?php if ($this->session->flashdata('error')): ?>
×
<div class="alert alert-error" id="error"><?php echo $this->session->flashdata('error'); ?></div>
<?php endif ?>
And I have this script that I want to put into this php so when the php is true the login box or account-container will shake.
$("#account-container").addClass("animated shake");
I tried echoing the script inside the php but all that was give me echo ; displayed on the page when the if was true.
Maybe you can use this script, I'm not at ease with jquery and you would have to adapt the code:
$(function(){
if ($("#error").length !== 0) {
$("#account-container").addClass("animated shake");
}
});
Place it in the header as javascript source or embedded in a script tag
The $().load hook the containing handler to the onload event in the page*
The function simply check if there is an element in the page with id error and
add the class to the #account-container element if is the case.
I won't use $().ready() as the dom can still be partially rendered
References:
http://api.jquery.com/ready/ Says to use .load() function for onload event and
alert that a <body onload="something"> tag is not compatible with the jquery event management
http://api.jquery.com/load/ Can be useful
I think that you are using Jquery for the javascript shake, you should call the javascript routine when the page is ready to load
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>shake demo</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<style>
#toggle {
width: 100px;
height: 100px;
background: #ccc;
}
</style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
</head>
<body>
<p>Click anywhere to shake the box.</p>
<div id="toggle">This is rendered by PHP</div>
<script>
$( document ).ready(function() {
$( "#toggle" ).effect( "shake" );
});
</script>
</body>
</html>
Note that the whole page is rendered by PHP, and the script will work when the document render is ready.

ajax not working in chrome

So I have this script which posts some text using ajax:
<?php
if (isset($_POST['q'])) {
echo 'q is '.$_POST['q'];
} else {
?>
<!DOCTYPE HTML>
<html>
<head>
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","aj.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Accept","text/html");
xmlhttp.send("q=some text");
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState===4&&xmlhttp.status===200)
if (r=xmlhttp.response||xmlhttp.responseText)
document.write(r);
else
alert("no response")
}
</script>
</head>
<body>
body
</body>
</html>
<?php } ?>
The output is suppose to be 'q is some text' but in Google Chrome (Windows) it runs repeatedly and all you see is the word 'body' repeating across the page.
Whats going wrong?
jQuery is the way
$.post('ajax.php','q=some text',function(data){
$(document.body).html(data);
});

Load data from Database using Javascript

I have this code to display the data retrieved from DB in accounts_view.php:
<script type="text/javascript">
function showPrice(str)
{
if (str=="")
{
document.getElementById("sender_price").innerHTML="";
return;
}
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("sender_price").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","?action=account&q="+str,true);
xmlhttp.send();
}
</script>
I have problem in the below line :
xmlhttp.open("GET","?action=account&q="+str,true);
Just to explain to you I have index.php and have many cases there, I have
case "account" :
$q=$_GET["q"];
//code is here to get data from db and return with result..
include($_STR_TEMPLATEPATH."/account_view.php");
break;
So, When I am redirecting to ?action=account&q=str in the account_view.php
it displays the page again, so I will have 2 pages over each other.
I hope the problem is clear to you :)
Thanks and Regards,
I would recommend using jquery to retrieve data from a database if you are wanting to use ajax. All the browser incompatibilities are already accounted for and you won't have to bother coding for all the issues you will encounter trying to accomplish this by hand. basically why re-invent the wheel that is already perfectly created.
Here is an example of my code using jquery and how easy it is to use.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>some title</title>
<link href="customize.css" rel="stylesheet" type="text/css" media="screen" />
<link href="css/black-tie/jquery-ui-1.8rc3.custom.css" rel="stylesheet" type="text/css" media="screen" />
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="jquery-ui-1.8rc3.custom.min.js"></script>
<script type="text/javascript">
function ShowActive(inputString){
//gives visual that something is happening
$('#Sresults').addClass('loading');
//send your data to a php script here i am only sending one variable
//if using more than one then use json format
$.post("allactive.php", {queryString: ""+inputString+""}, function(data){
if(data.length >0) {
//populate div with results
$('#Sresults').html(data);
$('#Sresults').removeClass('loading');
}
});
}
</script>
</head>
<body>
put your form here ....
<div id="Sresults" name="Sresults"></div>
</body>

Inline javascript checks in PHP

I was trying to use <script> <noscript> checks inline with my PHP to render different form elements depending on weather or not someone has javascript enabled.
To display something to non enabled users only I can successfully use
<noscript> <?php ... ?> </noscript>
To display something to enabled users only I tried whats below but it does not work the same as above. Instead it allows all users to still see the PHP.
<script> <?php ... ?> </script>
How can I limit something to only those with javascript enabled without having two totally different pages?
You may be able to use something like this:
<script>
<?php
ob_start();
// ...
$scriptOnlyData = ob_get_clean();
?>
document.write(<?php echo json_encode($scriptOnlyData); ?>);
</script>
Javascript runs on the Client-side (in the browser), PHP runs on the Server-side (before the page is sent to the browser). So PHP does not know whether the browser does, or does not, have Javascript.
The simplest solution is to use Javascript itself to show/hide various elements within the browser, like so:
<!doctype html>
<html>
<head>
<title>Test Page</title>
<style>
.showWithJS {
display:none;
}
</style>
</head>
<body>
<div class="showWithJS">
This DIV, and anything with the class "showWithJS",
will only be seen when Javascript is enabled.
</div>
<div class="hideWithJS">
This DIV, and anything with the class "hideWithJS",
will not be seen when Javascript is enabled.
</div>
<script src="http://code.jquery.com/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('.showWithJS').show();
$('.hideWithJS').hide();
});
</script>
</body>
</html>
Another option would be to use Javascript to set a cookie (which can be read by PHP) to indicate whether that javascript is running. The downside of that, of course, is that, should the user switch javascript on/off mid-visit, the cookie will not update to reflect that change.
<?php
$javascriptOn = ( isset( $_COOKIE['javascript'] ) && $_COOKIE['javascript']=='on' );
?><!doctype html>
<html>
<head>
<title>Test Page</title>
</head>
<body>
<?php if( $javascriptOn ){ ?>
<div>
This DIV will only be seen when Javascript is enabled.
</div>
<?php } ?>
<?php if( !$javascriptOn ){ ?>
<div>
This DIV will not be seen when Javascript is enabled.
</div>
<?php } ?>
<script>
document.cookie = 'javascript=on';
</script>
</body>
</html>
The downside of this is that you need a pageload to set the cookie (it cannot be set and read by the same pageload), so you would need to refresh the page to see the changes.
Load the PHP in javascript and then insert when the DOM loads
JS:
function pageLoad(){
var text = "<?php ... ?>";
document.getElementById('scriptSpan').innerHTML = text;
}
html:
<span id="scriptSpan"></span>

returning javascript via ajax but it doesnt work

I am trying to get the links that appear after clicking the business name to appear in a light box. on a standalone page, it was possible but as soon as I send the same code through ajax, it does not call the light box anymore. help?
This is the original file, which is supposed to represent a 3rd party publisher site, integrating our code:
<html>
<head>
<script type="text/javascript" src="lib/js/jquery-latest.js"></script>
<link rel="stylesheet" href="css/prettyPhoto.css" type="text/css" media="screen" charset="utf-8" />
<script src="lib/js/jquery.ppo.js" type="text/javascript" charset="utf-8"></script>
<script src="lib/js/sp.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
This is the publisher's website. <br>
<div id="bizname1" onclick="showComp(this.innerHTML)" id="bizname" class="bizname">click here - this event should be substituted for an 'on load'.</div><br><br>
lots of data about the company here
<br />
<div id="txtHint"><b>Company info will be listed here.</b></div>
</body>
</html>
This is the ajax script, showcomp.js:
function showComp(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getbutton.php?q="+str,true);
xmlhttp.send();
}
This is the getbutton.php file called by the ajax function:
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
include('config.php');
init_connection();
$sql=select content from db;// this part works fine, so actual sql query not inserted here.
$result = mysql_query($sql);
while ($row = mysql_fetch_object($result)) {
$companyname = $row->result1;
$contenturl = $row->result2;
//echo $companyname;
//echo $contenturl;
?>
<HTML>
<HEAD>
</HEAD>
<BODY>
<a href="http://www.youtube.com/embed/DudfBIxw6do?iframe=true&width=640&height=390" rel="prettyPhoto" title="my caption"> Video in iframe
<img src="images/thumb-1.jpg" width="100" height="40" alt="Video in iframe" />
</a>
<a href="demo/vidrefer.php?iframe=true&width=500&height=410" rel="prettyPhoto" title="my caption"> Vidrefer in iframe
<img src="images/thumb-1.jpg" width="100" height="40" alt="Vidrefer in iframe" />
</a>
<br />
</BODY>
</HTML>
<?php
}
//echo out button here. give the button what it needs to launch the light box.
echo "
<br>
<div id='button'>
this is a button
</div>
";
//mysql_close($con);
?>
<script id="ppready" type="text/javascript" charset="utf-8">
$(document).ready(function(){
$("a[rel^='prettyPhoto']").prettyPhoto();
});
</script>
Please help if you can see why it is not working! Thank you.
I fixed this! the problem was due to the fact that the javascript already acted before I loaded my new elements via ajax. all I had to do was to load my elements in before the ajax call and hey presto!
An alternative solution would have been to use live() or livequery() in jquery. They would have kept the jquery acting on elements both before and after they loaded into the DOM. Simples.
The JS would not run on the client side, when it is just echo'ed from the server side. Try moving your codeblock
$(document).ready(function(){
$("a[rel^='prettyPhoto']").prettyPhoto();
<-- inside-->
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
To look like :
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
$("a[rel^='prettyPhoto']").prettyPhoto();
}

Categories