How to use ajax to post wordpress comments? - php

i am building a wordpress theme and in that i have a custom contact form which stores data in a custom post type Messages when a user fills that form and submit it.
here is the code below
Contact-form.php
<form id="salmanlateefContactForm" class="salmanlateef-contact-form" action="#" method="post" data-url="<?php echo admin_url('admin-ajax.php'); ?>">
<div class="form-group">
<input type="text" class="form-control salmanlateef-form-control" placeholder="Your Name" id="name" name="name" required="required">
<small class="text-danger form-control-msg">Your Name Is Required</small>
</div>
<div class="form-group">
<input type="email" class="form-control salmanlateef-form-control" placeholder="Your Email" id="email" name="email" required="required">
<small class="text-danger form-control-msg">Your Email Is Required</small>
</div>
<div class="form-group">
<textarea name="message" id="message" class="form-control salmanlateef-form-control" required="required" placeholder="Your Message"></textarea>
<small class="text-danger form-control-msg">A Message Is Required</small>
</div>
<div class="text-center">
<button type="submit" class="btn btn-default btn-lg btn-salmanlateef-form">Submit</button>
<small class="text-info form-control-msg js-form-submission">Submission in process, please wait...</small>
<small class="text-success form-control-msg js-form-success">Message successfully submitted, thank you!</small>
<small class="text-danger form-control-msg js-form-error">There was an error while submitting the message, please try again</small>
</div>
JQuery
/* contact form submission */
$('#salmanlateefContactForm').on('submit', function(e){
e.preventDefault();
$('.has-error').removeClass('has-error');
$('.js-show-feedback').removeClass('js-show-feedback');
var form = $(this),
name = form.find('#name').val(),
email = form.find('#email').val(),
message = form.find('#message').val(),
ajaxurl = form.data('url');
if( name === '' ){
$('#name').parent('.form-group').addClass('has-error');
return;
}
if( email === '' ){
$('#email').parent('.form-group').addClass('has-error');
return;
}
if( message === '' ){
$('#message').parent('.form-group').addClass('has-error');
return;
}
form.find('input, button, textarea').attr('disabled', 'disabled');
$('.js-form-submission').addClass('js-show-feedback');
$.ajax({
url : ajaxurl,
type : 'post',
data : {
name : name,
email : email,
message : message,
action: 'salmanlateef_save_user_contact_form'
},
error : function( response ){
$('.js-form-submission').removeClass('js-show-feedback');
$('.js-form-error').addClass('js-show-feedback');
form.find('input, button, textarea').removeAttr('disabled');
},
success : function( response ){
if( response == 0 ){
setTimeout(function() {
$('.js-form-submission').removeClass('js-show-feedback');
$('.js-form-error').addClass('js-show-feedback');
form.find('input, button, textarea').removeAttr('disabled');
},1500);
} else {
setTimeout(function() {
$('.js-form-submission').removeClass('js-show-feedback');
$('.js-form-success').addClass('js-show-feedback');
form.find('input, button, textarea').removeAttr('disabled').val('');
},1500);
}
}
});
});
Ajax.php
add_action( 'wp_ajax_nopriv_salmanlateef_save_user_contact_form', 'salmanlateef_save_contact' );
add_action( 'wp_ajax_salmanlateef_save_user_contact_form', 'salmanlateef_save_contact' );
function salmanlateef_save_contact(){
$title = wp_strip_all_tags($_POST["name"]);
$email = wp_strip_all_tags($_POST["email"]);
$message = wp_strip_all_tags($_POST["message"]);
$args = array(
'post_title' => $title,
'post_content' => $message,
'post_author' => 1,
'post_status' => 'publish',
'post_type' => 'salmanlateef_contact',
'meta_input' => array(
'_contact_email_value_key' => $email
)
);
$postID = wp_insert_post( $args );
if ($postID !== 0) {
$to = get_bloginfo( 'admin_email' );
$subject = 'Salman Lateef Contact Form - '.$title;
$header[] = 'From: '.get_bloginfo( 'name' ).' <'.$to.'>';
$header[] = 'Reply-To: '.$title.' <'.$email.'>';
$header[] = 'Content-Type: text/html: charset=UTF-8';
wp_mail( $to, $subject, $message, $headers );
echo $postID;
} else {
echo 0;
}
die();
}
What i want is use the same logic to post comments to a post using comments form. Hope i am clear on the question. Looking forward for a reply. Thanks in advance

Since Version 2.8, The JavaScript global variable ajaxurl can be used in case you want to separate your JavaScript code from php files into JavaScript only files. This is true on the administration side only. If you are using AJAX on the front-end, you need to make your JavaScript aware of the admin-ajax.php url.
So please use admin-ajax rather than the ajaxurl in your theme.

$args = array(
'comment_author' => $author,
'comment_author_email' => $email,
'comment_content' => $comment,
'comment_parent' => $commentParent,
'comment_post_ID' => $postID,
'user_id' => $userID,
);
$commentID = wp_new_comment( $args );
if ($commentID !== 0) {
echo $commentID;
} else {
echo 0;
}
i used the wp_new_comment() function and it served my purpose. however i am still trying to figure out a way to append the newly generated comment into the comments list in the single.php

Related

How to send information to database without reloading the page

I've been trying to send information to the database using AJAX but nothing is working, each time i click the submit button, nothing works, the pages stays static somewhat. All JS files are referenced properly so i'm not sure what i'm doing wrong.
Here's what i've done so far;
Controller:
public function contact_us_ajax() {
//form validation rules and file upload config
$this->form_validation->set_rules('name', 'Name', 'trim|required');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
$this->form_validation->set_rules('subject', 'Subject', 'trim|required');
$this->form_validation->set_rules('message', 'Message', 'trim|required');
$this->form_validation->set_rules('captcha_code', 'Captcha Code', 'trim');
$this->form_validation->set_rules('c_captcha_code', 'Captcha Code', 'trim|required|matches[captcha_code]',
array(
'required' => 'Captcha is required. Reload the page if you cannot see any code.',
'matches' => 'Invalid captcha code'
)
);
if ($this->form_validation->run()) {
$this->message_model->contact_us(); //insert the data into database
$res = ['status' => true, 'msg' => 'Message sent successfully!'];
echo json_encode($res);
} else {
$res = ['status' => false, 'msg' => validation_errors()];
echo json_encode($res);
}
}
Model:
public function contact_us() {
$name = ucwords($this->input->post('name', TRUE));
$email = $this->input->post('email', TRUE);
$subject = ucwords($this->input->post('subject', TRUE));
$message = ucfirst($this->input->post('message', TRUE));
$message = nl2br($message);
$data = array (
'name' => $name,
'email' => $email,
'subject' => $subject,
'message' => $message,
);
$this->db->insert('contact_messages', $data);
//email admins
//$this->notify_admins($name, $email, $subject, $message);
}
View:
<?php
$form_attributes = array("id" => "contact_us_form");
echo form_open('home/contact_us_ajax', $form_attributes); ?>
<!-- Contact Form -->
<div class="col-md-5">
<h4>Send Us a Message</h4>
<div class="form-group">
<label>Name:</label><input type="text" name="name" class="form-control input-field" required>
<label>Email:</label><input type="email" name="email" class="form-control input-field" required>
<label>Subject:</label><input type="text" name="subject" class="form-control input-field" required>
</div>
<label>Message:</label>
<textarea name="message" class="textarea-field form-control" rows="4" required></textarea>
<div class="col-md-6">
<input type="text" name="captcha_code" id="captcha_code" value="<?php echo $captcha_code; ?>" class="form-control" readonly />
</div>
<div class="col-md-6">
<input type="text" name="c_captcha_code" value="<?php echo set_value('c_captcha_code'); ?>" class="form-control" placeholder="Enter captcha code here*" required />
</div>
<div id="status_msg"></div>
<?php echo flash_message_success('status_msg'); ?>
<?php echo flash_message_danger('status_msg_error'); ?>
<button class="btn center-block">Send message</button>
</div>
<?php echo form_close(); ?>
AJAX:
//Contact Us
$('#contact_us_form').submit(function(e) {
e.preventDefault();
var form_data = $(this).serialize();
$.ajax({
url: base_url + 'home/contact_us_ajax',
type: 'POST',
data: form_data,
dataType: 'json',
success: function(res) {
if (res.status) {
$( '#status_msg' ).html('<div class="alert alert-success text-center" style="color: #000">'+res.msg+'</div>').fadeIn('fast');
$('#contact_us_form')[0].reset(); //reset form fields
$('#captcha_code').val(''); //clear captcha field
setTimeout(function() {
location.reload();
}, 5000);
} else {
$( '#status_msg' ).html('<div class="alert alert-danger text-center" style="color: #000">' + res.msg + '</div>').fadeIn('fast').delay( 30000 ).fadeOut( 'slow' );
}
}
});
});
base_url is defined in codeigniter's config.php, for example like:
$config['base_url'] = 'http://or.org/';
BUT! This doesn't mean you can simply name a variable in javascript base_url and hope to get any value.
To use it in your ajax call, you need to echo the php constant out like:
url: '<?php echo base_url()?>' + 'home/contact_us_ajax'
I normally just use the relative path
url: '/home/contact_us_ajax'
which works fine as well, if you use a "regular" CI configuration

Getting null response to Recaptcha V3 with ajax

I'm having a problem with getting a problem when submitting captcha v3 to ajax. I get a null response to Google. I have tried multiple tutorials but I think it does not fix to ajax request.
I think the problem is with google or my php, or ajax request. I understand my codes but I am not familiar with using google's code like this captcha v3. I have use captcha v2 before. And now I am trying v3 I can't run it with my code.
Here is my Ajax and HTML code :
// when form is submit
$('.contact-form').submit(function (event) {
// we stoped it
event.preventDefault();
var url = $(this).prop('action');
var contact_data = $(this).serialize();
$('.btn-contact').html('<em class="fas fa-spinner fa-pulse"></em> Sending...');
$('.alert').fadeOut('slow');
// needs for recaptacha ready
grecaptcha.ready(function () {
// do request for recaptcha token
// response is promise with passed token
grecaptcha.execute('6Ldjp6Q[--my site key---]8H5bxI1', { action: 'create_contact' }).then(function (token) {
// add token to form
$('.contact-form').prepend('<input type="hidden" name="g-recaptcha-response" value="' + token + '">');
var contact = function () {
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
data: contact_data, token: token ,
success: function (response) {
$('.message').html(response.message);
$('.btn-contact').html('<em class="fas fa-paper-plane"></em> Send');
if (response.error) {
$('.status').removeClass('alert-success').addClass('alert-danger').show();
}
else {
$('.status').removeClass('alert-danger').addClass('alert-success').show();
$('.contact-form')[0].reset();
}
}
});
};
setTimeout(contact, 3000);
});;
});
});
<?=form_open('Contact/Send_Contact', array('class' => 'contact-form'))?>
<div class="row top-2">
<div class="col-md-12">
<div class="status alert text-center" style="display:none;">
<button type="button" class="close clearMsg"><span aria-hidden="true">×</span></button>
<span class="message"></span>
</div>
</div>
<div class="form-group col-md-6">
<input type="text" placeholder="Your Name" name="name" class="form-control name">
<div class="invalid-feedback invalid-name"></div>
</div>
<div class="form-group col-md-6">
<input type="email" placeholder="Your Email" name="email" class="form-control email">
<div class="invalid-feedback invalid-email"></div>
</div>
<div class="form-group col-md-12">
<input type="text" placeholder="Subject" name="subject" class="form-control subject">
<div class="invalid-feedback invalid-subject"></div>
</div>
<div class="form-group col-md-12">
<textarea placeholder="Message" class="form-control message_text" name="message" rows="4"></textarea>
<div class="invalid-feedback invalid-message"></div>
</div>
<div class="col-md-12">
<button type="submit" class="btn btn-info btn-contact float-right"><em class="fas fa-paper-plane"></em> Send</button>
</div>
</div>
</from>
<script src="https://www.google.com/recaptcha/api.js?render=6Ldj[--My site key--]5bxI1"></script>
And I also copied some PHP code and I don't know where is the problem here because this is my first time using CodeIgniter and I also haven't used captcha v3 too.
Please review my PHP code here :
public function Send_Contact() {
$output['error'] = true;
$output['message'] = 'Please fill up the error field(s).';
$name = $this->input->post('name');
$email = $this->input->post('email');
$subject = $this->input->post('subject');
$message = $this->input->post('message');
$captcha = $this->input->post('token');
$this->form_validation->set_rules('name', 'Name', 'required');
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('subject', 'Subject', 'required');
$this->form_validation->set_rules('message', 'Message', 'required');
if($this->form_validation->run() === false) {
//some codes here I remove because it has nothing to do with the question.
die(json_encode($output));
}
if(!$captcha){
$output['message'] = "Invalid catpcha";
die(json_encode($output));
}
$secretKey = "6Ldjp[--My secret key--]YQL_";
$ip = $_SERVER['REMOTE_ADDR'];
// post request to server
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = array('secret' => $secretKey, 'response' => $captcha);
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
$responseKeys = json_decode($response,true);
if($responseKeys["success"]) {
if($this->contact_model->create_contact()) {
$output['error'] = false;
$output['message'] = 'Thank you for sending message! <em class="far fa-check-circle"></em>';
echo json_encode($output);
} else {
$output['error'] = true;
$output['message'] = 'Error in database model.';
echo json_encode($output);
}
} else {
$output['message'] = "Invalid catpcha";
die(json_encode($output));
}
}
I'm using codeigniter 3. and this public function is in the contact controller.

wordpress insert post doesnt work on edge

I create a code to save data from Form to custom_post_type.
Everything ok on Firefox but when I test it on edge, the post still save, but I can't edit the post on admin, or view the post(object not found) (see the image)
I really don't know where is the problem, please help.
this is my code, i copy it from my function.php:
function wpshout_frontend_post() {
wpshout_save_post_if_submitted();
?>
<div>
<div>
RESERVATION
</div>
<form id="new_post" class = 'datcho' name="new_post" method="post">
<input type = 'text' name = 'ten' required>
<input type = 'tel' name = 'sdt' required>
<input type = 'number' name = 'num' min='1' max = '10' required>
<input type = 'date' name = 'ngay' required>
<input type = 'time' name = 'time' value = '13:00' min='9:00' max='21:00' required>
<?php wp_nonce_field( 'wps-frontend-post' ); ?>
<input type="submit" value="Reservation" id="submit" name="submit"/>
</div>
</form>
</div>
<?php
}
function wpshout_save_post_if_submitted() {
// Stop running function if form wasn't submitted
if ( !isset($_POST['ten']) ) {
return;
}
// Check that the nonce was set and valid
if( !wp_verify_nonce($_POST['_wpnonce'], 'wps-frontend-post') ) {
echo 'Did not save because your form seemed to be invalid. Sorry';
return;
}
// Do some minor form validation to make sure there is content
// Add the content of the form to $post as an array
$title = wp_strip_all_tags($_POST['ten']);
$post = array(
'post_title' => $title,
'post_content' => $title,
'post_status' => 'Pending',
'post_type' => 'datcho'
);
$eror = wp_insert_post($post,true);
if($eror){
$sdt = wp_strip_all_tags($_POST['sdt']);
$ngay = wp_strip_all_tags($_POST['ngay']);
$time = wp_strip_all_tags($_POST['time']);
$num = wp_strip_all_tags($_POST['num']);
add_post_meta($eror, 'sdt', $sdt);
add_post_meta($eror, 'ngay', $ngay);
add_post_meta($eror, 'time', $time);
add_post_meta($eror, 'num', $num);
echo 'Saved your post successfully! :)';
}else {
echo "something wrong";
}
}
Here is the complete solution.
The issue mainly is you are not logged into the WP in Edge so when creating the post using wp_insert_post wordpress has no idea with which account should it attach that post.
function wpshout_frontend_post() {
wpshout_save_post_if_submitted();
?>
<div>
<div>
RESERVATION
</div>
<form id="new_post" class = 'datcho' name="new_post" method="post">
<input type = 'text' name = 'ten' required>
<input type = 'tel' name = 'sdt' required>
<input type = 'number' name = 'num' min='1' max = '10' required>
<input type = 'date' name = 'ngay' required>
<input type = 'time' name = 'time' value = '13:00' min='9:00' max='21:00' required>
<?php wp_nonce_field( 'wps-frontend-post' ); ?>
<input type="submit" value="Reservation" id="submit" name="submit"/>
</form>
</div>
<?php
}
function wpshout_save_post_if_submitted() {
// Stop running function if form wasn't submitted
if ( !isset($_POST['ten']) ) {
return;
}
// Check that the nonce was set and valid
if( !wp_verify_nonce($_POST['_wpnonce'], 'wps-frontend-post') ) {
echo 'Did not save because your form seemed to be invalid. Sorry';
return;
}
// Do some minor form validation to make sure there is content
// Add the content of the form to $post as an array
$title = wp_strip_all_tags($_POST['ten']);
$author_id = 1; // You can change it with your User ID
$post = array(
'post_title' => $title,
'post_content' => $title,
'post_status' => 'draft',
'post_type' => 'datcho'
'post_author' => $author_id
);
$eror = wp_insert_post($post,true);
if($eror){
$sdt = wp_strip_all_tags($_POST['sdt']);
$ngay = wp_strip_all_tags($_POST['ngay']);
$time = wp_strip_all_tags($_POST['time']);
$num = wp_strip_all_tags($_POST['num']);
add_post_meta($eror, 'sdt', $sdt);
add_post_meta($eror, 'ngay', $ngay);
add_post_meta($eror, 'time', $time);
add_post_meta($eror, 'num', $num);
echo 'Saved your post successfully! :)';
}else {
echo "something wrong";
}
}

PHP and AJAX form with reCaptcha v2 fails to run the PHP script

I'm currently making a personal website from scratch using a webserver running Apache and PHP 5.6. I made the framework, some pages, and some CSS. I'm currently having issues integrating Google's reCaptcha v2 to my contact form. I was able to integrate it into the form through the HTML and my AJAX script is working correctly, but I can't for the life of me figure out how to properly integrate the captcha check into my PHP script. I want to like PHP, and I'm going to have to use it more, but It's been extremely frustrating to try and get this working.
This form works perfectly without the catcha integration, but when I introduce the changes tot he PHP script, it fails to complete and form messages don't get sent. I've been tracking down the exact issue, but can't figure it out. I would love to use JS alert() to stub different parts of the script, but since it's PHP I can't do that :c I also used a few validators to make sure that the PHP's syntax was correct. There are no errors in my IDE.
Can anybody see any absurd issues with the following PHP form script?
PHP
<?php
// Only process POST reqeusts.
if ( $_SERVER[ "REQUEST_METHOD" ] == "POST" ) {
// Get the form fields and remove whitespace.
$firstname = strip_tags( trim( $_POST[ "firstname" ] ) );
$firstname = str_replace( array( "\r", "\n" ), array( " ", " " ), $firstname );
$lastname = strip_tags( trim( $_POST[ "lastname" ] ) );
$lastname = str_replace( array( "\r", "\n" ), array( " ", " " ), $lastname );
$email = filter_var( trim( $_POST[ "email" ] ), FILTER_SANITIZE_EMAIL );
$phone = filter_var( trim( $_POST[ "phone" ] ), FILTER_SANITIZE_NUMBER_INT );
$message = trim( $_POST[ "message" ] );
$validation = false;
function buildCaptchaUrl() {
$captcha = $_POST[ 'g-recaptcha-response' ];
$secret = 'SECRET';
return "https://www.google.com/recaptcha/api/siteverify?secret=$secret&response=" . $captcha . "&remoteip=" . $_SERVER[ 'REMOTE_ADDR' ];
}
function fileGetContentsCurl( $url ) {
$ch = curl_init();
curl_setopt( $ch, CURLOPT_AUTOREFERER, true );
curl_setopt( $ch, CURLOPT_HEADER, 0 );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
$data = curl_exec( $ch );
curl_close( $ch );
return $data;
}
function sendCaptchaResponse() {
$response = json_decode( file_get_contents_curl( buildCaptchaUrl() ), true );
if ( $response[ 'success' ] == false ) {
return false;
}
return true;
}
//The problematic chain of events is caused by this
$validation = sendCaptchaResponse();
if ( $validation == false ) {
//captcha failed
http_response_code( 403 );
echo "Please verify your humanity by using the captcha.";
exit;
} else if ( $validation == true ) {
//captcha passed
// Check that data was sent to the mailer.
if ( empty( $firstname )OR empty( $message )OR!filter_var( $email, FILTER_VALIDATE_EMAIL ) ) {
// Set a 400 (bad request) response code and exit.
http_response_code( 400 );
echo "Some form fields must have been empty. Please complete the form and submit again.";
exit;
}
// Set the recipient email address.
// FIXME: Update this to your desired email address.
$recipient = "chris#chillstice.com";
// Set the email subject.
$subject = "Form Submission by $firstname $lastname";
// Build the email content.
$email_content = "Name: $firstname $lastname\n";
$email_content .= "Email: $email\n";
$email_content .= "Phone: $phone\n\n";
$email_content .= "Message:\n$message\n";
// Build the email headers.
$email_headers = "From: $firstname $lastname <$email>";
// Send the email.
if ( mail( $recipient, $subject, $email_content, $email_headers ) ) {
// Set a 200 (okay) response code.
http_response_code( 200 );
echo "Your message has been sent and I will be in contact soon.";
} else {
// Set a 500 (internal server error) response code.
http_response_code( 500 );
echo "Something went wrong and we couldn't send your message.";
}
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code( 403 );
echo "There was a problem with your submission, please try again.";
}
?>
HTML
<form id="form" class="item needs-validation" method="POST" action="contact-form.php" novalidate>
<div class="form-row">
<div class="form-group col-md-6">
<label for="firstname">First name *</label>
<input id="firstname" name="firstname" class="form-control" placeholder="John" type="text" required maxlength="100">
<div class="valid-feedback">What a lovely name!</div>
<div class="invalid-feedback">That's no name.</div>
</div>
<div class="form-group col-md-6">
<label for="lastname">Last name *</label>
<input id="lastname" name="lastname" class="form-control" placeholder="Doe" type="text" required maxlength="100">
<div class="valid-feedback">Looks good!</div>
<div class="invalid-feedback">That's not a real name.</div>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="email"><i class="far fa-envelope mr-2"></i>Email *</label>
<input id="email" name="email" class="form-control" placeholder="someone#domain.com" type="email" required maxlength="100">
<div class="valid-feedback">Valid</div>
<div class="invalid-feedback">That's not a real email...</div>
</div>
<div class="form-group col-md-6">
<label for="phone"><i class="fas fa-mobile-alt mr-2"></i>Phone</label>
<input id="phone" name="phone" class="form-control" placeholder="1234567890" type="tel" maxlength="20">
<div class="valid-feedback">Not required.</div>
<div class="invalid-feedback">That's not a real phone number.</div>
</div>
</div>
<div class="form-row">
<div class="form-group col-12">
<label for="message"><i class="fa fa-comment-alt mr-2"></i>Message *</label>
<textarea id="message" name="message" class="form-control" placeholder="" maxlength="100000"></textarea>
<div class="valid-feedback">Nice message.</div>
<div class="invalid-feedback">I have no idea what you did, but that's not valid.</div>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<div class="g-recaptcha" data-sitekey="6LdOqVsUAAAAAN25grBs05Ip8JmjGQNqURivfH0y"></div>
</div>
<div class="form-group col-md-6">
<button id="submit" name="submit" type="submit" class="btn btn-primary btn-lg" style="float: right;">
Submit
</button>
</div>
</div>
</form>
JS AJAX
$(function() {
"use strict";
// Get the form.
var form = $('#form');
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// Set the message text.
$('#alert-form-success-text').text(response);
$('#alert-form-success').css({
"visibility": "visible",
"opacity": "1"
});
$('#alert-form-fail').css({
"visibility": "hidden",
"opacity": "0"
});
})
.fail(function(data) {
$('#alert-form-fail').css({
"visibility": "visible",
"opacity": "1"
});
$('#alert-form-success').css({
"visibility": "hidden",
"opacity": "0"
});
// Set the message text.
if (data.responseText !== '') {
$('#alert-form-fail-text').text(data.responseText);
} else {
$('#alert-form-fail-text').text('An internal error occured and your message could not be sent.');
}
});
});
});
The issue only relates to the reCaptcha integration, the scripts ability to get the POST information and email is fine. I think the issue is localized to the chain of methods started by
$validation = sendCaptchaResponse();
If you have any questions, don't hesitate to ask.
Here's the page with the form: https://chillstice.com/contact
The fileGetContentsCurl() function in the PHP file was being run as 'file_get_contents_curl()'
Fixing this typo and making the methods go by a consistent name solved this issue. I sure wish my IDE or the debugging tools would have helped me fix this one (1) typo, but that's PHP for you.
I would like to thank Karlo Kokkak for alluding me to the typo.
After making the changes, the entire script works as intended.

Move_uploaded_file having issues with WordPress

Trying to add a file upload to WordPress, all is working well so far except for move_uploaded_file.
<input type="file" name="attachment" id="attachment">
The field in my form above
if (!move_uploaded_file($_FILES["attachment"]["tmp_name"],WP_CONTENT_DIR .'/uploads/cv/'.basename($_FILES['attachment']['name'])))
{
$return['error'] = true; $return['error_message'] = __('File could not be uploaded', 'btoa').'<br />';
}
Attempting to move the uploaded file, it's not working and displaying the error.
I've tried to use is_uploaded_file, which also returns false, the uploads folder is 777, the folder it is trying to save in /cv/ is also 777.
I am not quite sure what is going wrong here, there is no error log being created and I just can't seem to get it to work.
Apart from moving the uploaded file, sending out attachments is working perfectly.
Anything I can do?
FORM CODE
<form action="<?php echo home_url() ?>" method="post" id="enquiry-form" enctype="multipart/form-data">
<p><small class="error" style="margin-top: 15px; display: none;"></small></p>
<p><input type="text" value="<?php _e('Your name', 'btoa'); ?>" name="name" id="enquiry-name" onfocus="if(jQuery(this).val() == '<?php _e('Your name', 'btoa'); ?>') { jQuery(this).val(''); }" onblur="if(jQuery(this).val() == '') { jQuery(this).val('<?php _e('Your name', 'btoa'); ?>'); }" /></p>
<p><input type="text" value="<?php _e('Email address', 'btoa'); ?>" name="email" id="enquiry-email" onfocus="if(jQuery(this).val() == '<?php _e('Email address', 'btoa'); ?>') { jQuery(this).val(''); }" onblur="if(jQuery(this).val() == '') { jQuery(this).val('<?php _e('Email address', 'btoa'); ?>'); }" /></p>
<p><label for="file">Upload your CV/Resume:</label></p>
<p style="margin-bottom:0;"><input type="file" name="attachment" id="attachment"></p>
<p><textarea name="message" id="enquiry-message" cols="" rows="4" onfocus="if(jQuery(this).val() == '<?php _e('Message', 'btoa'); ?>') { jQuery(this).val(''); }" onblur="if(jQuery(this).val() == '') { jQuery(this).val('<?php _e('Message', 'btoa'); ?>'); }"><?php _e('Message', 'btoa'); ?></textarea></p>
<p><input type="submit" class="button-primary" value="<?php _e('Send', 'btoa'); ?>" /></p>
<div class="clear"></div>
<!-- /.clear/ -->
<div class="error-message"></div>
<div class="thank-you hidden">
<p><?php _e('Thank you! Your message has been successfully sent.', 'btoa'); ?></p>
</div>
</form>
SUCCESS FORM CODE
//// IF EMAIL IS VALID
if($return['error'] == '') {
/// GETS OTHER VARS
$name = isset($_POST['email']) ? trim($_POST['name']) : '';
$the_message = isset($_POST['message']) ? trim($_POST['message']) : '';
$post_id = isset($_POST['post_id']) ? trim($_POST['post_id']) : '';
//// NOW WE GET OUR SPOT AND THE USER
$spot = get_post($post_id);
$user = get_user_by('id', $spot->post_author);
//// STARTS OUR RECIPIENT ARRAY
$to = $user->user_email;
//// HEADERS
$headers = 'From: '.get_bloginfo('name').' <'.get_option('admin_email').'>'."\r\n".
'Reply-To: '.$email;
$subject = sprintf2(__('%site_name Contact: %spot_name', 'btoa'), array('site_name' => get_bloginfo('name'), 'spot_name' => $spot->post_title));
if (!move_uploaded_file($_FILES["attachment"]["tmp_name"],WP_CONTENT_DIR .'/uploads/cv/'.basename($_FILES['attachment']['name'])))
{
$return['error'] = true; $return['error_message'] = __('File could not be uploaded', 'btoa').'<br />';
error_reporting(E_ERROR | E_WARNING | E_PARSE);
}
$attachments = array(WP_CONTENT_DIR ."/uploads/cv/".basename($_FILES['attachment']['name']));
add_filter( 'wp_mail_content_type', 'my_custom_email_content_type' );
function my_custom_email_content_type() {
return 'text/html';
}
$message = sprintf2(__("Dear %author,
%user (email: %email) has sent you a message via %site_name:
-----
%message", 'btoa'), array(
'author' => $user->display_name,
'user' => $name,
'email' => $email,
'site_name' => get_bloginfo('name'),
'attachment' => $attachments,
'message' => $the_message
));
//// SENDS OUT OUR EMAIL
if(!wp_mail($to, $subject, stripslashes($message), $headers, $attachments)) {
$return['error'] = true; $return['error_email'] = sprintf2(__('There was a problem sending your enquiry. Please email us directly at %site_email', 'btoa'), array('site_email' => get_option('admin_email')));
} else { $return['success'] = stripslashes($headers); }
}
echo json_encode($return);
exit;
}
Ignore the slightly messy code while trying to fix this bug.
Also attempted to add/adjust this in wp_config, but still no error logs being created in root or wp-content
// Enable WP_DEBUG mode
define('WP_DEBUG', true);
// Enable Debug logging to the /wp-content/debug.log file
define('WP_DEBUG_LOG', true);
// Disable display of errors and warnings
define('WP_DEBUG_DISPLAY', false);
#ini_set('display_errors',0);
// Use dev versions of core JS and CSS files (only needed if you are modifying these core files)
define('SCRIPT_DEBUG', true);
Have you tried echoing out the WP_CONTENT_DIR and seeing what that gets? Or doing a var_dump(is_dir(WP_CONTENT_DIR .'/uploads/cv/'.basename($_FILES['attachment']['name'])). Also doing a print_r on the $_FILES array to see the actual error number it returns and correlating that with: http://us1.php.net//manual/en/features.file-upload.errors.php may help. Let me know the results to each please unless of course you figure it out.

Categories