I am trying to retrieve an xml file from the server via ajax, but cannot get it to parse. I do not know what I am doing wrong. When I call the getFriends.php, it prints the xml fine. here is the ajax code:
<!DOCTYPE>
<html>
<head>
<title>Ajax Sample</title>
<script type="text/javascript">
function getFriendsList(MemberId) {
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) {
var xmlDoc = xmlhttp.responseXML;
var friendElements = xmlDoc.getElementsByTagName('friend');
for (var x=0; x<friendElements.length; x++) {
// We know that the first child of show is title, and the second is rating
var id = showElements[x].childNodes[0].value;
var name = showElements[x].childNodes[1].value;
// Now do whatever you want with the show title and ratings
document.write("hi");
}
}
}
xmlhttp.open("POST","getFriends.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("id=" + MemberId);
}
</script>
</head>
<body>
<input name="ajax" type="button" onClick="getFriendsList(1)" value="Click for AJAX">
<div style="background-color:#00FF99;" id="placehere">Here is where the update will occur.</div>
</body>
</html>
and here is the getFriends.php code (user class works fine):
<?php
include('lib.php');
//$id = $_POST['id'];
$id=1;
$user = new User($id);
echo $user->getFriendsList();
?>
You have undefined variable 'showElements' in your for loop. These two lines:
var id = showElements[x].childNodes[0].value;
var name = showElements[x].childNodes[1].value;
should be replaced with:
var id = friendElements[x].childNodes[0].value;
var name = friendElements[x].childNodes[1].value;
using jquery to perform ajax calls is easy and hassle free see http://api.jquery.com/jQuery.ajax/ for more info
Related
I am trying to use AJAX on a form so that the user doesn't have to leave the current page to submit their name. I have got the function to work when the user types their name; it changes automatically while they're typing. What I'm struggling with is the onClick to submit the name. I am not receiving any response from the PHP file and I do not know why. Here is my code:
The form page: (The submit function sends the name through a global variable via the GET request)
<script type="text/javascript">
//Decalre the variables of name as Global variable
var name;
//For IE 5 + 6
function httpReq(){
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
return xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5
return xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
function nameTest(str) {
if (str.length==0) {
document.getElementById("nameTest").innerHTML="Please enter your name.";
return;
}
httpReq();
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("nameTest").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","nameTest.php?q="+str,true);
xmlhttp.send();
return name = str;
}
// function to submit the users details to the database
function submit(str) {
httpReq();
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("submitted").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","mailing-list.php?name="+name, true);
xmlhttp.send();
}
</script>
Name: <input type="text" onkeyup="nameTest(this.value)">
<span id="nameTest">Please enter your name.</span>
<input style="width: 100px; height: 40px;" type="button" onclick="submit" value="Join!">
<span id="submitted"></span>
The PHP page which doesn't give a response (Just echoing something simple until I get a response):
<?php
$name = $_GET["name"];
echo "Hello There " + $name;
?>
Can't seem to figure out why there is no response. Any help appreciated!
var name;
//For IE 5 + 6
function httpReq(){
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
} else {
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
function nameTest(str) {
if (str.length==0) {
document.getElementById("nameTest").innerHTML="Please enter your name.";
return;
}
var xmlhttp = httpReq();
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("nameTest").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","nameTest.php?name="+str,true);
xmlhttp.send();
window.name = str;
}
// function to submit the users details to the database
function submit() {
var xmlhttp = httpReq();
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("submitted").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","mailing-list.php?name="+window.name, true);
xmlhttp.send();
}
You haven't assigned a value to xmlhttp, probably the console tells you it is undefined, you should check it.
Sorry, there are a lot of errors inside your code. I edited it, you should try now.
submit() doesn't get params, it just get the name from the global variable name(window.name), which was set before by the function nameTest(str).
Last thing: you should check compatibility between what you want client and server side. You used "?q=" instead of "?name=" in your query string, pay attention to these things!
According with LightStyle, you should use the return of httpReq() method to retrieve your requestObject.
var xmlhttp = httpReq();
xmlhttp.onreadystatechange=function() {...}
You have to modify
onclick="submit"
into onclick="submit();" to make it called.
This PHP script will return 0, the concatenation operator is . in PHP :
<?php
$name = $_GET["name"];
echo "Hello There " . $name;
?>
Value "name" in your function submit(str) is unknown, and thus empty. change that into
xmlhttp.open("GET","mailing-list.php?name="+str, true);
and call your function like this:
submit("NameToShow");
BTW: Using jQuery would make this alot easier for you.
I have a simple form that that when changed includes a php file in a div. For some reason jquery will not load when placed in that included file? Can someone tell me why this doesnt work.
<select name='make' onChange='show(this.value)'>
<option value='some-file.php'>the file</option>
</select>
<div id="make">Where the file is loaded and where jquery wont work</div>
<script type="text/javascript">
function show(str)
{
if (str=="")
{
document.getElementById("make").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("make").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","include/some-file.php?q="+str,true);
xmlhttp.send();
}
</script>
Then some-file.php
$models = mysql_query("SELECT model, id FROM model where make like '%".$q."%' order by model asc") or die(mysql_error());
//Puts it into an array
$count = 1;
$max = 3;
while($model = mysql_fetch_array( $models ))
{
if($count%20==1)
echo '</ul><ul style="float:left; padding:0; margin-right:10px;" class="makesModels">';
echo "<li style='padding-right:5px; display:block;'><font color='#fe9000'>".$count.".</font> ".$model['model']." <a class='delete-model".$model['id']."'>x</a></li>";
<script type='text/javascript' src='http://code.jquery.com/jquery-1.8.1.min.js'></script>
<script type='text/javascript'>
$(docuument).ready(function() {
$(".delete-model<? echo $model['id'];?>").click(function() {
alert("delete");
});
});
</script>
$count++;
}
?>
i've had the same exact problem ...
to solve this all you need to do is edit the ajax from using normal JavaScript to $.ajax so use jQuery to handle it .. and it will work ..
$.ajax({
url: "include/some-file.php?q="+str,
type: "GET",
datatype: 'html',
success: function(e){
$('#make').html(e);
}
});
I'm not sure about it, because the code is not complete, my guess would be that on someotherphpfile that you are importing you use document.ready function which is not calling because you load the file using ajax.
scripts loaded with ajax or in general a script string injected in the DOM will not execute for security reasons
you can use eval to get it working although i must warn you that you could be opening a can of worms..
after document.getElementById("make").innerHTML=xmlhttp.responseText; add this..
var parent = document.getElementById('make');
var myScript = parent.getElementsByTagName('script');
for(var i=0,len=myScript.length; i<len; i++){
executeScrpt(myScript[i]);
}
then the execute function...
function executeScrpt(scrpt){
if(scrpt.innerHTML != ""){
eval("("+script.innerHTML+")");
} else {
if(scrpt.src != ""){
var myScrpt = document.createElement("script");
myScrpt.src = scrpt.src;
document.head.appendChild(myScrpt);
}
}
}
I want to create a login page.
So I put a captcha picture in the login form with following html code:
<img name="captcha" id="captcha" src="captcha/CaptchaSecurityImages.php?width=90&height=28&characters=5"/>
and I put a button that users can click on to change captcha if it is unreadable as follow :
<input type="button" name="new_Captcha_button" onClick="new_captcha()"/>
and I wrote a script as follow which work just in chrome :
<script type="text/javascript">
function new_captcha()
{
document.images["captcha"].src = "captcha/CaptchaSecurityImages.php?width=90&height=28&characters=5";
}
</script>
but it doesn't work in other browsers, so I replace the previous code with the following :
<script type="text/javascript">
function new_captcha()
{
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("captcha").src = xmlhttp.responseText;
}
}
xmlhttp.open("GET","captcha/CaptchaSecurityImages.php?width=90&height=28&characters=5",true);
xmlhttp.send();
}
So please tell me what changes I need to do in my code to make it correct. I think I need to change just following line :
document.getElementById("captcha").src = xmlhttp.responseText;
Thanks a lot.
<script type="text/javascript">
function new_captcha()
{
document.getElementById('captcha').src = 'captcha/CaptchaSecurityImages.php?width=90&height=28&characters=5&_t=' + Math.random(1);
}
</script>
Do not need to use ajax, function new_captcha() is ok as it is.
You may try to do this
login.php
<div id="captcha_container"></div>
<input type="button" id="btn_recaptcha" value="Recaptcha">
<script>
function ajax_loadpage(loadUrl,output_container)
{
$.post
(
loadUrl,
{language: "php", version: 5},function(responseText){$(output_container).html(responseText);},"html"
);
}
ajax_loadpage("captcha_page.php","#captcha_container");
$('#btn_recaptcha').click(function(){
ajax_loadpage("captcha_page.php","#captcha_container");
})
</script>
______________________________________________________________________________________
captcha_page.php
<img width="212" height="53" src="captcha.php">
captcha.php contains my captcha code, it contains a header ("Content-type: image/gif"); code, so i needed an extra php file on where i can save the image file, thus using my captcha_page.php.
Worked for me :)
I am getting an undefined index error message on server side when i am trying to send a value selected from a dropdown box on client side (javascript/AJAX) to server side (php). I have a feeling that the GET on the client side is not sending the url correctly or if it is it is sending the value as null.
Does anyone have any idea how to solve this issue.
The code on the client is:
<title>test</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$.getJSON("process.php", function(fileName)
{
for(var i in fileName)
{
fileName[i] = fileName[i].split("../Test/").join("")
fileName[i] = fileName[i].split(".xml").join("")
document.dropDown.file[i]= new Option(fileName[i],"../Test/"+fileName[i]+".xml", false)
}
});
});
var xmlhttp;
function getFile(str){
alert("xmlprocess.php?filename="+str);
if (str=="")
{
document.getElementById("txtHint").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= response(file);
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML= xmlhttp.responseText;
}
}
xmlhttp.open("GET","xmlprocess.php?filename="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form name = "dropDown">
<Select name = "file" onclick = "getFile(str1)" onchange = "str1 = this.options[this.selectedIndex].value"></Select>
</form>
<div id="txtHint"></div>
</html>
and the code on the server side is :
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
$br = "<br>";
$filename = $_GET["filename"];
echo $filename;
?>
Ok guys ive found the answer
i had to change the onreadystatechange to be equal to a function on client side as shown below
xmlhttp.onreadystatechange= function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML= xmlhttp.responseText;
}
};
I'm trying to find a good example on how to retrieve records using PHP from a table and refresh it say every 2 minutes using Ajax.
Anyone can point me to that tutorial?
I don't think you'll find a tutorial that specific, but you just need to learn AJAX and then make the AJAX call every two minutes using JavaScript's setInterval method.
EDIT
Meh, I'm bored enough to write this example. This isn't tested, but I don't think it has errors.
<html>
<head>
<script type="text/JavaScript">
window.onload = function()
{
// call your AJAX function every 2 minutes (120000 milliseconds)
setInterval("getRecords()", 120000);
};
function getRecords()
{
// create the AJAX variable
var xmlhttp;
if (window.XMLHttpRequest)
xmlhttp = new XMLHttpRequest();
else
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
// set up the response function
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
/*
Your code goes here. 'xmlhttp.responseText' has the output from getRecords.php
*/
document.getElementById("txaRecords").innerHTML = xmlhttp.responseText;
}
}
// make the AJAX call
xmlhttp.open("GET", "getRecords.php", true);
xmlhttp.send();
}
</script>
</head>
<body>
<textarea id="txaRecords"></textArea>
</body>
</html>
This is a bit of code that I wrote for this exact purpose. Adapt as appropriate.
AJAX code:
function timer()
{
var t=setTimeout("check()",2000);
// At an appropriate interval
}
function check(){
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)
{
if (xmlhttp.responseText!=""){
var output = xmlhttp.responseText;
// Do what you need to do with this variable
}
}
}
xmlhttp.open("GET","backend.php",true);
// Set file name as appropriate.
xmlhttp.send();
timer();
}
PHP code:
<?php
// This assumes you have already done mysql_connect() somewhere.
// Replace as appropriate
$query = "SELECT * FROM table_name";
// Perform the query
$result = mysql_query($query);
// Get the results in an array
while($row = mysql_fetch_array( $result )) {
// Echo the message in an appropriate format.
echo "<br />" . $row['column_name'];
}
?>
Remember to initiate one of the JS functions as you load the page:
<body onload="timer()">