Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
CODE PROJECT For Those Who Code
  • Home
  • Articles
  • FAQ
Community
  1. Home
  2. Web Development
  3. Linux, Apache, MySQL, PHP
  4. AJAX & PHP

AJAX & PHP

Scheduled Pinned Locked Moved Linux, Apache, MySQL, PHP
helpphptoolstutorialquestion
15 Posts 4 Posters 92 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • I it_8x

    i will help you

    P Offline
    P Offline
    Perspx
    wrote on last edited by
    #4

    A clear and concise response statement :) I didn't know that CP had implemented telepathy.. :rolleyes:

    "A refund for defective software might be nice, except it would bankrupt the entire software industry in the first year."
    -Andrew Tanenbaum
    "Einstein argued that there must be simplified explanations of nature, because God is not capricious or arbitrary. No such faith comforts the software engineer."
    -Fred Brooks

    B 1 Reply Last reply
    0
    • P Perspx

      A clear and concise response statement :) I didn't know that CP had implemented telepathy.. :rolleyes:

      "A refund for defective software might be nice, except it would bankrupt the entire software industry in the first year."
      -Andrew Tanenbaum
      "Einstein argued that there must be simplified explanations of nature, because God is not capricious or arbitrary. No such faith comforts the software engineer."
      -Fred Brooks

      B Offline
      B Offline
      Bryant May
      wrote on last edited by
      #5

      Does anyone have any answers on this? I'm running out of hair very rapidly :laugh:

      1 Reply Last reply
      0
      • B Bryant May

        Hello everyone, Im having a bit of trouble with Ajax & php that Im hoping someone can help me with. I've had a search about on this but have been unable to find anything out... My problem is this: I have set up an Ajax function which is executed on the click of a button (in context this is a password reminder system when logging in to a CMS) which opens up a short php script containing a form held within a couple of divs. Everything works as it should; the the script is called, displayed and functions correctly. But for the life of me I cannot work out how to access variables that I set in the php script. I want to be able to say (in my Ajax function): "if this php variable holds this value, then execute this part of the Ajax function" My Ajax code looks like this:

        //Submit the password reminder form
        function checkRemForm(email, div)
        {
        //checkValidEmail(email, div);
        createObject();

        if (XMLHttpRequestObject)
        {
        	var targetDiv = document.getElementById(div);
        	var url = "/cms/\_sql/sendPassword.php?email=" +email;
        	
        	XMLHttpRequestObject.open('GET', url, true);
        
        	XMLHttpRequestObject.onreadystatechange = function()
        	{
        		if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200)
        		{
        			var result = XMLHttpRequestObject.responseText;
        			targetDiv.innerHTML = result;
        		}
        	}
        	XMLHttpRequestObject.send(null);
        
        }
        

        }

        The php is currently just initialising a variable and looks like this:

        So the aim of this bit of code is to be able to access the value of $email in my Ajax function. As you can imagine im just learning Ajax so I hope that i have understood how the two languages work together. If anyone has any help or advise I would appreciate it massively. Thanks Bryant :)

        I Offline
        I Offline
        Ioannis_o5
        wrote on last edited by
        #6

        Although I am not sure that I can help you the way you put the question, I will try. I use a lot of Ajax and in my opinion i. you are close to the traditional way , ii . you could find other solutions. My comments : a. Your example seems to be OK. Of course it returns whatever you havae passed as email. Pls confirm that is is so. b. Do I understand that you want to pass THE NAME of a variable and receive a value OR IS IT you want the calling javascript to decide what to do and NOT the called PHP. c. Before you clear this II would suggest : Wht don't you store your values in the php script in arrays like this $name= "Napoleon"; $myphone = "199199"; $myvalues[]=array("name" => $name , "phone" => $myphone ); $value_of_param= $_GET["req"]; // req is in place of your email variable echo $myvalues[$value_of_param]; (I hope I have no typo errors)

        B 1 Reply Last reply
        0
        • I Ioannis_o5

          Although I am not sure that I can help you the way you put the question, I will try. I use a lot of Ajax and in my opinion i. you are close to the traditional way , ii . you could find other solutions. My comments : a. Your example seems to be OK. Of course it returns whatever you havae passed as email. Pls confirm that is is so. b. Do I understand that you want to pass THE NAME of a variable and receive a value OR IS IT you want the calling javascript to decide what to do and NOT the called PHP. c. Before you clear this II would suggest : Wht don't you store your values in the php script in arrays like this $name= "Napoleon"; $myphone = "199199"; $myvalues[]=array("name" => $name , "phone" => $myphone ); $value_of_param= $_GET["req"]; // req is in place of your email variable echo $myvalues[$value_of_param]; (I hope I have no typo errors)

          B Offline
          B Offline
          Bryant May
          wrote on last edited by
          #7

          Hi there, thanks for getting back to me! I'll try and be a bit clearer on what im asking...So, I have an Ajax function that calls a php script which contains a variable with a value (lets say $one = 1). If I print this variable in my php script (print $one;) and output it in my Ajax function like so:

          var result = XMLHttpRequestObject.responseText;
          document.getElementById("div").innerHTML = result;

          This will obviously output the variable value of 1 to "div". But what i actually want to do is, in my ajax function say

          var result = XMLHttpRequestObject.responseText;
          if (result.$one == 1)
          {
          somecodeHere;
          }

          Hopefully thats a little clearer. If you need me to explain further thats no problem. Thank you Bryant

          I 1 Reply Last reply
          0
          • B Bryant May

            Hi there, thanks for getting back to me! I'll try and be a bit clearer on what im asking...So, I have an Ajax function that calls a php script which contains a variable with a value (lets say $one = 1). If I print this variable in my php script (print $one;) and output it in my Ajax function like so:

            var result = XMLHttpRequestObject.responseText;
            document.getElementById("div").innerHTML = result;

            This will obviously output the variable value of 1 to "div". But what i actually want to do is, in my ajax function say

            var result = XMLHttpRequestObject.responseText;
            if (result.$one == 1)
            {
            somecodeHere;
            }

            Hopefully thats a little clearer. If you need me to explain further thats no problem. Thank you Bryant

            I Offline
            I Offline
            Ioannis_o5
            wrote on last edited by
            #8

            Hello again Bryant, I believe that your $one should be passed to the php page and the response must be the value of $one. This

            result.$one

            doent look 'nice' to me. For instance if there should be a variable in your php code called $one , if you don't follow my previous comment for an array then it could look like :

            $variable_name = $_GET["req"];
            if ($variable_name == "one")
            echo $one;
            /// etc.

            This means of course that your java line that creates the URL should be like :

            var url = "/cms/_sql/sendPassword.php?req=one"

            and then your script (above) changes to

            var result = XMLHttpRequestObject.responseText;
            if (result == '1')
            { somecodeHere;
            }

            I ll be glad to help more if I can

            B 1 Reply Last reply
            0
            • I Ioannis_o5

              Hello again Bryant, I believe that your $one should be passed to the php page and the response must be the value of $one. This

              result.$one

              doent look 'nice' to me. For instance if there should be a variable in your php code called $one , if you don't follow my previous comment for an array then it could look like :

              $variable_name = $_GET["req"];
              if ($variable_name == "one")
              echo $one;
              /// etc.

              This means of course that your java line that creates the URL should be like :

              var url = "/cms/_sql/sendPassword.php?req=one"

              and then your script (above) changes to

              var result = XMLHttpRequestObject.responseText;
              if (result == '1')
              { somecodeHere;
              }

              I ll be glad to help more if I can

              B Offline
              B Offline
              Bryant May
              wrote on last edited by
              #9

              hey cheers for getting back to me so quickly. Hopefully Im starting to understand this after your excellent explanation. Heres where Im getting lost.. Whats going to happen in my script is that an email address is going to be checked to make sure it is valid. If it is then I want my php script to initialise a variable which is then sent back in the responsetext object which I want to be able to access from the ajax function. It looks kind of like this:

              function checkRemForm(email, div)
              {

              createObject();

              if (XMLHttpRequestObject)
              {
              var url = "/cms/_sql/sendPassword.php?email=" +email.value;

              XMLHttpRequestObject.open('GET', url, true);

              XMLHttpRequestObject.onreadystatechange = function()
              {
              if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200)
              {
              var result = XMLHttpRequestObject.responseText;
              if (result == 1)
              {
              targetDiv.innerHTML = result;
              }
              else
              targetDiv.innerHTML = "no";
              }
              }
              XMLHttpRequestObject.send(null);
              }

              and my php, at the moment is simply

              $email = $_GET['email'];
              print $email;
              $one = 1;

              ?>

              In the end, the php script will run an sql statement, checking the email against a database and if its all ok the $one variable will be initialised. It is this that i want access to in my ajax script, like I have shown above. Sorry if Im being stupid about this, Ive tried everything I can think of to get at that $one!! Once again, thank you for your time and help. Bryant

              I 1 Reply Last reply
              0
              • B Bryant May

                hey cheers for getting back to me so quickly. Hopefully Im starting to understand this after your excellent explanation. Heres where Im getting lost.. Whats going to happen in my script is that an email address is going to be checked to make sure it is valid. If it is then I want my php script to initialise a variable which is then sent back in the responsetext object which I want to be able to access from the ajax function. It looks kind of like this:

                function checkRemForm(email, div)
                {

                createObject();

                if (XMLHttpRequestObject)
                {
                var url = "/cms/_sql/sendPassword.php?email=" +email.value;

                XMLHttpRequestObject.open('GET', url, true);

                XMLHttpRequestObject.onreadystatechange = function()
                {
                if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200)
                {
                var result = XMLHttpRequestObject.responseText;
                if (result == 1)
                {
                targetDiv.innerHTML = result;
                }
                else
                targetDiv.innerHTML = "no";
                }
                }
                XMLHttpRequestObject.send(null);
                }

                and my php, at the moment is simply

                $email = $_GET['email'];
                print $email;
                $one = 1;

                ?>

                In the end, the php script will run an sql statement, checking the email against a database and if its all ok the $one variable will be initialised. It is this that i want access to in my ajax script, like I have shown above. Sorry if Im being stupid about this, Ive tried everything I can think of to get at that $one!! Once again, thank you for your time and help. Bryant

                I Offline
                I Offline
                Ioannis_o5
                wrote on last edited by
                #10

                I ve just written this little piece of code (interrupting my VB project development - dont bother I like it) :

                if (isset($_GET["email"])) // if the email var was passed
                {
                include('dbconn.php') // connect etc. to your mysql - i have this stuff in dbconn.php
                $query="select email,blabla,etc FROM MyTable WHERE email='".$_GET["email"]."'";
                $result=mysql_query($query) or die('0');
                if (mysql_num_rows($result)>0) // if at least one record with this email
                echo '1'; // then send 1
                else
                echo '0'; // else send 0
                mysql_free_result($result);
                }

                I you have questions be back. Anyway let me know : did this help ?

                B 1 Reply Last reply
                0
                • I Ioannis_o5

                  I ve just written this little piece of code (interrupting my VB project development - dont bother I like it) :

                  if (isset($_GET["email"])) // if the email var was passed
                  {
                  include('dbconn.php') // connect etc. to your mysql - i have this stuff in dbconn.php
                  $query="select email,blabla,etc FROM MyTable WHERE email='".$_GET["email"]."'";
                  $result=mysql_query($query) or die('0');
                  if (mysql_num_rows($result)>0) // if at least one record with this email
                  echo '1'; // then send 1
                  else
                  echo '0'; // else send 0
                  mysql_free_result($result);
                  }

                  I you have questions be back. Anyway let me know : did this help ?

                  B Offline
                  B Offline
                  Bryant May
                  wrote on last edited by
                  #11

                  Im sorry to interupt your work.....I'll continue to do it though by asking you this :) That bit of code that you added is all fine, I can do that...php is the language I am most familiar with. The problem comes when I try to access the '1' in javascript. I dont actually want to output the '1', I just want to set it. So your 'if' statement becomes: if (mysql_num_rows($result)>0) $one = 1; I then need to be able to say (in my ajax statement): (pseudo code)

                  if (in result $one equals 1)
                  {
                  do this;
                  }

                  Remembering that 'result' is the value of responseText. So basically, how do I access a variable value passed FROM php TO an ajax function. To say it plainly.

                  I 1 Reply Last reply
                  0
                  • B Bryant May

                    Im sorry to interupt your work.....I'll continue to do it though by asking you this :) That bit of code that you added is all fine, I can do that...php is the language I am most familiar with. The problem comes when I try to access the '1' in javascript. I dont actually want to output the '1', I just want to set it. So your 'if' statement becomes: if (mysql_num_rows($result)>0) $one = 1; I then need to be able to say (in my ajax statement): (pseudo code)

                    if (in result $one equals 1)
                    {
                    do this;
                    }

                    Remembering that 'result' is the value of responseText. So basically, how do I access a variable value passed FROM php TO an ajax function. To say it plainly.

                    I Offline
                    I Offline
                    Ioannis_o5
                    wrote on last edited by
                    #12

                    I will disappoint you : You can't do that BUT you need not do that ! Think of the php page as a black box which can ONLY return a return string to the requesting javascript. That is : the javascript via the URL "thinks" that it requests a page from the server. The requested page (php) is executed and with the echo (or the print) statement it can send back text. This text received can be anything you like - anything the php programmer has designed. And this text is received in the

                    XMLHttpRequestObject.responseText

                    . And this responseText IS THE ONLY VIEW that you can have from you AJAX request to the php : php variables are NOT visible / accessible by the javascript. If all you want is to do your job then why do you worry. Or is it just curiosity? Send a message if there's anything else I can give a hand. I wish you good luck.

                    B 1 Reply Last reply
                    0
                    • I Ioannis_o5

                      I will disappoint you : You can't do that BUT you need not do that ! Think of the php page as a black box which can ONLY return a return string to the requesting javascript. That is : the javascript via the URL "thinks" that it requests a page from the server. The requested page (php) is executed and with the echo (or the print) statement it can send back text. This text received can be anything you like - anything the php programmer has designed. And this text is received in the

                      XMLHttpRequestObject.responseText

                      . And this responseText IS THE ONLY VIEW that you can have from you AJAX request to the php : php variables are NOT visible / accessible by the javascript. If all you want is to do your job then why do you worry. Or is it just curiosity? Send a message if there's anything else I can give a hand. I wish you good luck.

                      B Offline
                      B Offline
                      Bryant May
                      wrote on last edited by
                      #13

                      Im doing this as a project for university. This is part of a log in script for a content management system...the whole validation of an email and sending back a variable etc... As you can see Im learning Ajax and can do quite a bit with it already but im struggling to understand this bit of it. The part I dont get is that if my 'responseText' object contains my variable then why cant I get at it in any other way than outputting it to the screen. If I dont output it in my "innerText ='result';" statement then its still within result. In my mid there must be a way of accessing the contents of 'result'...Maybe not, I dont know. Anyway, thanks for your time and efforts on helping me out with this. I really appreciate it.

                      I 1 Reply Last reply
                      0
                      • B Bryant May

                        Im doing this as a project for university. This is part of a log in script for a content management system...the whole validation of an email and sending back a variable etc... As you can see Im learning Ajax and can do quite a bit with it already but im struggling to understand this bit of it. The part I dont get is that if my 'responseText' object contains my variable then why cant I get at it in any other way than outputting it to the screen. If I dont output it in my "innerText ='result';" statement then its still within result. In my mid there must be a way of accessing the contents of 'result'...Maybe not, I dont know. Anyway, thanks for your time and efforts on helping me out with this. I really appreciate it.

                        I Offline
                        I Offline
                        Ioannis_o5
                        wrote on last edited by
                        #14

                        Hello I am back again (I went to bed that's why I didn't answer this - you see I am in time zone GMT +2 ). NOW I SEE WHAT YOUR PROBLEM IS : The value you receive in responseText you DON'T HAVE TO DISPLAY IT ! For instance you can 'say' :

                        var result = XMLHttpRequestObject.responseText;
                        if (result==1)
                        document.getElementById(div).style.visibility='hidden';
                        else
                        // do something else

                        A last comment regarding your project : Things that can/must be done AT SERVER put them in the php script, while those that need the user's update and response hndle them with Java after returning from AJAX. My wishes for success. I ll check my mail again in about 6 hours. If there anything else, send a message. Cheers

                        B 1 Reply Last reply
                        0
                        • I Ioannis_o5

                          Hello I am back again (I went to bed that's why I didn't answer this - you see I am in time zone GMT +2 ). NOW I SEE WHAT YOUR PROBLEM IS : The value you receive in responseText you DON'T HAVE TO DISPLAY IT ! For instance you can 'say' :

                          var result = XMLHttpRequestObject.responseText;
                          if (result==1)
                          document.getElementById(div).style.visibility='hidden';
                          else
                          // do something else

                          A last comment regarding your project : Things that can/must be done AT SERVER put them in the php script, while those that need the user's update and response hndle them with Java after returning from AJAX. My wishes for success. I ll check my mail again in about 6 hours. If there anything else, send a message. Cheers

                          B Offline
                          B Offline
                          Bryant May
                          wrote on last edited by
                          #15

                          The way Ive kind of got this working is to do this:

                          var result = XMLHttpRequestObject.responseText;

                          targetDiv.innerHTML = result; //Output any error messages printed in the php script

                          if (targetDiv.innerHTML == "") // If there arent any error messages then do this code
                          {
                          // Some code
                          }

                          Its not exactly what I want because it doesnt allow for switching based on true variables that arent errors (I cant think of an example there but Im sure you get what I mean). So I've done as you say, I've carried out all the things that the php script has to do IN the php script (outputting any errors, sql statements etc...) and used the javascript function to do everything else. Its quite untidy code-wise but it does the trick I suppose. Thank you for all your help. It has helped massively. Good luck with your VB project :) Bryant

                          1 Reply Last reply
                          0
                          Reply
                          • Reply as topic
                          Log in to reply
                          • Oldest to Newest
                          • Newest to Oldest
                          • Most Votes


                          • Login

                          • Don't have an account? Register

                          • Login or register to search.
                          • First post
                            Last post
                          0
                          • Categories
                          • Recent
                          • Tags
                          • Popular
                          • World
                          • Users
                          • Groups