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:


$("#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
	$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. :crazy:

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

1 Like

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:

$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.

1 Like

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
	$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


		$("#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);
			  }
			});
		});
      });

Okay, I just got that resolved by just changing the target in the JS/jQuery to


$("#submissionform").submit(function(e){

Now, when I submit the form, the browser re-directs to a blank page that says

{“validation”:" “,“message”:” "}

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.

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

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. :smashy:

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


<?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";
		}
	}
?>

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.

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.

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.


https://www.google.com.au/search?q=Warning%3A+PDO%3A%3A__construct()%3A+php_network_getaddresses%3A+getaddrinfo+failed&aq=f&oq=Warning%3A+PDO%3A%3A__construct()%3A+php_network_getaddresses%3A+getaddrinfo+failed&sourceid=chrome&ie=UTF-8

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)?

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.


			  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
	$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
	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 '';
		}
	}
?>

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



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.