• I have read quite a few advice on the subject in the forum but none of the methods worked for me.
    I have included an HTML form into a page template.

            <script type="text/javascript" src="https://code.jquery.com/jquery-3.5.0.js"></script>
            <script type="text/javascript">
              const url = "https://www.plasticatbay.org/ChartBal/populatebeach2.php";
              $.getJSON(url, function(data){
                $('#selector').empty();
                $('#selector').append('<option selected="true" disabled>Choose a beach</option>')
                $('#selector').prop('selectedIndex', 0);
                $.each(data, function(key,entry){
                  $('#selector').append($('<option>').text(entry.Beach).attr('value', entry.Id))});
                });
              </script>
            <script type="text/javascript">
            function validateForm(){
              /* Validating name field */
              var x=document.forms["myForm"]["name"].value;
              if (x==null || x=="") {
                alert("Name must be filled out");
                return false;
                }
              /* Validating email field */
              var x=document.forms["myForm"]["email"].value;
              var atpos=x.indexOf("@");
              var dotpos=x.lastIndexOf(".");
              if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length){
                alert("Not a valid e-mail address");
                return false;
                }
              var x=document.forms["myForm"]["date"].value;
              if (x==null || x=="") {
                alert("The date must be filled out");
                return false;
                }
              var x=document.forms["myForm"]["selector"].value;
              if (x==null || x=="") {
                alert("The beach must be selected");
                return false;
                }
              var x=document.forms["myForm"]["weight"].value;
              if (x==null || x=="") {
                alert("The weight must be provided");
                return false;
                }
            }
              </script>
          </head>
          <body>
          <form action="<?php echo admin_url( 'admin-post.php' ); ?>" method="post" name="myForm">
          <input type="hidden" name="action" value="pollution_data">
          Name:<br> <input id="name" type="text" name="name" /><p>
          Enter your email:<br> <input type = "email" id="email" name="email" /><p>
          Date of collection: <input type="date" id="date" name="date" class="datepicker" /><p>
          Choose a beach: <select id= "selector" name="Choose_beach"></select><br>
          If the beach is not listed please use the contact form<p>
          Weight collected in kg: <input id="weight" type="number" name="weight" /><p>
          Feedback: <br><textarea name="feedback" rows="10" cols="50" ></textarea><p>
          <input type="submit" value="Submit" /></form>
          </body>

    I have modified the function.php to export my POST data via admin_post but nothing seems to work. Here an exert of the function.

    /**
     * Manage form
     */
    add_action( 'admin_post_nopriv_pollution_data', 'add_pollution_data' );
    add_action( 'admin_post_pollution_data','add_pollution_data');
    function add_pollution_data(){	
    	$name=$email=$date=$beach=$weight=$unit=$feedback="";
    //get the form elements and store them in a variable
      
    	if (! is_page("contribute-to-marine-pollution-data-collection")||! isset( $_POST['name'] )) {
    		return;}
     	 $name=test_input($_POST["name"]);
     	 $email=test_input($_POST["email"]);
     	 $date=test_input($_POST["date"]);
     	 $beach=test_input($_POST["beach"]);
     	 $weight=test_input($_POST["weight"]);
     	 $feedback=test_input($_POST["feedback"]);
    	
    	function test_input($data) {
    	  $data = trim($data);
     	 $data = stripslashes($data);
     	 $data = htmlspecialchars($data);
    	  return $data;
    	}
    //database
    	define('DB_HOST', 'host');
    	define('DB_USERNAME', 'user');
    	define('DB_PASSWORD', 'pwd');
    	define('DB_NAME', 'DB');
    //get connection
    	$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
    	if(!$mysqli){
     	 die("Connection failed: " . $mysqli->error);
     	 }
    //insert data
    	$query1 ="INSERT INTO <code>TAB1</code> (a,b,c,d) VALUES ($beach, $date,$weight,$email)";
    	$result1 = $mysqli->query($query1);
    //free memory associated with result
    $result1->close();
    //close connection
    $mysqli->close();
    // Sanitize E-mail Address
    	$email =filter_var($email, FILTER_SANITIZE_EMAIL);
    // Validate E-mail Address
    	$email= filter_var($email, FILTER_VALIDATE_EMAIL);
    	if (!$email){
     	 echo "Invalid Sender's Email";
     	 }
    	$subject ="Data Submission";
    	$headers ='From: /*valid email*/';
    	$message = wordwrap("name:\t$name\nemail:\t$email\ndate:\t$date\nbeach:\t$beach\nWeigth:\t$weight $unit\nmsg:\n",70);
    	wp_mail("/*valid email*/",$subject,$message,$headers);
    	echo "Thanks for the submission!";
    	//Redirects to the success page
    	header("Location: https://www.plasticatbay.org/contribute-to-marine-pollution-data-collection");
    }

    I don’t think the function is read and I don’t really find a way of debugging this. Any help is welcome.

    • This topic was modified 4 years, 6 months ago by bcworkz. Reason: email redacted from code

    The page I need help with: [log in to see the link]

Viewing 4 replies - 1 through 4 (of 4 total)
  • Moderator bcworkz

    (@bcworkz)

    Is your DB table within the WP DB? If so, you should use the DB connection opened by the global $wpdb object instead of opening your own. DB connections are precious, don’t make more than necessary.

    Requests to admin-post.php are handled as new page requests. Your handler function can output normal HTML, which can include debugging information. Another useful debugging option when output isn’t useful is to send information to the error log with error_log().

    Error logging a confirmation message will tell you if your callback was successfully called or not. If it is called, you’ve won half the battle. The next likely problem is correctly connecting to the DB. If you use the global $wpdb object to write to the DB, a proper connection is very likely. Your own connection, not so much ??

    Thread Starter Boorhin

    (@moreaujuli1)

    I have switched to wpdp
    I have not suceeded in logging errors except the ones of functions.php but these are popping at save-
    I am clearly outside my comfort zone there. I think I don’t call the function properly and it just freezes in the wp-admin.

    Moderator bcworkz

    (@bcworkz)

    Exceeding ones comfort zone is how we develop new skills, it’s OK. I don’t see any reason that add_pollution_data() would not be called when the form is submitted. That aspect appears correct. Use your browser’s network developer tool to verify the admin-post.php request is made correctly with appropriate parameter data.

    Since admin-post.php requests constitute a new page, you don’t really need to error_log() debug data. You can echo out or var_dump() debug data as usual. Ensure WP_DEBUG is defined as true in wp-config.php so you will see any errors that occur in your add_pollution_data() function or other code.

    You could confirm the function is at least called on form submit by adding
    echo 'Function add_pollution_data() was called!';
    as the very first line within the function declaration.

    Thread Starter Boorhin

    (@moreaujuli1)

    Thanks,
    Activating the debugging information was really the most helpful.
    the reason why the function was not launched was in the declaration

    add_action( 'admin_post_nopriv_pollution_data', 'add_pollution_data' );
    add_action( 'admin_post_pollution_data','add_pollution_data');

    It should have been

    add_action( 'admin_post_nopriv_add_pollution_data', 'add_pollution_data' );
    add_action( 'admin_post_add_pollution_data','add_pollution_data');

    Once I was in the function I could start debugging and getting it to work.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘html form POST_ not populating DB/ email’ is closed to new replies.