SitePoint Sponsor

User Tag List

Results 1 to 11 of 11
  1. #1
    SitePoint Guru etidd's Avatar
    Join Date
    May 2011
    Location
    atlanta, ga
    Posts
    632
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)

    Question Receiving Multiple Parameters into PHP from jQuery Ajax Call

    Hello everyone,

    I have a question as to how to assign values to PHP variables after they are passed from the jQuery Ajax call, particularly through the data: specification. This is what the .ajax() call looks like:

    Code:
    $("#submissionform form").submit(function(e){
    			var origEmail = $('#go').val();
    			var confirmEmail = $("#confirmemail").val();
    			var name = $("#name").val();
    			var age = $("#age").val();
    			var country = $("#country").val();
    		
    			$.ajax({
    			  type: "POST",
    			  dataType: 'json',
    			  cache: false,
    			  url: "Scripts/confirmform.php",
    			  data: { origEmail: origEmail,
    			        confirmEmail: confirmEmail,
    					name: name,
    					age: age,
    					country: country },
    			  success: function(data){
    				  testSecondResults(data);
    			  }
    			});
    		});
          });
    I want to be able to receive those parameters into the PHP script for all the values into the following PHP script (filename: confirmform.php).

    PHP Code:
    <?php
        $instance 
    = new CheckForm;
        
    $instance -> checkSubmission();
        
        class 
    CheckForm
        
    {
            public function 
    checkSubmission()
            {    
                
    $response = array("validation" => " ""message" => " ");    
                if (
    $_POST['country'] != "Select Country")
                {
                    if (isset(
    $_POST['confirmemail']) && isset($_POST['name']))
                    {
                        
    $origEmail $_GET['go'];
                        
    $confirmEmail $_POST['confirmemail'];
                        if (
    $origEmail == $confirmEmail)
                        {
                            
    $name htmlspecialchars($_POST['name']);
                            
    $ageRange $_POST['age'];
                            
    $country $_POST['country'];
                            
                            require_once(
    'databasewriter.php');
                            
    $dbWriter = new DatabaseWriter;
                            
    $dbWriter -> writeUserToDatabase($confirmEmail$name$ageRange$country$category);
                            
    $response = array("validation" => "pass""message" => 'Thanks for joining the e-mail list, ' $name ', under the e-mail address, ' $confirmEmail '.');
                        } else {
                            
    $response = array("validation" => "fail""message" => 'E-mail addresses don\'t match.');
                            die();
                        }
                    } else {
                        if (!isset(
    $_POST['confirmemail'])){
                            
    $response = array("validation" => "fail""message" => 'Confirmation e-mail not entered.');
                        } elseif (!isset(
    $_POST['name'])) {    
                            
    $response = array("validation" => "fail""message" => 'Please enter a name.');
                        }
                    }
                } else {
                    
    $response = array("validation" => "fail""message" => 'Please select a country.');
                }
                echo 
    json_encode($response);
            }
        }
    ?>
    Maybe the solution is to use the "this" keyword or I don't know if a constructor is the right way.

    For other info, this will process a second confirmation form that is activated after another form has received a valid e-mail address submission. I want to pass that value along to compare it with the "confirmation" e-mail address, but I don't have access to that data anymore as I am seeing the following error that relates to the first form data that I am trying to use the $_GET server variable to receive into this form- it doesn't like me trying to fetch the first form data again with $_GET.

    Notice: Undefined index: go in C:\xampp\htdocs\Scripts\confirmform.php on line 14

  2. #2
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,198
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    In your PHP you have confirmemail but your Ajax call has confirmEmail, the index aka the name you put before the : has to match whatever you have defined in your backend code otherwise it will post exactly how you spelled it. Also I noticed you have the following line in your code:

    PHP Code:
    $origEmail $_GET['go']; 
    When your Ajax request goes through this will be undefined so I would recommend you put in some error checking for that.

  3. #3
    SitePoint Guru etidd's Avatar
    Join Date
    May 2011
    Location
    atlanta, ga
    Posts
    632
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Hi, Chris, and thanks for your reply.

    So, I have just learned that the name of the parameter is how the PHP code must fetch the passed value; therefore, if it is set to confirmEmail, then I must call it as $_POST['confirmEmail']; in my PHP file.

    Here's what it looks like now:
    PHP Code:
    <?php
        $instance 
    = new CheckForm;
        
    $instance -> checkSubmission();
        
        class 
    CheckForm
        
    {
            public function 
    checkSubmission()
            {    
                
    $response = array("validation" => " ""message" => " ");    
                if (
    $_POST['country'] != "Select Country")
                {
                    if (isset(
    $_POST['confirmEmail']) && isset($_POST['name']))
                    {
                        
    $origEmail $_POST['origEmail'];
                        
    $confirmEmail $_POST['confirmEmail'];
                        if (
    $origEmail == $confirmEmail)
                        {
                            
    $name htmlspecialchars($_POST['name']);
                            
    $ageRange $_POST['age'];
                            
    $country $_POST['country'];
                            
                            require_once(
    "categoryfinder.php");
                            
    $categoryFinder = new CategoryFinder;
                            
    $category $categoryFinder -> getCategory();
                            
                            require_once(
    'databasewriter.php');
                            
    $dbWriter = new DatabaseWriter;
                            
    $dbWriter -> writeUserToDatabase($confirmEmail$name$ageRange$country$category);
                            
    $response = array("validation" => "pass""message" => 'Thanks for joining the e-mail list, ' $name ', under the e-mail address, ' $confirmEmail '.');
                        } else {
                            
    $response = array("validation" => "fail""message" => 'E-mail addresses don\'t match.');
                            die();
                        }
                    } else {
                        if (!isset(
    $_POST['confirmemail'])){
                            
    $response = array("validation" => "fail""message" => 'Confirmation e-mail not entered.');
                        } elseif (!isset(
    $_POST['name'])) {    
                            
    $response = array("validation" => "fail""message" => 'Please enter a name.');
                        }
                    }
                } else {
                    
    $response = array("validation" => "fail""message" => 'Please select a country.');
                }
                echo 
    json_encode($response);
            }
        }
    ?>
    It's still saying undefined variable for the declaration of $origEmail and $confirmEmail, so I guess there may be something wrong with the .ajax() call.

    jQuery / JS
    Code:
    		$("#submissionform form").submit(function(e){
    			var origEmail = $('#go').val();
    			var confirmEmail = $("#confirmemail").val();
    			var name = $("#name").val();
    			var age = $("#age").val();
    			var country = $("#country").val();
    		
    			$.ajax({
    			  type: "POST",
    			  dataType: 'json',
    			  cache: false,
    			  url: "Scripts/confirmform.php",
    			  data: { origEmail: origEmail,
    			        confirmEmail: confirmEmail,
    					name: name,
    					age: age,
    					country: country },
    			  success: function(data){
    				  testSecondResults(data);
    			  }
    			});
    		});
          });

  4. #4
    SitePoint Guru etidd's Avatar
    Join Date
    May 2011
    Location
    atlanta, ga
    Posts
    632
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Okay, I just got that resolved by just changing the target in the JS/jQuery to
    Code:
    $("#submissionform").submit(function(e){
    Now, when I submit the form, the browser re-directs to a blank page that says

    {"validation":" ","message":" "}

  5. #5
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,198
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    You're not preventing the default action of the form when the submit event is been executed, see the below which should fix the issue.

    Code:
    $("#submissionform form").submit(function(e) {
        e.preventDefault();
        
        // Your Ajax code here...
    });

  6. #6
    SitePoint Guru etidd's Avatar
    Join Date
    May 2011
    Location
    atlanta, ga
    Posts
    632
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)

    Question Okay, here are the Console Errors.

    Yes, that does make the page just sit there now when the form is submitted.

    These are the error/warning messages I see in Firebug:

    Warning: preg_match(): Unknown modifier 'c' in C:\xampp\htdocs\Scripts\categoryfinder.php on line 7

    Warning: preg_match(): Unknown modifier 'c' in C:\xampp\htdocs\Scripts\categoryfinder.php on line 9

    Warning: preg_match(): Unknown modifier 'c' in C:\xampp\htdocs\Scripts\categoryfinder.php on line 11

    Warning: preg_match(): Unknown modifier 'c' in C:\xampp\htdocs\Scripts\categoryfinder.php on line 13

    Warning: preg_match(): Unknown modifier 'c' in C:\xampp\htdocs\Scripts\categoryfinder.php on line 15

    Warning: preg_match(): Unknown modifier 'c' in C:\xampp\htdocs\Scripts\categoryfinder.php on line 17

    Warning: preg_match(): Unknown modifier 'c' in C:\xampp\htdocs\Scripts\categoryfinder.php on line 19

    Warning: preg_match(): Unknown modifier 'c' in C:\xampp\htdocs\Scripts\categoryfinder.php on line 21

    Warning: preg_match(): Unknown modifier 'c' in C:\xampp\htdocs\Scripts\categoryfinder.php on line 23

    Warning: PDO::__construct(): php_network_getaddresses: getaddrinfo failed: This is usually a temporary error during hostname resolution and means that the local server did not receive a response from an authoritative server. in C:\xampp\htdocs\Scripts\databasewriter.php on line 7

    Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: This is usually a temporary error during hostname resolution and means that the local server did not receive a response from an authoritative server. ' in C:\xampp\htdocs\Scripts\databasewriter.php:7 Stack trace: #0 C:\xampp\htdocs\Scripts\databasewriter.php(7): PDO->__construct('mysql:host=worl...', 'worldreviewgrou...', 'PASSWORD') #1 C:\xampp\htdocs\Scripts\confirmform.php(28): DatabaseWriter->writeUserToDatabase('etidd88@ymail.c...', 'Tyler', '18???35', 'United States', NULL) #2 C:\xampp\htdocs\Scripts\confirmform.php(3): CheckForm->checkSubmission() #3 {main} thrown in C:\xampp\htdocs\Scripts\databasewriter.php on line 7

    Error: Permission denied to access property 'toString' jQuery.js (line 524)
    I am either not passing data back properly in the PHP script or not testing it in JS/jQuery when I receive the data back.

  7. #7
    SitePoint Guru etidd's Avatar
    Join Date
    May 2011
    Location
    atlanta, ga
    Posts
    632
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)

    Question My categoryfinder.php file

    Since many of those errors are from categoryfinder.php, here is that file

    PHP Code:
    <?php
        
    class CategoryFinder
        
    {
            public function 
    getCategory()
            {
                
    $currentURL$_SERVER['PHP_SELF'];
                if (
    preg_match($currentURL"index"))
                    return 
    "Home Page";
                elseif (
    preg_match($currentURL"health"))
                    return 
    "Health";
                elseif (
    preg_match($currentURL"insurance"))
                    return 
    "Insurance";
                elseif (
    preg_match($currentURL"general"))
                    return 
    "General";
                elseif (
    preg_match($currentURL"dating"))
                    return 
    "Dating";
                elseif (
    preg_match($currentURL"education"))
                    return 
    "Education";
                elseif (
    preg_match($currentURL"legal"))
                    return 
    "Legal";
                elseif (
    preg_match($currentURL"startyour"))
                    return 
    "Business Opportunities";
                elseif (
    preg_match($currentURL"business"))
                    return 
    "Business Services";
            }
        }
    ?>

  8. #8
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,198
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    Your preg_match statements are malformed meaning you have incorrectly written them, when using the preg_match() function you always need two forward slashes wrapped within a string which starts the regular expression and you then need the value to match the expression against. E.g.

    PHP Code:
    if (preg_match('/Chris/i''chris')) {
        
    // Will return true because "Chris" is matched, the "i" modifier allows for upper and lowecase characters

    See the below which is how I would write your above if statement.

    PHP Code:
    class CategoryFinder
    {
        public function 
    getCategory()
        {
            
    // Get the current page URL
            
    $currentURL $_SERVER['PHP_SELF'];

            
    // Build the regular expression and the match to array
            
    $matchTo = array(
                
    'index'     => 'Home Page',
                
    'health'    => 'Health',
                
    'insurance' => 'Insurance',
                
    'general'   => 'General',
                
    'dating'    => 'Dating',
                
    'education' => 'Education',
                
    'legal'     => 'Legal',
                
    'startyour' => 'Business Opportunities',
                
    'business'  => 'Business Services'
            
    );

            
    $regExp  '/' join('|'array_keys($matchTo)) . '/i';

            
    // Attempt to match something from the URL
            
    if (preg_match($regExp$currentURL$matches)) {
                return 
    $matchTo[$matches[0]];
            }

            return 
    '';
        }

    As for the other errors you may want to check out the following links.

    http://stackoverflow.com/questions/5...nection-string
    https://www.google.com.au/search?q=W...hrome&ie=UTF-8

  9. #9
    SitePoint Guru etidd's Avatar
    Join Date
    May 2011
    Location
    atlanta, ga
    Posts
    632
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Yeah, that really helps!

    The page is just sitting there right now when I try to submit the form. That may be a JS issue, so I posted my code over in that section.

    Should I do a try-catch or some type of test to detect if database writing failed and if the mail() function failed (when I add that in)?

  10. #10
    SitePoint Guru etidd's Avatar
    Join Date
    May 2011
    Location
    atlanta, ga
    Posts
    632
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)

    Unhappy

    Well, I inserted an alert(data); right in the ajax call to see if there was anything to see, but I don't think that the PHP script is returning anything useful back to the jQuery because I didn't see an alert pop up after I submitted the form.

    Code:
    			  data: { origEmail: origEmail,
    			        confirmEmail: confirmEmail,
    					name: name,
    					age: age,
    					country: country },
    			  success: function(data){
    				  console.log(data);
    				  alert(data);
    				  testSecondResults(data);
    			  }
    The PHP files thus far:
    confirmform.php
    PHP Code:
    <?php
        $instance 
    = new CheckForm;
        
    $instance -> checkSubmission();
        
        class 
    CheckForm
        
    {
            public function 
    checkSubmission()
            {    
                
    $response = array("validation" => " ""message" => " ");    
                if (
    $_POST['country'] != "Select Country")
                {
                    if (isset(
    $_POST['confirmEmail']) && isset($_POST['name']))
                    {
                        
    $origEmail $_POST['origEmail'];
                        
    $confirmEmail $_POST['confirmEmail'];
                        if (
    $origEmail == $confirmEmail)
                        {
                            
    $name htmlspecialchars($_POST['name']);
                            
    $ageRange $_POST['age'];
                            
    $country $_POST['country'];
                            
                            require_once(
    "categoryfinder.php");
                            
    $categoryFinder = new CategoryFinder;
                            
    $category $categoryFinder -> getCategory();
                            
                            require_once(
    'databasewriter.php');
                            
    $dbWriter = new DatabaseWriter;
                            
    $dbWriter -> writeUserToDatabase($confirmEmail$name$ageRange$country$category);
                            
    $response = array("validation" => "pass""message" => 'Thanks for joining the e-mail list, ' $name ', under the e-mail address, ' $confirmEmail '.');
                        } else {
                            
    $response = array("validation" => "fail""message" => 'E-mail addresses don\'t match.');
                            die();
                        }
                    } else {
                        if (!isset(
    $_POST['confirmemail'])){
                            
    $response = array("validation" => "fail""message" => 'Confirmation e-mail not entered.');
                        } elseif (!isset(
    $_POST['name'])) {    
                            
    $response = array("validation" => "fail""message" => 'Please enter a name.');
                        }
                    }
                } else {
                    
    $response = array("validation" => "fail""message" => 'Please select a country.');
                }
                echo 
    json_encode($response);
            }
        }
    ?>
    categoryfinder.php
    PHP Code:
    <?php
        
    class CategoryFinder
        
    {
            public function 
    getCategory()
            {
                
    // Get the current page URL
                
    $currentURL $_SERVER['PHP_SELF'];
        
                
    // Build the regular expression and the match to array
                
    $matchTo = array(
                    
    'index'     => 'Home Page',
                    
    'health'    => 'Health',
                    
    'insurance' => 'Insurance',
                    
    'general'   => 'General',
                    
    'dating'    => 'Dating',
                    
    'education' => 'Education',
                    
    'legal'     => 'Legal',
                    
    'startyour' => 'Business Opportunities',
                    
    'business'  => 'Business Services'
                
    );
        
                
    $regExp  '/' join('|'array_keys($matchTo)) . '/i';
        
                
    // Attempt to match something from the URL
                
    if (preg_match($regExp$currentURL$matches)) {
                    return 
    $matchTo[$matches[0]];
                }
        
                return 
    '';
            }
        }  
    ?>

  11. #11
    SitePoint Guru etidd's Avatar
    Join Date
    May 2011
    Location
    atlanta, ga
    Posts
    632
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)

    Exclamation Still Trying

    I fixed the fatal error by adding in the following changes:

    PHP Code:

    try{

                                require_once(
    'databasewriter.php');

                                
    $dbWriter = new DatabaseWriter;

                                
    $dbWriter -> writeUserToDatabase($confirmEmail$name$ageRange$country$category);

                            } catch (
    PDOException $e) {

                                
    $response = array("validation" => "pass""message" => "Thanks for joining the e-mail list, " $name ", under the e-mail address, " $confirmEmail ".""database" => "fail");

                            } 

    I still can't figure out the second one
    , and the page just sits there on form submission.

    Warning: PDO::__construct(): php_network_getaddresses: getaddrinfo failed: This is usually a temporary error during hostname resolution and means that the local server did not receive a response from an authoritative server. in C:\xampp\htdocs\Scripts\databasewriter.php on line 7
    By the way, I've uploaded my PHP files online now.


Tags for this Thread

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
  •