PHP File not loading via AJAX

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • nathj
    Recognized Expert Contributor
    • May 2007
    • 937

    PHP File not loading via AJAX

    Hi,

    I am currently working on a new site that offers various files for download. The file information is stored in a MySQL database and the page is produced in PHP depending on how the user got to the page:

    [php]
    <?php
    session_start() ;
    $_SESSION['pageStyle'] = $_SESSION['pageStyle']; // set to whatever is, as you can only access this page from within a top level section
    ?>
    <!--
    File: download.php
    Author: Nathan Davies
    Created: 09/08/2007
    Purpose: The downloads from the CLF site - for each topic type
    -->
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
    <?php
    include("includ e/pageHeader.php" );

    if($loUser->hasAccess(1) ||$loUser->hasAccess(2) || $loUser->hasAccess(3) )
    {
    // establish where this page was called from
    if(isset($_GET['topicID']) && isset($_GET['topicType'])) // use isset as 0 is valid for this page
    {
    $lnTopicID = $_GET['topicID'] ;
    $lnTopicType = $_GET['topicType'] ;

    switch($lnTopic Type)
    {
    case 0: // ad hoc entries that appear under general resources
    $lnSubSection = 4 ;
    $lcDownloadSele ct =
    "SELECT
    a.ID, a.name, a.url, a.typeID,
    b.description
    FROM download a
    LEFT OUTER JOIN downloadtype b on b.ID = a.typeID
    WHERE a.topicType = $lnTopicType
    ORDER BY a.typeID ASC" ; // this set is only ever the full set
    break ;
    case 1: // event downloads
    $lnSubSection = 2 ;
    $lcDownloadSele ct =
    "SELECT
    a.ID, a.name, a.url, a.typeID, a.topicID,
    b.title,
    c.description
    FROM download a
    LEFT OUTER JOIN event b on b.ID = a.topicID
    LEFT OUTER JOIN downloadtype c on c.ID = a.typeID
    WHERE a.topicType = $lnTopicType" ;

    // if only one specific event then add that condition to the SQL statement
    if($lnTopicID > 0)
    {
    $lcDownloadSele ct .= " AND a.topicID = $lnTopicID" ;
    }
    $lcDownloadSele ct .= " ORDER BY a.topicID ASC" ;
    break ;
    case 2: // module downloads
    $lnSubSection = 3 ;
    $lcDownloadSele ct =
    "SELECT
    a.ID, a.name, a.url, a.typeID, a.topicID,
    b.title,
    c.description
    FROM download a
    LEFT OUTER JOIN module b on b.ID = a.topicID
    LEFT OUTER JOIN downloadtype c on c.ID = a.typeID
    WHERE a.topicType = $lnTopicType" ;

    // if only one specific module then add that condition to the SQL statement
    if($lnTopicID > 0)
    {
    $lcDownloadSele ct .= " AND a.topicID = $lnTopicID" ;
    }
    $lcDownloadSele ct .= " ORDER BY a.topicID ASC" ;
    break ;
    }

    include("includ e/subSectionTitle AndNavigation.p hp") ;

    // execute the query

    $laDownload = $loDB->queryGetData($ lcDownloadSelec t) ;

    if($laDownload)
    {
    // there is information to display
    switch($lnTopic Type)
    {
    case 0: // general
    echo '<h1 class="pageTitl e">General Downloads</h1><br />' ;
    echo $lcGeneralText ;
    echo '<p>' ;
    echo 'The items available here are listed by file type - e.g. PDF, MP3 etc' ;
    echo '</p>' ;
    break ;
    case 1: // event
    echo '<h1 class="pageTitl e">Event Downloads</h1><br />' ;
    echo $lcGeneralText ;
    echo '<p>' ;
    echo 'The items available here are listed by event title' ;
    echo '</p>' ;
    break ;
    case 2: // module
    echo '<h1 class="pageTitl e">Training Downloads</h1><br />' ;
    echo $lcGeneralText ;
    echo '<p>' ;
    echo 'The items available here are listed by module title.';
    echo '</p>' ;
    break ;
    }

    $lnCurrentCateg oryID = -1 ;
    foreach($laDown load as $laDownloadItem )
    {
    switch($lnTopic Type)
    {
    case 0: // general
    $lnNextCategory ID = $laDownloadItem['typeID'] ;
    if($lnNextCateg oryID != $lnCurrentCateg oryID)
    {
    // the category has changed, display a new sub-heading $laDownloadItem['description']
    echo '<h4 class="eventLis tItem">Download Category: ' . substr_replace( $laDownloadItem['description'], strtoupper(subs tr($laDownloadI tem['description'], 0, 1)), 0, 1) . '</h4>' ;
    // change the meta data
    $lnCurrentCateg oryID = $lnNextCategory ID ;
    }

    break ;

    case 1: // event
    $lnNextCategory ID = $laDownloadItem['topicID'] ;
    if($lnNextCateg oryID != $lnCurrentCateg oryID)
    {
    // the category has changed, display a new sub-heading
    echo '<h4 class="eventLis tItem">Event: ' . substr_replace( $laDownloadItem['title'], strtoupper(subs tr($laDownloadI tem['title'], 0, 1)), 0, 1) . '</h4>' ;
    // change the meta data
    $lnCurrentCateg oryID = $lnNextCategory ID ;
    }

    break ;

    case 2: // module
    $lnNextCategory ID = $laDownloadItem['topicID'] ;
    if($lnNextCateg oryID != $lnCurrentCateg oryID)
    {
    // the category has changed, display a new sub-heading
    echo '<h4 class="eventLis tItem">Module: ' . substr_replace( $laDownloadItem['title'], strtoupper(subs tr($laDownloadI tem['title'], 0, 1)), 0, 1) . '</h4>' ;
    // change the meta data
    $lnCurrentCateg oryID = $lnNextCategory ID ;
    }

    break ;
    }
    // write the stuff that's the same for each type - the link - url, name and the onclick code using the ID to update the association between leader and download
    // note the update is only for leaders - so another hasAccess check is required.
    echo '<p class="linkList ">' ;
    if ($loUser->hasAccess(1) )
    {
    echo '<a id="' . $laDownloadItem['ID'] . '" "class="inlineL ink" href="' . $laDownloadItem['url'] . '" title="' . $laDownloadItem['name'] . '" onclick="dataUp date(1, ' . $laDownloadItem['ID'] . ')">' . $laDownloadItem['name'] . '</a><br />';
    }
    else
    {
    echo '<a class="inlineLi nk" href="' . $laDownloadItem['url'] . '" title="' . $laDownloadItem['name'] . '">' . $laDownloadItem['name'] . '</a><br />';
    }
    echo '</p>';

    }
    echo '<br />' ; // just to give it some room to breathe
    }
    else
    {
    echo '<p>' ;
    echo 'There are currently no downloads available. ' ;
    echo 'New information is loaded regularly so please check back soon.' ;
    echo '</p>' ;
    echo '<p>' ;
    echo 'In the mean time please feel free to browse around the rest of the site.' ;
    echo '</p>' ;
    }
    }
    else
    {
    echo '<p>' ;
    echo 'Unfortunately this page was accessed incorrectly.' ;
    echo '</p>' ;
    echo '<p>' ;
    echo 'There are 3 valid ways into this page - via Resources, Leaders Forum and Training. ';
    echo 'It is essential that you are a registered with the site and that you are currently logged in.' ;
    echo '</p>' ;
    }
    }
    else
    {
    echo '<p>' ;
    echo 'Access to this area of the site is for members only. If you are a member already please log in.' ;
    echo '</p>' ;
    echo '<p>' ;
    echo 'If you would like to join the Christian Leadership Foundation please take a moment to complete the <a class="inlineLi nk" href="applicati on.php?step=1" title="Applicat ion Form">form</a>.' ;
    echo '</p>' ;
    }
    include("includ e/pageFooter.php" );
    ?>

    [/php]

    On downloading a file the idea is that a record is either updated in or added to the database. The purpose of this is so that at a later date I can make recommendations within the members area based on the category of downloads they have been interested in previously. A simplistic recommendation system.

    In order to do this the link to the download file has an onClick that calls a JavaSacript function

    Code:
    function dataUpdate(pnType, pnItem)
    {
    	GetXmlHttpObject() ;
    	gcUrl = "../lib/dataupdateajax.php?type=" + pnType + "&item=" + pnItem 
    	gcItemID = pnItem
    	goXMLHTTP.onreadystatechange = function()
    	{ 
    		if (goXMLHTTP.readyState==4 || goXMLHTTP.readyState=="complete")
    		{ 
    			alert("Enjoy");
    		}
    	}  ;
    	goXMLHTTP.open("GET",gcUrl,true) ;
    	goXMLHTTP.send(null) ;
    }
    This is getting called - the alert tells me that. However, the URL listed is not being called. I have used this methodology for form validation previously without problem.

    I know it's not getting into the PHP code because I have echo lines in there before any conditions are tested and they don't execute.

    The basic problem is that I can't get the php file dataupdateajax. php to load.

    Any suggestions on this or alternative ways to build a recommendation system will be greatly appreciated.

    Cheers
    nathj
  • ak1dnar
    Recognized Expert Top Contributor
    • Jan 2007
    • 1584

    #2
    There is a ";" on line number 12 on the javascript. what is it really.

    Comment

    • nathj
      Recognized Expert Contributor
      • May 2007
      • 937

      #3
      Originally posted by ajaxrand
      There is a ";" on line number 12 on the javascript. what is it really.
      Hi Ajaxrand,

      That's what it is. Should this be removed do you think?

      Cheers
      nathj

      Comment

      • ak1dnar
        Recognized Expert Top Contributor
        • Jan 2007
        • 1584

        #4
        Originally posted by nathj
        Hi Ajaxrand,

        That's what it is. Should this be removed do you think?

        Cheers
        nathj
        Really I didn't go through the your php coding yet. That semicolon doesn't makes any sense to me. If you are thinking there is a issue with the URL of the Server script too, try the absolute URL, instead the relative.

        Comment

        • nathj
          Recognized Expert Contributor
          • May 2007
          • 937

          #5
          Originally posted by ajaxrand
          Really I didn't go through the your php coding yet. That semicolon doesn't makes any sense to me. If you are thinking there is a issue with the URL of the Server script too, try the absolute URL, instead the relative.
          Hi Ajaxrand,

          I have removed the semi colon and I have altered the url to be the full path. However, this has made no noticeable difference.

          I have checked the case of the php file in the code and on the server to ensure they are the same and I've been caught out by that before.

          As far as I can tell the onclick event is firing nicely and the javascript fnction is executing but the XMLHTTP object is not actually running the PHP code in dataupdateajax. php.

          I have used code like this previously with no problems so I'm completely flumoxed by this issue.

          I have also watched the code using Firebug and I can see now errors there.

          Any further thoughts at all?

          Cheers
          nathj

          Comment

          • jx2
            New Member
            • Feb 2007
            • 228

            #6
            pnType and pnItem are not url encoded that might cose problems (e.g. if there is a space in it)
            regards
            jx2

            Comment

            • nathj
              Recognized Expert Contributor
              • May 2007
              • 937

              #7
              Originally posted by jx2
              pnType and pnItem are not url encoded that might cose problems (e.g. if there is a space in it)
              regards
              jx2
              Hi jx2,

              I'll add some code to ensure there are no spaces but at present they equate to 1 and 3 respectively.

              I should have said that in my original post - sorry.

              Cheers
              nathj

              Comment

              • ak1dnar
                Recognized Expert Top Contributor
                • Jan 2007
                • 1584

                #8
                Originally posted by nathj
                Hi jx2,

                I'll add some code to ensure there are no spaces but at present they equate to 1 and 3 respectively.

                I should have said that in my original post - sorry.

                Cheers
                nathj
                Please post back your javaScript coding that you have used to create XMLHttpRequest. and the calling JS function for the Php.

                Comment

                • nathj
                  Recognized Expert Contributor
                  • May 2007
                  • 937

                  #9
                  Originally posted by ajaxrand
                  Please post back your javaScript coding that you have used to create XMLHttpRequest. and the calling JS function for the Php.
                  Ajaxrand,

                  Heres the html line that calls the javascript:
                  [html]<a id="3"class="in lineLink"href=" http://www.christianle adership.org.uk/m3u/eddiegibbs_sess ion1.m3u"title= "What Good Looks Like - Session 1(mp3)"onclick= "dataUpdate (1, 3)">What Good Looks Like - Session 1(mp3)</a>
                  [/html]

                  This is generated in PHP based on records in a database.

                  The function that is called in the above code is:
                  [code=javascript]
                  function dataUpdate(pnTy pe, pnItem)

                  {

                  GetXmlHttpObjec t() ;

                  gcUrl = "http://www.christianle adership.org.uk/lib/dataupdateajax. php?type=" + pnType + "&item=" + pnItem

                  gcItemID = pnItem

                  goXMLHTTP.onrea dystatechange = function()

                  {

                  if (goXMLHTTP.read yState==4 || goXMLHTTP.ready State=="complet e")

                  {

                  alert("Enjoy"); // needs to change to something else

                  }

                  }

                  goXMLHTTP.open( "GET",gcUrl,tru e) ;

                  goXMLHTTP.send( null) ;

                  }
                  [/code]

                  This instantiates the goXMLHTTP object via the following JavaScript
                  (I use this function in other places and it works fine.)

                  [code=javascript]
                  function GetXmlHttpObjec t()

                  {

                  if (window.XMLHttp Request)

                  {

                  goXMLHTTP=new XMLHttpRequest( )

                  }

                  else if (window.ActiveX Object)

                  {

                  goXMLHTTP=new ActiveXObject(" Microsoft.XMLHT TP")

                  }

                  if (goXMLHTTP==nul l)

                  {

                  alert ("Browser does not support HTTP Request")

                  return

                  }

                  }
                  [/code]

                  I think thats all the code you asked for, if there's anything else let me know and I'll pos it happily - I really need some help with this as it's driving me mad.

                  Cheers
                  nathj

                  PS Are there specific code tags for javascript?
                  Last edited by ak1dnar; Sep 5 '07, 06:43 AM. Reason: Added the [code=javascript] Tags

                  Comment

                  • ak1dnar
                    Recognized Expert Top Contributor
                    • Jan 2007
                    • 1584

                    #10
                    Hi nathj,
                    Once you created a variable/object on a function, you have to return them to calling function. then Only you can use them.

                    check out this:

                    [CODE=javascript]
                    function GetXmlHttpObjec t()
                    {
                    if (window.XMLHttp Request)
                    {
                    goXMLHTTP=new XMLHttpRequest( )
                    }
                    else if (window.ActiveX Object)
                    {
                    goXMLHTTP=new ActiveXObject(" Microsoft.XMLHT TP")
                    }
                    if (goXMLHTTP==nul l)
                    {
                    alert ("Browser does not support HTTP Request")
                    return
                    }
                    return goXMLHTTP; // This Line is Missing in yours
                    }
                    [/CODE]

                    Comment

                    • nathj
                      Recognized Expert Contributor
                      • May 2007
                      • 937

                      #11
                      Originally posted by ajaxrand
                      Hi nathj,
                      Once you created a variable/object on a function, you have to return them to calling function. then Only you can use them.

                      check out this:

                      [CODE=javascript]
                      function GetXmlHttpObjec t()
                      {
                      if (window.XMLHttp Request)
                      {
                      goXMLHTTP=new XMLHttpRequest( )
                      }
                      else if (window.ActiveX Object)
                      {
                      goXMLHTTP=new ActiveXObject(" Microsoft.XMLHT TP")
                      }
                      if (goXMLHTTP==nul l)
                      {
                      alert ("Browser does not support HTTP Request")
                      return
                      }
                      return goXMLHTTP; // This Line is Missing in yours
                      }
                      [/CODE]
                      Hi,

                      Thats my bad, the goXMMLHTTP is a global variable. I had forgotten to declare it as such in my code so I have now done that but the problem persists. It still doesn't seem to be entering the code specified in the URL.

                      Cheers
                      nathj

                      PS Normally I don't like globals but I know there was a reason I used one here but right now I can't think of it. All I know is that it works in other cases.

                      Comment

                      • ak1dnar
                        Recognized Expert Top Contributor
                        • Jan 2007
                        • 1584

                        #12
                        nathj,
                        Check this out, I made some changes. If your Javascripts functions in separate files, how about merge them, like this to a single unit at least for now.

                        [CODE=javascript]var xmlHttp;
                        function GetXmlHttpObjec t()
                        {
                        if (window.XMLHttp Request)
                        {
                        goXMLHTTP=new XMLHttpRequest( )
                        }
                        else if (window.ActiveX Object)
                        {
                        goXMLHTTP=new ActiveXObject(" Microsoft.XMLHT TP")
                        }
                        if (goXMLHTTP==nul l)
                        {
                        alert ("Browser does not support HTTP Request")
                        return
                        }
                        return goXMLHTTP;
                        }

                        function dataUpdate(pnTy pe, pnItem){
                        xmlHttp=GetXmlH ttpObject();
                        gcUrl = "server.php?typ e=" + pnType + "&item=" + pnItem
                        gcItemID = pnItem
                        xmlHttp.onready statechange=get TheResponse;
                        xmlHttp.open("G ET",gcUrl,true) ;
                        xmlHttp.send(nu ll);
                        }

                        function getTheResponse( ){
                        if (xmlHttp.readyS tate==4)
                        {
                        if (xmlHttp.status == 200){
                        alert(xmlHttp.r esponseText);// Assumed that you are using HTML out put
                        }
                        }
                        }
                        [/CODE]

                        call dataUpdate function with the some parameters.

                        If you just want to check the working condition of your JS, forget about your real php script and Do something like this. This should print alert box saying "Server is Here". post back with your updates.

                        server.php

                        [CODE=php]<?Php
                        echo 'Server is Here';
                        ?>[/CODE]

                        Comment

                        • nathj
                          Recognized Expert Contributor
                          • May 2007
                          • 937

                          #13
                          Hi Ajaxrand,

                          The javascript is all in one file - functionlibrary .js.

                          I have altered the function that instantiates the goXMLHTTP variable so that it returns the object.

                          I have also 'installed' the functions you recommend and changed the php page to simply echo as you suggest.

                          The result is still the same. Do you think this could be due to the fact that the calling line is to download a file?

                          [html]
                          <a id="3"class="in lineLink"href=" http://www.christianle adership.org.uk/m3u/eddiegibbs_sess ion1.m3u"title= "What Good Looks Like - Session 1(mp3)"onclick= "dataUpdate (1, 3)">What Good Looks Like - Session 1(mp3)</a>
                          [/html]

                          I really appreciate your help with this.

                          Many thanks
                          nathj

                          Comment

                          • ak1dnar
                            Recognized Expert Top Contributor
                            • Jan 2007
                            • 1584

                            #14
                            "Problem still the same", Is that mean nothing is happening.
                            First can you call for the download page with the Javascript file?
                            comment other all the other contents on the download.php and Just try to echo something back to the calling page.

                            And 1 more thing, replace this.

                            [CODE=html]
                            <a id="3"class="in lineLink"href=" http://www.christianle adership.org.uk/m3u/eddiegibbs_sess ion1.m3u"title= "What Good Looks Like - Session 1(mp3)"onclick= "dataUpdate (1, 3)">What Good Looks Like - Session 1(mp3)</a>
                            [/CODE]

                            with this.

                            [CODE=html]
                            <a id="3"class="in lineLink"href=" #"title="Wha t Good Looks Like - Session 1(mp3)"onclick= "dataUpdate (1, 3)">What Good Looks Like - Session 1(mp3)</a>
                            [/CODE]

                            Comment

                            • nathj
                              Recognized Expert Contributor
                              • May 2007
                              • 937

                              #15
                              Originally posted by ajaxrand
                              "Problem still the same", Is that mean nothing is happening.
                              First can you call for the download page with the Javascript file?
                              comment other all the other contents on the download.php and Just try to echo something back to the calling page.

                              And 1 more thing, replace this.

                              [CODE=html]
                              <a id="3"class="in lineLink"href=" http://www.christianle adership.org.uk/m3u/eddiegibbs_sess ion1.m3u"title= "What Good Looks Like - Session 1(mp3)"onclick= "dataUpdate (1, 3)">What Good Looks Like - Session 1(mp3)</a>
                              [/CODE]

                              with this.

                              [CODE=html]
                              <a id="3"class="in lineLink"href=" #"title="Wha t Good Looks Like - Session 1(mp3)"onclick= "dataUpdate (1, 3)">What Good Looks Like - Session 1(mp3)</a>
                              [/CODE]
                              Hi Ajaxrand,

                              Making the change you suggest - so that the download page is stripped to nothing but a link really and the link has no url in it I get the alert box.

                              However, if I change the link to point at the file for download I don't get the alert box.

                              Thanks again for taking the time to help, I realy appreciate it.
                              nathj

                              Comment

                              Working...