404 error ajax, code works with straight php / html - php

so my code works fine by itself, but I'm trying to add some ajax into it. I'm using CI, to do some of the lifting. I don't understand why it's giving a 404 if the code works fine without ajax.
Here is the form:
<div class="divider" id="contact">
<p class = "header"><a id="contactheader" name="gocontact">Contact</a></p>
<div id = "contactform">
<form method = "post" id="contactform" action="<?php site_url()?>index.php/home/sendemail">
<div id ="formtitles">
<p class = "info">You:</p>
<p class = "info">Me:</p>
<p class = "info">Subject:</p>
<p class = "info">Body:</p>
<input id = "submit" type="submit" value="Send" />
</div>
<div id ="formfields">
<input id="you" type="text" name="you" /><br/>
<p class = "info">#gmail.com</p>
<input id ="subject" type="text" name="subject" /><br/>
<textarea id = "contactbody"></textarea>
</div>
</form>
</div>
</div>
The .js
$(document).ready(function() {
$('#submit').click(function(){
var contactformdata = {
you: $('#you').val(),
subject: $('#subject').val(),
message: $('#message').val(),
}
console.log(you);
$.ajax({
url: "trenthauck.com/index.php/home/sendemail",
type: 'POST',
data: contactformdata,
success: function(){
$('#contactheader').replaceWith("<p class='header'>Thanks</p>");
$('#contactform').remove();
$('#contactlink').remove();
$(document).scrollTop(25);
}
});
return false;
});
});
And finally the controller:
<!--
Name: Trent Hauck
Date: INSERT
File: INSERT
Desc: INSERT
-->
<?php
class Home extends Controller{
function index(){
$this->load->view('home_view');
return true;
}
function sendemail(){
$to = "trent.hauck#gmail.com";
$from = $this->input->post('you');
$subject = $this->input->post('subject');
$message = $this->input->post('contactbody');
$message = wordwrap($message, 75);
$tosend = "From: " . $from . "\nMessage: " . $message;
mail($to, $subject, $tosend);
$this->index();
}
}
Side question, assuming you're still reading. Is there anyway to do something like site_url() from CI in the .js so I don't have to call the whole thing. Thanks

You forgot http:// at the beginning of your Ajax url parameter:
So the browser thinks you're pointing it to [site_url]/trenthauck.com/index.php/home/sendemail, which, in all likelihood, isn't what you intended.

Related

Error in submit form with ajax and send mail in wordpress

I am trying submit custom form written in header.php with ajax and send mail to particular email address with submitted data,but getting error of 404 in console, form validation is performs taht means jquery file is loaded but when trying to call ajaxurl to send mail it gives 404 error. I am 100% sure that error is in ajax call or need to make function in function.php for sending mail but can't solve it out, can anyone help me solve out this issue?
Form in header.php
<form id="wp_con_form" method="post">
<ul class="form-list wp_contact_form_ul cf">
<li>
<input type="text" name="name" id="name" placeholder="Name *" class="text-field wp_con_frm_name">
</li>
<li>
<input type="text" name="phone" id="phone" placeholder="Phone *" class="text-field wp_con_frm_phone">
</li>
<li>
<input type="text" name="email" id="email" placeholder="Email *" class="text-field wp_con_frm_email">
</li>
<li>
<input type="text" name="agency" id="agency" placeholder="agency" class="text-field ">
</li>
<li class="full">
<textarea name="message" id="message" placeholder="Message *" class="text-field wp_con_frm_message"></textarea>
</li>
<li class="form-button">
<input type="submit" value="Send" id="wp_con_frm_btn" class="button" />
</li>
<div class="wp_cont_form_msg"></div>
</ul>
</form>
calling jquery file in function.php is
wp_enqueue_style( 'themestyle', get_template_directory_uri() . '/assets/css/style.css',false,'1.1','all' );
wp_localize_script("themestyle","the_ajax_theme", array("ajaxurl_anyName" => admin_url("admin-ajax.php")));
Jquery file for validation and ajax call
var j = jQuery.noConflict();
j(document).ready(function(){
function validateContact(){
var output = true;
j('.wp_contact_form_ul li').removeClass('wp_cont_frm_err_msg');
if(!(j(".wp_con_frm_name").val())){
j(".wp_con_frm_name").parent().addClass('wp_cont_frm_err_msg');
output = false;
}
if(!(j(".wp_con_frm_phone").val())){
j(".wp_con_frm_phone").parent().addClass('wp_cont_frm_err_msg');
output = false;
}
if(!j(".wp_con_frm_phone").val().match(/^[(]{0,1}[0-9]{3}[)]{0,1}[-\s\.]{0,1}[0-9]{3}[-\s\.]{0,1}[0-9]{4}$/))
{
j(".wp_con_frm_phone").parent().addClass('wp_cont_frm_err_msg');
output = false;
}
if(!(j(".wp_con_frm_email").val())){
j(".wp_con_frm_email").parent().addClass('wp_cont_frm_err_msg');
output = false;
}
if(!j(".wp_con_frm_email").val().match(/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/))
{
j(".wp_con_frm_email").parent().addClass('wp_cont_frm_err_msg');
output = false;
}
if(!(j(".wp_con_frm_message").val())){
j(".wp_con_frm_message").parent().addClass('wp_cont_frm_err_msg');
output = false;
}
return output;
}
/* send contact form data to email */
function afterSubmit(getobj)
{
if(getobj.status)
{
j('#wp_con_form')[0].reset();
j('#wp_con_form .wp_cont_form_msg').html(getobj.message).slideDown().delay(5000).slideUp();
}
else
{
j('#wp_con_form .wp_cont_form_msg').html(getobj.message).slideDown().delay(5000).slideUp(5000);
}
}
j('#wp_con_frm_btn').click(function(){
var output = validateContact();
if(output){
var dataString = j("#wp_con_form").serialize();
j.ajax({
type: "POST",
url: ajaxurl,
dataType:"json",
data: dataString,
}).always(function(data)
{
afterSubmit(data);
});
}
return false;
});
});
code for sending mail in function.php
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$msg = $_POST['message'];
$to = 'yourname#example.com';
$subject = 'List Qwick';
$message = 'Name: '.$name. "\r\n" .
'Phone: '.$phone. "\r\n" .
'Email: '.$email. "\r\n" .
'Message: '.$msg. "\r\n" .
$headers = "From: ".$email."\r\n" .'X-Mailer: PHP/' . phpversion();
if(wp_mail($to, $subject, $message, $headers))
{
$getMessage = '<p class="success">Your Email Has Been Sent Successfully</p>';
echo json_encode(array('status'=>1,'message'=>$getMessage));
}
else
{
$getMessage = '<p class="error">Mail function not working..</p>';
echo json_encode(array('status'=>0,'message'=>$getMessage));
}
When you make the Ajax URL available for JavaScript, you're actually creating an object called the_ajax_theme, and one of its properties is called ajaxurl_anyName and contains your Ajax URL.
wp_localize_script( 'themestyle', 'the_ajax_theme', array(
'ajaxurl_anyName' => admin_url( 'admin-ajax.php' )
) );
In your Ajax call, you're trying to access the ajaxurl which doesn't exists. To use the value that you're actually defining, you have to use the names you defined in your wp_localize_script(). So, your Ajax call should look like this:
j('#wp_con_frm_btn').click(function(){
var output = validateContact();
if(output){
var dataString = j("#wp_con_form").serialize();
j.ajax({
type: "POST",
url: the_ajax_theme.ajaxurl_anyName,
dataType:"json",
data: dataString,
}).always(function(data)
{
afterSubmit(data);
});
}
return false;
});
I'd recommend to use shorten names like themeSlug.ajaxURL.
It doesn't look like ajaxurl is ever set, so you're getting a 404 on an "undefined" URL. Set that value and you should be set.
It's possible it needs the admin-ajax.php file from WordPress, for the form action.
<form action="<?php echo admin_url( 'admin-ajax.php' ) ?>" method="post">
Also, it doesn't look like you're defining ajaxurl in your JavaScript. Try adding this:
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
Add it above or below this line in your existing code:
var dataString = j("#wp_con_form").serialize();

$POST is returning empty values from HTML form

I am newbie for HTML and PHP programming.
When i am submitting data from form $POST is not fetching values from form and simply empty values are getting mailed .spent quite a lot time for this but couldn't figured it out..
following is part of a code of my HTML Form
<form id="main-contact-form" class="contact-form" name="contact-form" method="POST" action="sendemail.php">
<div class="form-group">
<input type="text" name="namefirst" class="form-control" required="required" placeholder="Name">
</div>
<div class="form-group">
<input type="email" name="emailfirst" class="form-control" placeholder="Email ID">
</div>
<div class="form-group">
<input type="tel" name="tel" class="form-control" placeholder="Mobile No">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary pull-right">Send</button>
</div>
</form>
following is my PHP code
<?php
header('Content-type: application/json');
$status = array(
'type'=>'success',
'message'=>'Thank you for registering wth us.We will keep updating you.'
);
{
$name = $_POST["namefirst"];
$email = #trim(stripslashes($_POST["emailfirst"]));
$email_from = $email;
$email_to = '****';//replace with your email
$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email . "\n\n" ;
$success = #mail($email_to, $subject, $body, 'From: <'.$email_from.'>');
echo json_encode($status);
}
?>
i have tried all the possible solutions,but its just not working.Please let me know what is wrong with this.
i figured it out ..problem is not with PHP or HTML file it is with javascript code,values were not getting set there #MueyiwaMosesIkomi thanks alot becoz of this i got this problem so to solve this I did following thing:
EARLIER my code was:
var form = $('.contact-form');
form.submit(function () {'use strict',
$this = $(this);
$.post($(this).attr('action'), function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
return false;
});
which was not sending values. after this code its working;
var form = $('.contact-form');
var namefirst= $('.contact-form' . 'namefirst').val();
form.submit(function () {'use strict',
$this = $(this);
$.post($(this).attr('action'), function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
return false;
});
now its sending values but it is going on next page and showing php echo as it is,not encoding Json so i thnik
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
this part of code is not working...can anyone help regarding this??????
Thanks all of you

Ajax not capturing php contact form script

I have a contact form on my website that is not posting the success or error message as it should.
The weird thing is I have used this exact same form, php, and ajax script on several other sites and it works great. In fact, it used to work great on the site in question.
The website is https://www.pouncingfoxdesign.com. The contact form is at the bottom. Feel free to fill it out for testing purposes.
Here's the form and script:
<div class="col-md-8 col-sm-9 wow form1 fadeInLeft">
<div class="contact-form clearfix contactForm">
<form id="form" action="php/email.php" class="contactForm"
method="post">
<div class="messages"></div>
<div class="input-field">
<input type="text" class="form-control" name="name"
placeholder="Your Name" required="">
</div>
<div class="input-field">
<input type="email" class="form-control"
name="email" placeholder="Your Email" required="">
</div>
<div class="input-field message">
<textarea name="message" class="form-control"
placeholder="Your Message" required=""></textarea>
</div>
<input type="submit" name="submit" class="btn btn-blue
pull-right" value="SEND MESSAGE" id="msg-submit">
<div class="g-recaptcha fadeInLeft" data-
sitekey=""></div>
</form>
</div> <!-- end .contact-form -->
</div> <!-- .col-md-8 -->
<script> $('#form').on('submit', function(e) {
event.preventDefault(); //Prevents default submit
var form = $(this);
var post_url = form.attr('action');
var post_data = form.serialize(); //Serialized the form data for
process.php
// $('#loader', '#form').html('<img src="img/forms/loading.gif" />
Please Wait...');
$.ajax({
type: 'POST',
url: 'php/email.php', // Your form script
data: post_data,
success: function(msg) {
var old_html = form.html()
$(form)
.html(msg).fadeIn();
setTimeout(function(){
$(form)
.html(old_html).fadeIn();
}, 4000);
},
error: function(xhr, ajaxOptions, err){
var old_html = form.html()
$(form).fadeOut(500)
.html("<h3>There was an error. Please try again.
</h3>").fadeIn();
setTimeout(function(){
$(form).fadeOut(500)
.html(old_html).fadeIn();
}, 3000);
}
});
});
</script>
And here's the PHP:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$success = "
<div class=\"row-fluid\">
<div class=\"span12\">
<h1>Submission successful</h1>
<h3>Thank you for contacting us!</h3>
</div>
</div>";
$to = "email#email.com";
$subject = "$name\n filled Pouncing Fox Desing Form";
$txt = "From: $name\n E-Mail: $email\n Comments:\n $message";
$headers = "From: Pouncing Fox Design" . "\r\n" ;
if(isset($_POST['g-recaptcha-response'])){
$captcha=$_POST['g-recaptcha-response'];
}
if(!$captcha){
echo '<h2>Please check the the captcha form.</h2>';
exit;
}
$secretKey = "";
$ip = $_SERVER['REMOTE_ADDR'];
$response=file_get_contents
("https://www.google.com/recaptcha/api/siteverify?
secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
$responseKeys = json_decode($response,true);
if (mail($to, $subject, $txt, $headers)) {
echo "$success"
} else {
echo 'Form submission failed. Please try again...'; // failure
}
?>
What I want it to do is replace the form with the success message for a few seconds and then go back to the form. What it does instead is just go to the email.php file with the success message being all that's on the screen.
If you want to check out https://www.mooreengaging.com, the same script and php file is used for that site. It works great and you can see my intended results. Again, feel free to fill out the form for testing purposes.
I have tried to use other ajax scripts and have tried to rework it several different times, but no matter what when clicking submit it just loads the php file. It's like it is bypassing the ajax script altogether.
Thanks!
EDIT:
I have received the emails from you guys testing and they look right. So it is working, just not posting the success message as I'd like.
Ok, I figured it out. I added <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> to the top of the page under the header.
I thought it was best to put jquery at the bottom?
Did it fail because I was trying to run that script before it loaded jquery?
Change
$('#form').on('submit', function(e)
To
$('#form').on('submit', function(event)
Because you use
event.preventDefault();

Form sending email but in the email $_POST values are blank

I have read many forums where this exact question posted but there is no satisfactory answer. Some posts seem to have found out how to make it work but the answer is not shared or only partly answered.
the answer that i see the most is (but don't know how to use it):
var form = $('.contact-form');
form.submit(function () {'use strict',
$this = $(this);
$.post("sendemail.php", $(".contact-form").serialize(),function(result){
if(result.type == 'success'){
$this.prev().text(result.message).fadeIn().delay(3000).fadeOut();
}
});
return false;
});
the problem with this is that $_POST is not being sent. The mail function is working but the mail contents are blank
my mail message:
Name:
Email:
Subject:
Message:
exactly this is in my mail when I fill the form with data and nothing is being sent
main.html
<h4>Contact Form</h4>
<div class="status alert alert-success" style="display: none"></div>
<form id="main-contact-form" class="contact-form" name="contact-form" method="post" action="sendemail.php" role="form">
<div class="row">
<div class="col-sm-5">
<div class="form-group">
<input type="text" class="form-control" name="subject" required="required" placeholder="Subject">
</div>
<div class="form-group">
<input type="text" class="form-control" name="name" required placeholder="First Name">
</div>
<div class="form-group">
<input type="text" class="form-control" name="email" required placeholder="Email address">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-lg">Send Message</button>
</div>
</div>
<div class="col-sm-7">
<textarea name="message" id="message" required class="form-control" rows="8" placeholder="Message"></textarea>
</div>
</div>
</form>
sendemail.php
<?php
header('Content-type: application/json');
$status = array(
'type'=>'success',
'message'=>'Email sent!'
);
$name = #trim(stripslashes($_POST['name']));
$email = #trim(stripslashes($_POST['email']));
$subject = #trim(stripslashes($_POST['subject']));
$message = #trim(stripslashes($_POST['message']));
$email_from = $email;
$email_to = 'myEmail#gmail.com';
$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;
$success = #mail($email_to, $subject, $body, 'From: <'.$email_from.'>');
echo json_encode($status);
die;
Is your form possibly getting submitted twice? (once completed and then blank) The html form is already fully wired to POST without the use of the submit handler, which is redundant.
If I'm going to submit a form via AJAX, I typically set only the id of the form (i.e. no action and no method attributes) and I use a regular button (not submit) as the submit button. This makes it clear that jQuery will be handling the POSTing.
<form id="main-contact-form" class="contact-form" role="form">
...fields
<button id="btn_submit" class="btn btn-primary">Submit</button>
</form>
Then in jQuery
'use strict';
var form = $('.contact-form'),
btn_submit = $('#btn_submit');
btn_submit.on('click', function(e) {
e.preventDefault(); //prevent default button behavior
$.post('sendemail.php', form.serialize(),function(result){
if(result.type == 'success'){
form.prev().text(result.message).fadeIn().delay(3000).fadeOut();
}
});
Change your "jquery" code as shown below:
$('.contact-form').submit(function (e) {
e.preventDefault(); // prevent default form 'submit' event
$this = $(this);
$.post(
"sendemail.php",
$(".contact-form").serialize(),
function(result){
if(result.type == 'success'){
$this.prev().text(result.message).fadeIn().delay(3000).fadeOut();
}
},
'json' // expecting a JSON response from server
);
});
I think you have multiple forms with the css class .contact-form in the same page. If you want to submit this form, then you can use form id selector.
<script type="text/javascript">
$(function() {
$('#main-contact-form').submit(function (e) {
e.preventDefault(); // prevent default form 'submit' event
var $this = $(this);
$.post("sendemail.php", $this.serialize(), function(result) {
if (result.type == 'success') {
$this.prev().text(result.message)
.fadeIn().delay(3000).fadeOut();
}
}
}, 'json');
});
</script>
Or you can write the code using the css selector as follows:
<script type="text/javascript">
$(function() {
$('.contact-form').submit(function (e) {
e.preventDefault(); // prevent default form 'submit' event
var $this = $(this);
$.post("sendemail.php", $this.serialize(), function(result) {
if (result.type == 'success') {
$this.prev().text(result.message)
.fadeIn().delay(3000).fadeOut();
}
}
}, 'json');
});
</script>

PHP mail function + ajax = frustrated me

I'm using ajax to submit a contact from without reloading the page, it works well for the most part except when I try to send the body of the message nothing gets sent. The to and subject parts work fine, it is just when the body tries to get sent I see nothing. I've tested it running strickly a php function and the body works, just the page reloads and I'm not sure why it works here, but not with ajax. If anybody could shed some light it'd be great, thanks.
.js
$(document).ready(function () {
$('#submit').click(function () {
var contactformdata = {
you: $('#you').val(),
subject: $('#subject').val(),
message: $('#contactbody').val(),
}
$.ajax({
url: "http://www.trenthauck.com/index.php/home/sendemail",
type: 'POST',
data: contactformdata,
success: function () {
$('#contactheader').replaceWith("<p class='header'>Thanks</p>");
$('#contactform').remove();
$('#contactlink').remove();
$(document).scrollTop(25);
}
});
return false;
});
});
Here is the php function (using CI, btw)
function sendemail(){
$to = "auck#gmail.com";
$from = $this->input->post('you');
$subject = $this->input->post('subject');
$message = $this->input->post('contactbody');
$tosend = "From: " . $from . "\nMessage: " . $message;
mail($to, $subject, $message);
$this->index();
}
And the form if that helps
<div class="divider" id="contact">
<p class = "header"><a id="contactheader" name="gocontact">Contact</a></p>
<div id = "contactform">
<form method = "post" id="contactform" action="<?php site_url()?>index.php/home/sendemail">
<div id ="formtitles">
<p class = "info">You:</p>
<p class = "info">Me:</p>
<p class = "info">Subject:</p>
<p class = "info">Body:</p>
<input id = "submit" type="submit" value="Send" />
</div>
<div id ="formfields">
<input id="you" type="text" name="you" /><br/>
<p class = "info">auck#gmail.com</p>
<input id ="subject" type="text" name="subject" /><br/>
<textarea id = "contactbody" name="contactbody"></textarea>
</div>
</form>
</div>
</div>
Thanks for the help
in the jquery you're sending the message using the variable 'message' but in the php you're picking it up using 'contactbody'.
change the php from:
$message = $this->input->post('contactbody');
to:
$message = $this->input->post('message');

Categories