SitePoint Sponsor

User Tag List

Results 1 to 5 of 5

Thread: AJAX Call Fails

  1. #1
    SitePoint Enthusiast
    Join Date
    Jan 2005
    Location
    Hobart, Australia
    Posts
    81
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    AJAX Call Fails

    Hello,

    I have a simple script that is showing and hiding content while also updating div's through AJAX. The script works fine in a simple example but when I place it into my application I don't get the same results but I just can't figure out what I'm doing wrong.

    Here is the behaviour that I want: http://www.kekbur.com/alex/removetest/test.php

    test.php
    Code HTML4Strict:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
    	<title>Test</title>
    	<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    	<script type="text/javascript" src="script.js"></script>
    </head>
     
    <body>
    <h1>Remove</h1>
    <p id="remove">Do you want to remove this item? <input type="button" class="button" onclick="javascript:Remove();" value="Yes" /></p>
    </body>
    </html>

    script.js
    Code JavaScript:
    function createRequestObject() {
     
        var ro;
        var browser = navigator.appName;
     
        if (browser == "Microsoft Internet Explorer") {
     
            ro = new ActiveXObject("Microsoft.XMLHTTP");
     
        } else {
     
            ro = new XMLHttpRequest();
     
        }
     
        return ro;
     
    }
     
    var http = createRequestObject();
     
    function handleResponse() {
     
        if (http.readyState == 4) {
     
            var response = http.responseText;
            var update = new Array();
     
            if (response.indexOf('|' != -1)) {
     
                update = response.split('|');
                document.getElementById(update[0]).innerHTML = update[1];
    			ShowHide();
     
            }
     
        }
     
    }
     
    function Remove() {
     
    	var url = 'remove.php';
    	var params = 'remove=';
     
    	http.open('post', url, true);
    	http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    	http.setRequestHeader('Content-length', params.length);
    	http.onreadystatechange = handleResponse;
    	http.send(params);
     
    }
     
    function Confirm() {
     
    	var url = 'remove.php';
    	var params = 'confirm=';
     
    	http.open('post', url, true);
    	http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    	http.setRequestHeader('Content-length', params.length);
    	http.onreadystatechange = handleResponse;
    	http.send(params);
     
    }
     
    function Cancel() {
     
    	var url = 'remove.php';
    	var params = 'cancel=';
     
    	http.open('post', url, true);
    	http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    	http.setRequestHeader('Content-length', params.length);
    	http.onreadystatechange = handleResponse;
    	http.send(params);
     
    }
     
    function ShowHide() {
     
    	removeDiv = document.getElementById("remove");
    	removeDiv.style.border = (removeDiv.style.border == "") ? "2px solid #b71d01" : "";
    	removeDiv.style.padding = (removeDiv.style.padding == "") ? "1em" : "";
    	removeDiv.style.margin = (removeDiv.style.margin == "") ? "0 0 1em 0" : "";
     
    }

    remove.php
    Code PHP:
    <?php
     
    if (isset($_POST['confirm'])) {
     
    	$result = "remove|";
    	$result .= "<span>You have successfully removed the item.</span>";
     
    	echo $result;
    	exit;
     
    }
     
    if (isset($_POST['cancel'])) {
     
    	$result = "remove|";
    	$result .= 'Do you want to remove this item? <input type="button" class="button" onclick="javascript:Remove();" value="Yes" />';
     
    	echo $result;
    	exit;
     
    }
     
    if (isset($_POST['remove'])) {
     
    	$result = "remove|";
    	$result .= '<em>Please confirm that you wish to remove this item.</em><br />';
    	$result .= '<input type="button" class="confirm" value="CONFIRM" onclick="javascript:Confirm();" />&nbsp; <input type="button" class="confirm" value="CANCEL" onclick="javascript:Cancel();" />';
     
    	echo $result;
    	exit;
     
    }
    ?>

    This works as expected. I can click Yes and Cancel until the cows come home. However when I use this code in my application it falls over.

    Here is the page I use the "test.php" code on
    Code PHP:
    <?php
    // Get all class files and create new instance
    require_once 'includes/Page.php';
    $Page = new Page;
     
    // Display page header
    $Page->GetHeader();
    ?>
    		<!-- Start application navigation -->
    		<div id="appnav">
     
    			<ul>
    				<li class="first"><a href="AddAdvert.php">Add a new ad</a></li>
    				<li><a href="index.php">Show all ads</a></li>
    			</ul>
     
    		</div>
    		<!-- End application navigation -->
     
    		<!-- Start central container -->
    		<div id="container">
     
    		<!-- Start application return link. -->
    		<div id="appreturnlink">
     
    			<a href="#" title="Return to Council Business Centre">Return to Council Business Centre</a>
     
    		</div>
    		<!-- End application return link. -->
     
    		<!-- Start content container -->
    		<div id="content">
     
    		<!--
    		###########################################################################
    		# START MAIN CONTENT                                                      #
    		###########################################################################
    		-->
     
    		<h1>Edit an ad</h1>
     
    <?php
    // Convert the query string to a number before executing sql query
    $Id = intval($_GET['Id']);
     
    // Check that the user has permissions to edit this advert
    $Page->CheckUserAuth($Id);
     
    // Check to see if the Cancel button was pressed and if so redirect back to the edit page.
    if (isset($_POST['Cancel'])) {
     
    	header("Location: index.php");
    	exit;
     
    }
     
    // Check that the form was posted correctly
    if (isset($_POST['Submit'])) {
     
    	// Run validation functions over posted data
    	$Page->ValGeneral($_POST['Title'], 'You Must Enter A Title');
    	$Page->ValGeneral($_POST['Description'], 'You Must Enter A Description');
     
    	// Check to see if a file was uploaded
    	if (isset($_FILES['Attachment'])) {
     
    		// If a file has been uploaded validate its file extension
    		if ($_FILES['Attachment']['size'] > 0) {
     
    			$Page->ValFileExtension(basename($_FILES['Attachment']['name']), 'File Extension Not Allowed');
     
    		}
     
    	}
     
    	if ($Page->FoundErrors()) {
     
    		// Create a variable holding all the found validation errors
    		$ValErrors = $Page->ListErrors('<br />');
     
    		// Process all passed variables to re-enter into the form. These values are only used if a page is submitted but has an error in validation
    		$Title = htmlspecialchars($_POST['Title']);
    		$Description = htmlspecialchars($_POST['Description']);
     
    	} else {
     
    		// Process all passed variables
    		$Title = mysql_real_escape_string($_POST['Title']);
    		$Description = mysql_real_escape_string($_POST['Description']);
     
    		$UpdateAdvert = $Page->Query("UPDATE adverts SET title='$Title', description='$Description' WHERE id=$Id LIMIT 1;");
     
    		// Check if a file was attached
    		if ($_FILES['Attachment']['size'] > 0) {
     
    			// Process all passed variables
    			$FileName = $Id . "_" . basename($_FILES['Attachment']['name']);
    			$UploadFile = $Page->Settings['UploadDir'] . $FileName;
     
    			// Initially set the isImage variable to false
    			$IsImage = 0;
     
    			// Attempt to copy the new file to the required folder
    			copy($_FILES['Attachment']['tmp_name'], $UploadFile);
     
    			// Resize the attachment if it is an image. Max width or height of 400 pixels
     
    			// Load image
    			$Image = $Page->OpenImage($UploadFile);
     
    			// If $image returns a correct image type then process it
    			if ($Image !== false) {
     
    				// Set a field in the database to show that it is an image. This will be used to display images inline and not just as a hyperlink in the displayed page.
    				$IsImage = 1;
     
    				// Get original width and height
    				$Width = imagesx($Image);
    				$Height = imagesy($Image);
     
    				if ($Width >= $Height && $Width > 400) {
     
    					// Set a new width, and calculate new height
    					$NewWidth = 400;
    					$NewHeight = $Height * ($NewWidth/$Width);
     
    				} elseif ($Height >= $Width && $Height > 400) {
     
    					// Set a new height, and calculate new width
    					$NewHeight = 400;
    					$NewWidth = $Width * ($NewHeight/$Height);
     
    				} else {
     
    					// The image doesn't require resizing so just write the details to the database then end the script
    					$FileName = mysql_real_escape_string(basename($UploadFile));
     
    					$AttachDocument = $Page->Query("INSERT INTO attachments (id, date_time, item_id, filename, image) VALUES (NULL, NOW(), '$Id', '$FileName', '$IsImage');");
     
    					// Redirect to the home page
    					header("Location: index.php?Id=$Id");
    					exit;
     
    				}
     
    				// Resample the image
    				$ImageResized = imagecreatetruecolor($NewWidth, $NewHeight);
    				imagecopyresampled($ImageResized, $Image, 0, 0, 0, 0, $NewWidth, $NewHeight, $Width, $Height);
     
    				// Re-create the new image with the correct image type
    				switch ($ImageType) {
     
    					case 1:
     
    						imagejpeg($ImageResized, $UploadFile);
    						break;
     
    					case 2:
     
    						imagegif($ImageResized, $UploadFile);
    						break;
     
    					case 3:
     
    						imagepng($ImageResized, $UploadFile);
    						break;
     
    				}
     
    			}
     
    			$FileName = mysql_real_escape_string(basename($UploadFile));
     
    			$AttachDocument = $Page->Query("INSERT INTO attachments (id, date_time, item_id, filename, image) VALUES (NULL, NOW(), '$Id', '$FileName', '$IsImage');");
     
    		}
     
    		// Redirect to the home page
    		header("Location: index.php?Id=$Id");
    		exit;
     
    	}
     
    }
     
    if (isset($ValErrors)) {
     
    	echo '<p class="error">' . $ValErrors . "</p>\r\n";
     
    }
     
    $Results = $Page->Query("SELECT * FROM adverts WHERE id=$Id LIMIT 1;");
    $SelectAdvert = $Page->FetchArray($Results);
    ?>
    <form enctype="multipart/form-data" method="post" action="#">
    <p>Edit the details into the form below to change a classifieds item.</p>
    <h3>Title</h3>
    <input type="text" name="Title" style="width: 500px;" value="<?php if (isset($Title)) { echo $Title; } else { echo htmlspecialchars($SelectAdvert['title']); } ?>" />
    <br /><br />
    <h3>Description</h3>
    <textarea name="Description" rows="25" cols="120"><?php if (isset($Description)) { echo $Description; } else { echo htmlspecialchars($SelectAdvert['description']); } ?></textarea>
    <p><em>You must enter all the details above before continuing.</em></p>
    <?php
    $SelectAttachment = $Page->Query("SELECT * FROM attachments WHERE item_id=" . $SelectAdvert['id'] . " LIMIT 1;");
     
    // Check to see if there are actually any attachments for this item
    if ($Page->GetNumRows($SelectAttachment) > 0) {
     
    	// If results are found then grab them
    	$Attachment = $Page->FetchArray($SelectAttachment);
     
    	echo '<h3>Attachment</h3>' . "\r\n";
    	//echo '<div id="removeattachment"><p>This item has an <a href="' . $Page->Settings['SiteUrl'] . '/uploads/' . $Attachment['filename'] . '" target="new">attachment</a>, you can <input type="button" class="button" onclick="javascript:RemoveAttachment(' . "'" . $Attachment['id'] . "'" . ');" value="REMOVE" /> it to add a different one.</p></div>' . "\r\n";
    	echo '<div id="removeattachment"><p>This item has an <a href="' . $Page->Settings['SiteUrl'] . '/uploads/' . $Attachment['filename'] . '" target="new">attachment</a>, you can <input type="button" class="button" onclick="javascript:RemoveAttachment(' . $Attachment['id'] . ');" value="REMOVE" /> it to add a different one.</p></div>' . "\r\n";
     
    } else {
     
    	echo '<h3>Attachment</h3>' . "\r\n";
    	echo "<input type=\"file\" name=\"Attachment\" style=\"width: 350px;\" />\r\n";
    	echo "<p>You may attach one file to an advert above. This can be an image, word document or PDF.</p>\r\n";
     
    }
    ?>
    <div id="EditButtons">
    <input class="button" id="EditSubmit" type="submit" name="Submit" value="SUBMIT" />&nbsp;
    <input class="button" type="submit" name="Cancel" value="CANCEL" />
    </div>
    <input type="hidden" name="Id" value="<?php if (isset($Id)) { echo $Id; } else { echo $SelectAdvert['id']; } ?>" />
    </form>
    <br />
    <input type="button" class="button" onclick="javascript:alert(document.getElementById('removeattachment').innerHTML);" value="test" />
     
    		<!-- Start right side container -->
    		<div id="tips">
     
    			<fieldset>
    				<h2>Editing an ad</h2>
    				<p>Conse vero con henit, venim eum iustionulla feugiat. Iduop enis dolupatum nit vel vaccom mostiu consqequam ilit vulla feu facil il ipr se et enit lore et lorpercil domulm vullam in ut se vellisissit vulput.</p>
    			</fieldset>
    			<div id="blankdiv">&nbsp;</div>
     
    		</div>
    		<!-- End right side container -->
    <?php
    // Display page footer
    $Page->GetFooter();
    ?>
    Towards the bottom is the line:
    Code PHP:
        echo '<div id="removeattachment"><p>This item has an <a href="' . $Page->Settings['SiteUrl'] . '/uploads/' . $Attachment['filename'] . '" target="new">attachment</a>, you can <input type="button" class="button" onclick="javascript:RemoveAttachment(' . $Attachment['id'] . ');" value="REMOVE" /> it to add a different one.</p></div>' . "\r\n";
    This is where the javascript gets called and also this is the id that gets updated from the javascript.

    And here is the script.js file
    Code JavaScript:
    function createRequestObject() {
     
        var ro;
        var browser = navigator.appName;
     
        if (browser == "Microsoft Internet Explorer") {
     
            ro = new ActiveXObject("Microsoft.XMLHTTP");
     
        } else {
     
            ro = new XMLHttpRequest();
     
        }
     
        return ro;
     
    }
     
    var http = createRequestObject();
     
    function handleResponse() {
     
        if (http.readyState == 4) {
     
            var response = http.responseText;
            var update = new Array();
     
            if (response.indexOf('|' != -1)) {
     
                update = response.split('|');
                document.getElementById(update[0]).innerHTML = update[1];
    			ShowHide();
     
            }
     
        }
     
    }
     
    function RemoveAttachment(id) {
     
    	var url = 'RemoveAttachment.php';
    	var params = 'Id='+id;
     
    	http.open('post', url, true);
    	http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    	http.setRequestHeader('Content-length', params.length);
    	http.onreadystatechange = handleResponse;
    	http.send(params);
     
    }
     
    function ConfirmRemove(id) {
     
    	var url = 'RemoveAttachment.php';
    	var params = 'Confirm='+id;
     
    	http.open('post', url, true);
    	http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    	http.setRequestHeader('Content-length', params.length);
    	http.onreadystatechange = handleResponse;
    	http.send(params);
     
    }
     
    function CancelRemove(id) {
     
    	var url = 'RemoveAttachment.php';
    	var params = 'Cancel='+id;
     
    	http.open('post', url, true);
    	http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    	http.setRequestHeader('Content-length', params.length);
    	http.onreadystatechange = handleResponse;
    	http.send(params);
     
    }
     
    function ShowHide() {
     
    	HideButtons = document.getElementById("EditButtons");
    	HideButtons.style.visibility = (HideButtons.style.visibility == "") ? "hidden" : "";
     
    	RemoveAttachment = document.getElementById("removeattachment");
    	RemoveAttachment.style.border = (RemoveAttachment.style.border == "") ? "2px solid #b71d01" : "";
    	RemoveAttachment.style.padding = (RemoveAttachment.style.padding == "") ? "1em" : "";
    	RemoveAttachment.style.margin = (RemoveAttachment.style.margin == "") ? "0 0 1em 0" : "";
     
    	Submit = document.getElementById("EditSubmit");
    	Submit.disabled = (Submit.disabled == "") ? "true" : "";
     
    }

    And finally the RemoveAttachment.php file that the xmlhttprequest calls
    Code PHP:
    <?php
    // Get all class files and create new instance
    require_once 'includes/Page.php';
    $Page = new Page;
     
    if (isset($_POST['Confirm'])) {
     
    	// Convert the query string to a number before executing sql query
    	$Id = intval($_POST['Confirm']);
     
    	$Results = $Page->Query("SELECT item_id FROM attachments WHERE id=$Id LIMIT 1;");
    	$SelectAdvertId = $Page->FetchArray($Results);
     
    	// Ensure the user trying to remove an attachment is the author of the advert it was attached to
    	if (!$Page->CheckUserAuth($SelectAdvertId['item_id'], 1)) {
     
    		echo "blankdiv|";
    		exit;
     
    	}
     
    	$Results = $Page->Query("SELECT * FROM attachments WHERE id=$Id LIMIT 1;");
    	$SelectFilename = $Page->FetchArray($Results);
    	$RemoveFile = unlink($Page->Settings['UploadDir'] . $SelectFilename['filename']);
    	$RemoveFileFromDb = $Page->Query("DELETE FROM attachments WHERE id=$Id LIMIT 1;");
     
    	$Result = "removeattachment|";
    	$Result .= "<span class=\"error\">You have successfully removed an attachment. You can now add a new attachment to this advert below:</span><br />";
    	$Result .= "<input type=\"file\" name=\"Attachment\" style=\"width: 350px;\" /><br /><br />\r\n";
    	$Result .= "You may attach one file to an advert above. This can be an image, word document or PDF.\r\n";
     
    	echo $Result;
    	exit;
     
    }
     
    if (isset($_POST['Cancel'])) {
     
    	// Convert the query string to a number before executing sql query
    	$Id = intval($_POST['Cancel']);
     
    	$SelectAttachment = $Page->Query("SELECT * FROM attachments WHERE id=$Id LIMIT 1;");
     
    	// Check to see if there are actually any attachments for this item
    	if ($Page->GetNumRows($SelectAttachment) > 0) {
     
    		// If results are found then grab them
    		$Attachment = $Page->FetchArray($SelectAttachment);
     
    		$Result = "removeattachment|";
    		$Result .= '<p>This item has an <a href="' . $Page->Settings['SiteUrl'] . '/uploads/' . $Attachment['filename'] . '" target="new">attachment</a>, you can <input type="button" class="button" onclick="javascript:RemoveAttachment(' . $Attachment['id'] . ');" value="REMOVE" /> it to add a different one.</p>' . "\r\n";
     
    	} else {
     
    		$Result = "removeattachment|$Id";
    		$Result .= "<input type=\"file\" name=\"Attachment\" style=\"width: 350px;\" /><br /><br />\r\n";
    		$Result .= "You may attach one file to an advert above. This can be an image, word document or PDF.\r\n";
     
    	}
     
    	echo $Result;
    	exit;
     
    }
     
    if (isset($_POST['Id'])) {
     
    	// Convert the query string to a number before executing sql query
    	$Id = intval($_POST['Id']);
     
    	$Results = $Page->Query("SELECT item_id FROM attachments WHERE id=$Id LIMIT 1;");
    	$SelectAdvertId = $Page->FetchArray($Results);
     
    	// Ensure the user trying to remove an attachment is the author of the advert it was attached to
    	if (!$Page->CheckUserAuth($SelectAdvertId['item_id'], 1)) {
     
    		echo "blankdiv|";
    		exit;
     
    	}
     
    	$Result = "removeattachment|";
    	$Result .= "You have selected to remove this ad's attachment.<br /><br />";
    	$Result .= '<em>Please confirm that you wish to remove this attachment.</em><br /><br />';
    	$Result .= '<input type="button" class="confirm" value="CONFIRM" onclick="javascript:ConfirmRemove(' . $Id . ');" />&nbsp; <input type="button" class="confirm" value="CANCEL" onclick="javascript:CancelRemove(' . $Id . ');" />';
     
    	echo $Result;
    	exit;
     
    }
    ?>

    So what happens in this code is I can click the Remove button just fine, and it does the AJAX call ok and returns the new content from RemoveAttachment.php. Then when I click the Cancel button it goes back to the original contents of the removeattachment paragraph. However if I click the Remove button once again it doesn't do anything. This is where it falls over. In FF I just get no response and in IE7 I get a Line: 1, Char: 1, Error: Object doesn't support this property or method.

    I must be missing something really easy here and it's bugging the hell out of me lol. Can anyone see where I might be going wrong?
    Thanks for taking the time to read my long question, it is appreciated!

    Regards,
    Alex

  2. #2
    rajug.replace('Raju Gautam'); bronze trophy Raju Gautam's Avatar
    Join Date
    Oct 2006
    Location
    Kathmandu, Nepal
    Posts
    4,013
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Did you fix the problem already? It seems it is working fine when i click 'Yes' button again and again after coming back from clicking on 'Cancel'. I tried in FF3 and IE7, in both it is working fine.
    Mistakes are proof that you are trying.....
    ------------------------------------------------------------------------
    PSD to HTML - SlicingArt.com | Personal Blog | ZCE - PHP 5

  3. #3
    SitePoint Enthusiast
    Join Date
    Jan 2005
    Location
    Hobart, Australia
    Posts
    81
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The example from the URL is the working example that I provided to show what I was trying to do. The problem is in the code after I place it into my application. Do you mean the http://www.kekbur.com/alex/removetest/test.php URL is working for you? Because sorry that does work for me, it's the other code that fails. Sorry if I wasn't clear enough to start with.

    Thanks

  4. #4
    SitePoint Enthusiast
    Join Date
    Jan 2005
    Location
    Hobart, Australia
    Posts
    81
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi guys, does anyone else have any ideas?

    Thanks

  5. #5
    SitePoint Enthusiast
    Join Date
    Jan 2005
    Location
    Hobart, Australia
    Posts
    81
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Eureka!

    I renamed the javascript function from RemoveAttachment to fnRemoveAttachment and now it works perfectly. Perhaps JavaScript has problems when the functions name is the same as the PHP file it is calling?

    VERY weird one but I would love to know more if any one has any ideas. I am very relied, thanks for reading my post people.

    Regards,
    Alex


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •