I have a specific request from a client that a newsletter signup be sent to a CSV file. I am a noob when it comes to anything backend, let alone frontend development.
I have a template that I am working from and can't make sense of the way it delivers the values.
The form code is quite simple
<form action="" method="post" class="signup" id="newsletter-form">
<p>
<input type="text" name="signup_name" id="signup_name" class="required" value="Your Name" />
</p>
<p>
<input type="text" name="signup_email" id="signup_email" class="required" value="Your E-mail" />
</p>
<input type="submit" value="SEND" class="signupSubmit" id="submitform" />
<div id="newsletter-msg-wrapper" style="position:relative; clear:both; width:100%;">
<div id="newsletter-loader"></div> <span id="newsletter-msg"> </span>
</div>
</form>
Then I have this .js file that seems to be handling the post
$(document).ready(function () {
var contactFormDefaults = new Array();
contactFormDefaults['name'] = 'Your Name';
contactFormDefaults['email'] = 'E-mail';
contactFormDefaults['subject'] = 'Subject';
contactFormDefaults['message'] = 'Message';
contactFormDefaults['msg'] = $('.contactForm span#msg').html();
$('.contactForm input[type="text"], .contactForm textarea').focus(function () {
$(this).addClass('inputHighlight').removeClass('errorOutline');
if ($(this).hasClass('required')) {
$('.contactForm span#msg').html('This is a required field.').removeClass('errorMsg successMsg');
} else {
$('.contactForm span#msg').html(contactFormDefaults['msg']).removeClass('errorMsg successMsg');
}
if ($(this).val() == contactFormDefaults[$(this).attr('id')]) {
$(this).val('');
}
});
$('.contactForm input[type="text"], .contactForm textarea').blur(function () {
$(this).removeClass('inputHighlight');
$('.contactForm span#msg').html(contactFormDefaults['msg']).removeClass('errorMsg successMsg');
if ($(this).val() == '') {
$(this).val(contactFormDefaults[$(this).attr('id')]);
}
});
$('.contactForm input[type="text"], .contactForm textarea').hover(function () {
$(this).addClass('inputHighlight');
}, function () {
$(this).not(':focus').removeClass('inputHighlight');
});
$('.contactForm').submit(function () {
$('.contactForm .submit').attr("disabled", "disabled");
$('#msg').html('<img src="images/loader-light.gif" />').removeClass('errorMsg successMsg');
var isError = false;
$('.contactForm input, .contactForm textarea').each(function () {
if ($(this).hasClass('required') && ($.trim($(this).val()) == contactFormDefaults[$(this).attr('id')] || $.trim($(this).val()) == '')) {
$(this).addClass('errorOutline');
$('#msg').html('There was an error sending your message. Please try again.').addClass('errorMsg');
isError = true;
}
if ($(this).attr('id') == 'email') {
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (reg.test($(this).val()) == false) {
$(this).addClass('errorOutline');
if (!isError) {
$('#msg').html('Please enter a valid e-mail address and try again.').addClass('errorMsg');
}
isError = true;
}
}
});
if (isError) {
$('.contactForm .submit').removeAttr("disabled");
return false;
} else {
var name = $('#name').val(),
email = $('#email').val(),
subject = $('#subject').val(),
message = $('#message').val();
$.ajaxSetup({
cache: false
});
var dataString = 'name=' + name + '&email=' + email + '&subject=' + subject + '&message=' + message + '&ajax=1';
$.ajax({
type: "POST",
url: "../myform.php",
data: dataString,
success: function (msg) {
// Check to see if the mail was successfully sent
if (msg == 'Mail sent') {
// Update the progress bar
$('#msg').html('Message sent.').addClass('successMsg');
// Reset the subject field and message textbox
if (contactFormDefaults['subject']) {
$('#subject').val(contactFormDefaults['subject']);
} else {
$('#subject').val('');
}
if (contactFormDefaults['message']) {
$('#message').val(contactFormDefaults['message']);
} else {
$('#message').val('');
}
} else {
$('#msg').html('There was an error sending your email. Please try again.').addClass('errorMsg');
$('.contactForm .submit').attr("disabled", "");
}
// Activate the submit button
$('.contactForm .submit').removeAttr("disabled");
},
error: function (ob, errStr) {
$('#msg').html('There was an error sending your email. Please try again.').addClass('errorMsg');
//Activate the submit button
$('.contactForm .submit').removeAttr("disabled");
}
});
return false;
}
});
});
If possible I'd love to know how to make this all function and what I am not seeing here and how this all can be written into a CSV file.
A full view of the site and code can be viewed here:
www.cndnsd.com/ClientAccess/Newmarket/FinalSite/index.html
The form is at the bottom of the page.
in your myform.php , receive all the data (email, name etc) and start creating your CSV file. It is a simple operation and not that complicated.
For CSV file writing, please check out these posts on stack overflow:
write into csv file in php
Creating csv file with php
Also do some googling.
Hopefully this will help you.
Related
I want to get the value of jquery in php form in popup.
my jquery is
$(document).ready(function(){
$("#submit").click(function() {
var mobileNumber = $("#mobileNumber").val();
if(mobileNumber=="")
{
alert("Please Enter Mobile Number");
}
else
{
$.ajax({
type: "POST",
url: "<?php echo base_url('test'); ?>",
data: {mobileNumber: mobileNumber},
success: function(result){
if(result){
$("#enter-otp").modal('show');
}
}
});
}
return false;
});
});
I want to print var mobileNumber value in enter-otp id popup in same page
so i write
<?php echo $mobileNumber; ?>
but it is not showing
If you want to enter value in enter-otp id popup in same page. You dont want any PHP script you can do it by jquery only. (Although You can write in success of ajax). Suppose you have div tag with id of otp-div inside enter-otp. You can write following code
success: function(result){
if(result){
$("#enter-otp").modal('show');
$("#otp-div").html(mobileNumber);
//OR ifotp-div inout attribute then use `val()`
$("#otp-div").val(mobileNumber);
}
}
depending on what gives you back your "result"-variable, you can output data.
so if your "result"-variable gives you back something useful, you can take this data and put it in the html like this.
success: function(result){
if(result){
$("#enter-otp").html(result).modal('show');
}
}
regarding to your edit, this would be a simple solution:
success: function(result){
if(result){
$("#enter-otp").html(mobileNumber).modal('show');
}
}
i picked up your code and run it on localhost. and after few changes, i got it working. to try following:
test.php
<form action="" method="post">
<input id="mobileNumber" type="text" name="mobileNumber" value="" placeholder="">
<input id="submit" type="submit" name="" value="submit">
</form>
<div id="enter-otp" style="display: none; border: 1px solid red;"></div>
<script>
$(document).ready(function() {
$("#submit").click(function() {
var mobileNumber = $("#mobileNumber").val();
if (mobileNumber == "") {
alert("Please Enter Mobile Number");
} else {
$.ajax({
type: "POST",
url: "result.php",
data: { 'mobileNumber': mobileNumber },
success: function(result) {
if(result){
$("#enter-otp").show();
$("#enter-otp").html(result);
} else {
alert("no data received");
}
}
});
}
return false;
});
});
</script>
result.php
<?php
if( isset($_REQUEST['mobileNumber'] )){
echo $mobileNumber = $_REQUEST['mobileNumber'];
} else {
echo "no data";
}
?>
I'm not a tech completely, and I'm trying to build my custom theme for WordPress.
So, I came to a point that I need to implement a custom JS script to send the form data. As far as I understand, it's going to be a PHP file, but now I'm concentrated on front-end. This is AJAX + jQuery validation.
I don't want my form to refresh the page after it sends the data, just a simple message telling that everything went successful.
Can anyone have a look at the code I wrote and tell me what's wrong with it? It took me just two days..
PS - the file, that stores that code is embedded into WP theme properly, with a jQuery as a dependancy. I wonder, do I have to do anything to implement AJAX, or it comes with jQuery?
http://codepen.io/anon/pen/MpdRpE
<form class="form">
<div class="form__item form__item_no-margin">
<input type="text" name="firstname" placeholder="What's your name?*" class="firstname" required>
<p class="error-message">Sorry, but this field can't be empty.</p>
</div>
<div class="form__item">
<input type="text" name="email" placeholder="What's your email address?*" class="email" required>
<p class="error-message">Oopps, I haven't seen emails like that.</p>
</div>
<div class="form__item">
<textarea name="comment" placeholder="Want to leave any message?*" class="textarea" required></textarea>
<p class="error-message">Nothing to say at all? Really?</p>
</div>
<div class="form__item">
<input type="button" name="submit" value="Send" class="submit-btn">
<p class="error-message error-message_main val-error">All the required fields have to be filled out.</p>
<p class="error-message error-message_main_success val-success">Thanks. I'll contact you ASAP!</p>
</div>
</form>
.error-message {
display: none;
}
jQuery(document).ready(function(){
jQuery(".submit-btn").click(function(){
var name = jQuery(".firstname").val();
var email = jQuery(".email").val();
var message = jQuery(".textarea").val();
if(name === "" || email === "" || message === "") {
jQuery(".val-error", ".error-message").css("display", "block");
}
else {
jQuery.ajax({
url:"/assets/php/send.php",
method:"POST",
data:{name:firstname, email:email, message:comment},
success: function(data) {
jQuery("form").trigger("reset");
jQuery(".val-success").show(fast);
}
});
}
});
});
First you need to prevent the default click event
Second you need a action variable to pass to the wordpress hook
3th you jquery selector for showing the errors is incorrect, the coma needs to be in the string
jQuery(document).ready(function(){
jQuery(".submit-btn").click(function(e){
e.preventDefault();
var name = jQuery(".firstname").val();
var email = jQuery(".email").val();
var message = jQuery(".textarea").val();
if(name === "" || email === "" || message === "") {
jQuery(".val-error, .error-message").show();//a little bit cleaner
}
else {
jQuery.ajax({
url:"/assets/php/send.php",
method:"POST",
data:{name:firstname, email:email, message:comment,action:'validate_form'},
success: function(data) {
jQuery("form").trigger("reset");
jQuery(".val-success").show(fast);
}
});
}
});
});
for more information read the wp documentation on ajax
Little changes required otherwise code is looking fine.Have a look
$(document).ready(function(){
$(".submit-btn").click(function(){
var name = $(".firstname").val();
var email = $(".email").val();
var message = $(".textarea").val();
if(name === "" || email === "" || message === "") {
$(".val-error", ".error-message").css("display", "block");
return false;
}
else {
$.ajax({
url:"/assets/php/send.php",
method:"POST",
data:{name:name, email:email, message:message},
success: function(data) {
if(data){
$("form").trigger("reset");
$(".val-success").show(fast);
}
}
});
}
});
});
I am trying to implement a realtime email duplication check in an application using PHP Codigniter, Ajax and Jquery. But I am not getting any successful results.
Jquery
<script type="text/javascript">
$(document).ready(function()
{
$("#email").keyup(function()
{
if($("#email").val().length >= 4)
{
$.ajax(
{
type: "POST",
url: "<?php echo site_url('stthomas/check_user');?>",
data: "email="+$("#email").val(),
success: function(msg)
{
if(msg=="true")
{
$("#usr_verify").css({ "background-image": "url('<?php echo base_url();?>images/yes.png')" });
}
else
{
$("#usr_verify").css({ "background-image": "url('<?php echo base_url();?>images/no.png')" });
}
}
});
}
else
{
$("#usr_verify").css({ "background-image": "none" });
}
});
});
</script>
My Form is as Follows
<div class="form-group formgp">
<label class="col-md-4" for="Inputemail">Email :</label>
<div class="col-md-8" >
<input type="text" name="email" class="form-control" id="email" value="<?php echo set_value('email'); ?>" placeholder="Email"> <span id="usr_verify" class="verify"></span>
</div>
</div>
Controller:
public function check_user()
{
$usr=$this->input->post('email');
$result=$this->stthomas_model->check_user_exist($usr);
if($result)
{
echo "false";
}
else{
echo "true";
}
}
Model:
public function check_user_exist($usr)
{
$this->db->where("email",$usr);
$query=$this->db->get("email");
if($query->num_rows()>0)
{
return true;
}
else
{
return false;
}
}
It is not easy to guess what the problem is, but you better check the jquery ajax error detail. you have just set the success part of process in your code:
success: function(msg){
See what error you have if the ajax gets an error:
success: function(msg){
// success code
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
Currently the below script works brillantly checking the database using ajax to see if the email address has been used before. My question is how do I stop it checking the database until it is a fully defined EMAIL address?
Form field
<label for="email">Email: * </label><br/>
<input id="username" name="username" type="email" value="" onblur="return check_username();" />
AJAX script
<script type="text/javascript">
$(document).ready(function() {
$('#Loading').hide();
});
function check_username(){
var username = $("#username").val();
if(username.length > 2){
$.post("../script/check_username_availablity.php", {
username: $('#username').val(),
}, function(response){
$('#Info').fadeOut();
setTimeout("finishAjax('Info', '"+escape(response)+"')", 450);
});
return false;
}
}
function finishAjax(id, response){
$('#'+id).html(unescape(response));
$('#'+id).fadeIn(1000);
}
</script>
Instead of if(username.length > 2){... use something like:
if (/^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\
".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA
-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(username.val())) {...
see http://jsfiddle.net/cmontgomery/gEL7n/
very similar to what ialencar posted:
isValidateEmail = function(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
check_username = function() {
var username = $("#username").val();
if(isValidateEmail(username)) {
$("#username-error").html("");
console.log("ajax request...");
} else {
$("#username-error").html("invalid email address");
}
}
I am having some problems adding a reCaptcha to my jQuery AJAX form.
I have tried following the documentation, in particular this page, but had no luck.
If I use the "Challenge and Non-JavaScript API", adding the code
before the send button, I get no output.
If I try with the method
called "AJAX API" adding a custom div inside the form, I don't get
anything anyway. Basically I am not able to show and then validate
it.
This is the code that I have so far.
My form:
<div id="contactForm"><img src="img/contact-form.png" width="250" height="365" alt="contact" /></div>
Name: <span class="contactErrorFloat" id="err-name">Need the name</span>
<input name="name" id="name" type="text" placeholder="Name.." />
Email: <span class="contactErrorFloat" id="err-email">Need email</span><span class="contactErrorFloat" id="err-emailvld">Email not valid.</span>
<input name="email" id="email" type="text" placeholder="Email.." />
Message:
<textarea name="message" id="message" rows="10" placeholder="Message.."></textarea>
<button id="send">Send</button>
<div class="contactError" id="err-form">Error during validation</div>
<div class="contactError" id="err-timedout">Timeout</div>
<div class="contactError" id="err-state"></div>
<div id="ajaxsuccess">Email sent!</div>
</form>
My Script:
jQuery(document).ready(function ($) {
$('#send').click(function(){
$('.error').fadeOut('slow'); // Resetta i messaggi di errore, nascondendoli
var error = false;
var name = $('input#name').val();
if (name == "" || name == " ") {
$('#err-name').fadeIn('slow');
error = true;
}
var email_compare = /^([a-z0-9_.-]+)#([da-z.-]+).([a-z.]{2,6})$/;
var email = $('input#email').val();
if (email == "" || email == " ") {
$('#err-email').fadeIn('slow');
error = true;
} else if (!email_compare.test(email)) {
$('#err-emailvld').fadeIn('slow');
error = true;
}
if (error == true) {
$('#err-form').slideDown('slow');
return false;
}
var data_string = $('#ajax-form').serialize();
$.ajax({
type: "POST",
url: $('#ajax-form').attr('action'),
data: data_string,
timeout: 6000,
error: function(request, error) {
if (error == "timeout") {
$('#err-timedout').slideDown('slow');
} else {
$('#err-state').slideDown('slow');
$('#err-state').html('C\'รจ stato un errore: ' + error + '');
}
},
success: function () {
$('ajax-form').slideUp('slow');
$('#ajaxsuccess').slideDown('slow');
}
});
return false;
});
});
There is also a PHP file with the php function to send the email but I don't think it's much important actually. I would really LOVE if someone could give me any help to implement this. Thanks a lot!
first of all you have to sign in to recaptcha. You can do this here:
recaptcha.net
then you can get your key. Then you embed the key into the sample code.
Here
<script type="text/javascript"
src="http://www.google.com/recaptcha/api/challenge?k=**your_public_key**">
and here
<iframe src="http://www.google.com/recaptcha/api/noscript?k=**your_public_key**"
height="300" width="500" frameborder="0"></iframe>