Form Validation laravel - javascript

Alright , I made a form with a validation , okay , when I want to connect the validation in laravel I use this way
this is pages controller
public function getContact(){
self::$data['title'] = 'Contact us';
return view('content.contact',self::$data);
}
public function postContact(test $request){
}
}
this is the routes :
Route::get('contact','PagesController#getContact');
Route::post('contact', 'PagesController#postContact');
and this is the form
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript" href="{{asset('js/class.FormValidation.js')}}"></script>
<script type="text/javascript" href="{{asset('js/landin_validation.js')}}"></script>
<link rel="stylesheet" type="text/css" href="{{asset ('js/style.css')}}"/>
</head>
<body>
<form action="" method="post" class="landing-form">
{!! csrf_field() !!}
<label>Fill your details here - </label><br/><br/>
<input placeholder="Full name:" type="text" name="name" class="field-name" />
<input placeholder="Email:" type="text" name="email" class="field-email" />
<input placeholder="Phone Number:" type="text" name="phone" class="field-phone" />
<input type="submit" name="submit" value="Send" />
Okay so , I tried a lot to connect the validation with the form , but since it's laravel so I know the requests way but I tried a lot to connect it with this validation but doesnt work ,
this is landin_validation.js
var formValidate = new FormValidation();
$(document).ready(function () {
$('form.landing-form').submit(function () {
// Collect client info from fields
var name = $.trim( $('input[type="text"].field-name').val() );
var email = $.trim( $('input[type="text"].field-email').val() );
var phone = $.trim( $('input[type="text"].field-phone').val() );
// Reset input fields error class
$('input[type="text"]').removeClass('error');
// Form validation
if (!formValidate.testName(name) ) {
$('input[type="text"].field-name').addClass('error');
$('input[type="text"].field-name').val('');
$('input[type="text"].field-name').attr('placeholder', '* Valid full name is required!');
} else if ( !formValidate.testEmail(email) ) {
$('input[type="text"].field-email').addClass('error');
$('input[type="text"].field-email').val('');
$('input[type="text"].field-email').attr('placeholder', '* Valid email is required!');
} else if ( !formValidate.testPhone(phone) ) {
$('input[type="text"].field-phone').addClass('error');
$('input[type="text"].field-phone').val('');
$('input[type="text"].field-phone').attr('placeholder', '* Valid phone is required!');
} else {
// Open ajax call to save client details + send mail to customer
$.ajax({
url: "form_handler.php",
type: "POST",
dataType: "html",
async: "false",
data: {name: name, email: email, phone: phone},
beforeSend: function () {
var messege = '<img src="ajax-loader.gif" border="0">';
messege += ' Sending... ';
$('form.landing-form label').html(messege);
},
success: function (response) {
if (response == true) {
setTimeout(function(){
$('div.form-wrapper').html('<label>Your details has been send!</label>');
}, 2000);
} else {
$('div.form-wrapper').html('<label>Something went wrong, please try again later...</label>');
}
}
});
}
// Stop form submission
return false;
});
});
And this is FormValidation.js
function FormValidation(){
this.nameReg = [
/^([a-zA-Z\s]+){2,255}$/
];
this.emailReg = [
/^[_a-z0-9-]+(.[_a-z0-9-]+)*#[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$/
];
this.phoneReg = [
/^[0-9]{3}-[0-9]{3}-[0-9]{4}$/i,
/^[0-9]{3}.[0-9]{3}.[0-9]{4}$/i,
/^\([0-9]{3}\)-[0-9]{3}-[0-9]{4}$/i,
/^[0-9]{9,10}$/i
];
this.testName = function( nameInput ){
return this.inputCheck(this.nameReg, nameInput);
};
this.testEmail = function( emailInput ){
return this.inputCheck(this.emailReg, emailInput);
};
this.testPhone = function( phoneInput ){
return this.inputCheck(this.phoneReg, phoneInput);
};
this.inputCheck = function( regArray, inputData ){
var valid = false;
$.each( regArray, function( key, val ){
if( val.test( inputData ) ){
valid = true;
}
});
return valid;
};
}
I just want to know the way to connect the form with this validation.

I think it's not good idea to validate form data with js.Аccording to me you should validate from the server-side.If you want to have good user experience you can use this javascript lib - http://t4t5.github.io/sweetalert/

Related

Ajax form required select and input fields

im new at this so i couldnt work this out with required fields on script.
html form
<form name="rezform" onsubmit="return validation()" id="loginForm" method="" action="" novalidate="novalidate">
javascript
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
function insertData() {
var rez_ad = $("#rez_ad").val();
var rez_saat = $("#rez_saat").val();
var rez_gsm = $("#rez_gsm").val();
var rez_tarih = $("#rez_tarih").val();
var rez_email = $("#rez_email").val();
var rez_tip = $("select#rez_tip").val();
var rez_sayi = $("select#rez_sayi").val();
var rez_aciklama = $("#rez_aciklama").val();
// AJAX code to send data to php file.
$.ajax({
type: "POST",
url: "rez/insert-data.php",
data: {
rez_ad: rez_ad,
rez_saat: rez_saat,
rez_gsm: rez_gsm,
rez_email: rez_email,
rez_tarih: rez_tarih,
rez_tip: rez_tip,
rez_sayi: rez_sayi,
rez_aciklama: rez_aciklama
},
dataType: "JSON",
success: function(data) {
$("#message").html(data);
$("#message").addClass("alert alert-success");
},
error: function(err) {
alert(err);
}
});
}
</script>
insert-data.php
/*
Developer: Ehtesham Mehmood
Site: PHPCodify.com
Script: Insert Data in PHP using jQuery AJAX without Page Refresh
File: Insert-Data.php
*/
include('db.php');
$rez_ad=$_POST['rez_ad'];
$rez_saat=$_POST['rez_saat'];
$rez_gsm=$_POST['rez_gsm'];
$rez_email=$_POST['rez_email'];
$rez_tarih=$_POST['rez_tarih'];
$rez_tip=$_POST['rez_tip'];
$rez_sayi=$_POST['rez_sayi'];
$rez_aciklama=$_POST['rez_aciklama'];
$stmt = $DBcon->prepare("INSERT INTO rezervasyon(rez_ad,rez_saat,rez_gsm,rez_email,rez_tarih,rez_tip,rez_sayi,rez_aciklama) VALUES(:rez_ad, :rez_saat,:rez_gsm,:rez_email,:rez_tarih,:rez_tip,:rez_sayi,:rez_aciklama)");
$stmt->bindparam(':rez_ad', $rez_ad);
$stmt->bindparam(':rez_saat', $rez_saat);
$stmt->bindparam(':rez_gsm', $rez_gsm);
$stmt->bindparam(':rez_email', $rez_email);
$stmt->bindparam(':rez_tarih', $rez_tarih);
$stmt->bindparam(':rez_tip', $rez_tip);
$stmt->bindparam(':rez_sayi', $rez_sayi);
$stmt->bindparam(':rez_aciklama', $rez_aciklama);
if($stmt->execute())
{
$res="Rezervasyonunuz tarafımıza ulaşmıştır. En yakın sürede girmiş olduğunuz GSM numaranıza dönüş yapılacaktır.";
echo json_encode($res);
}
else {
$error="Sistemsel bir hata meydana geldi lütfen bir süre sonra tekrar deneyiniz veya iletişime geçiniz.";
echo json_encode($error);
}
?>
So my problem is when i click my send button on html/php data is going mysql even if the inputs and select boxes are empty/not selected. So I have to do it required like in html input or select box. I dont know how to do it properly in javascript. I have found another script but couldnt work it same as like this one. So how can i put required field on this one and if you can explain it the logic it would be nice !
Also do we have a trick for bot protection on javascript form ?
Thanks !
And have a nice day.
You can do something like create a validation function for check whether input fields are empty or not.
function validation() {
submit = true;
var rez_ad = $("#rez_ad").val();
if ( rez_ad.trim() == "" ) {
//Do what ever you like with when empty submission.
alert('Input is empty.');
submit = false;
}
return submit;
}
Then in form on submit return this function.
<form action="" onsubmit="return validation()" method="POST">
function insertData() {
var rez_ad=$("#rez_ad").val();
var rez_saat=$("#rez_saat").val();
var rez_gsm=$("#rez_gsm").val();
var rez_tarih=$("#rez_tarih").val();
var rez_email=$("#rez_email").val();
var rez_tip=$("select#rez_tip").val();
var rez_sayi=$("select#rez_sayi").val();
var rez_aciklama=$("#rez_aciklama").val();
if(rez_ad == "" || rez_saat == "" || rez_gsm == "" || rez_tarih == "" || rez_email == "" || rez_tip == "" || rez_sayi == "" || rez_aciklama == "" ){
$("#message").html("some field is empty!!");
}else{
// AJAX code to send data to php file.
$.ajax({
type: "POST",
url: "rez/insert-data.php",
data: {rez_ad:rez_ad,rez_saat:rez_saat,rez_gsm:rez_gsm,rez_email:rez_email,rez_tarih:rez_tarih,rez_tip:rez_tip,rez_sayi:rez_sayi,rez_aciklama:rez_aciklama},
dataType: "JSON",
success: function(data) {
$("#message").html(data);
$("#message").addClass("alert alert-success");
},
error: function(err) {
alert(err);
}
});
}
}
<form name="rezform" onsubmit="return validation()" id="loginForm" method="POST" action="#" >
Since you are using jquery, use $('form').submit() method to return false if the validation is not success. other wise return true.
$( "form" ).submit(function( event ) {
if ( $( "input:first" ).val() === "correct" ) {
$( "span" ).text( "Validated..." ).show();
return;
}
$( "span" ).text( "Not valid!" ).show().fadeOut( 1000 );
event.preventDefault();
});
I have created a jsbin page for the reference given by jquery: https://jsbin.com/dokabod/1/edit?html,output
#alex also post the samething. I just corrected some of the errors he had. like return submit. below code working perfectly.
<form action="index.php" onsubmit="return insertData()" method="POST">
<input type="text" name="name" id="rez_ad">
<input type="text" name="name" id="rez_saat">
<input type="text" name="name" id="rez_gsm">
<input type="text" name="name" id="rez_tarih">
<input type="text" name="name" id="rez_email">
<input type="text" name="name" id="rez_tip">
<input type="text" name="name" id="rez_sayi">
<input type="text" name="name" id="rez_aciklama">
<input type="submit" name="" value="Send">
</form>
<div id="message"></div>
function insertData() {
submit = true;
var rez_ad=$("#rez_ad").val();
var rez_saat=$("#rez_saat").val();
var rez_gsm=$("#rez_gsm").val();
var rez_tarih=$("#rez_tarih").val();
var rez_email=$("#rez_email").val();
var rez_tip=$("#rez_tip").val();
var rez_sayi=$("#rez_sayi").val();
var rez_aciklama=$("#rez_aciklama").val();
if(rez_ad == "" || rez_saat == "" || rez_gsm == "" || rez_tarih == "" || rez_email == "" || rez_tip == "" || rez_sayi == "" || rez_aciklama == "" ){
$("#message").html("some field is empty!!");
submit = false;
return submit;
}else{
// AJAX code to send data to php file.
$.ajax({
type: "POST",
url: "rez/insert-data.php",
data: {rez_ad:rez_ad,rez_saat:rez_saat,rez_gsm:rez_gsm,rez_email:rez_email,rez_tarih:rez_tarih,rez_tip:rez_tip,rez_sayi:rez_sayi,rez_aciklama:rez_aciklama},
dataType: "JSON",
success: function(data) {
$("#message").html(data);
$("#message").addClass("alert alert-success");
},
error: function(err) {
alert(err);
}
});
}
}

JavaScript validation before AJAX submission

I'm trying to validate a form before allowing my ajax submission,however I have two problems. The first problem being I don't know how to best go about validating before submission (most professional process). The second problem being, what is preventing my validation code I currently from working? Looking to become more efficient so all input is welcome. Thanks a ton.
$('#form-reg').on('submit', function(){
var bool = false;
var name = document.getElementById('#name-reg');
var email = document.getElementById('#email-reg');
console.log(name);
console.log(email);
if(!/[^a-zA-Z]/.test(name)){
bool = true;
}
else{
bool = false;
}
if(bool == true){
console.log(document.getElementById('#name-reg'));
$('#form-reg').slideUp('slow');
// serialize the form
var formData = $(this).serialize();
console.log(formData);
$.ajax({
type : 'POST',
url : 'register.php',
data : formData,
success: function() {
alert("Success");
},
error: function(xhr) {
alert("fail");
}
})
.done(function (data) {
document.getElementById('form-reg').reset();
})
.fail(function (error) {
alert("POST failed");
});
//return false;
}
else {
alert('try again');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" type="text/javascript">
<form id = "form-reg">
<label id ="x" for="name">Name</label>
<input id="name-reg" name="name"></br>
<label id = "y" for="email">Email</label>
<input id="email-reg" name="email"></br>
<input type="submit" value="submit" id = "submit-reg">
</form>
The issue with your code is you have to stop the form submit like:
$('#form-reg').on('submit', function(e){
e.preventDefault();
and after checking the validation, submit the form if validation succeeds.
Although it is a minor answer, I will post it anyway. The problem looks like the use of
var name = document.getElementById('#name-reg');
the # is causing the first problem and should be
var name = $('#name-reg').val();
$('#form-reg').on('submit', function(){
var bool = false;
var name = $('#name-reg').val();
var email = $('#email-reg').val();
console.log(name);
console.log(email);
if(!/[^a-zA-Z]/.test(name)){
bool = true;
}
else{
bool = false;
}
if(bool == true){
console.log($('#name-reg').val());
$('#form-reg').slideUp('slow');
// serialize the form
var formData = $(this).serialize();
console.log(formData);
$.ajax({
type : 'POST',
url : 'register.php',
data : formData,
success: function() {
alert("Success");
},
error: function(xhr) {
alert("fail");
}
})
.done(function (data) {
document.getElementById('form-reg').reset();
})
.fail(function (error) {
alert("POST failed");
});
//return false;
}
else {
alert('try again');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" type="text/javascript">
<form id = "form-reg">
<label id ="x" for="name">Name</label>
<input id="name-reg" name="name"></br>
<label id = "y" for="email">Email</label>
<input id="email-reg" name="email"></br>
<input type="submit" value="submit" id = "submit-reg">
</form>

Kindly Resolve the Issue in My AJAX Script For Contact Form [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am trying to achieve some AJAX Script By Which My Contact US Form Submit without Refreshing the Page
I have tried alot because i dont know where the mistake is in my AJAX Code.
This is my index.php File
<div id="response_result">
</div>
<form class="contact-form" method="POST" action="" onsubmit="return foo();" name="form" id="form_id">
<input type="text" name="contact_name" id="contact_name_id" />
<input type="text" name="contact_email" id="contact_email_id" />
<input type="text" id="contact_phone_id" name="contact_phone" />
<input type="text" id="contact_company_name_id" name="contact_company_name"/>
<input type="text" name="contact_subject" id="contact_subject_id"/>
<textarea name="contact_message" id="contact_message_id"></textarea>
<input type="submit" name="contact_submit" value="Submit Message" id="contact_submit_id" />
</form>
This is my PHP Code For That File
<?php
if(isset($_POST['contact_submit']))
{
$contact_name = $_POST['contact_name'];
$contact_email = $_POST['contact_email'];
$contact_phone = $_POST['contact_phone'];
$contact_company_name = $_POST['contact_company_name'];
$contact_subject = $_POST['contact_subject'];
$contact_message = $_POST['contact_message'];
if ((strlen($contact_message) < 5) OR (strlen($contact_message) > 500))
{
?>
<script>
alert('Your Message Should contains Characters between 5 to 500 ..... !!');
</script>
<?php
return false;
}
else if(($contact_name == "") OR ($contact_email == "") OR ($contact_phone == "") OR ($contact_company_name == "") OR ($contact_subject == "") OR ($contact_message == ""))
{
?>
<script>
alert('Please Supply Each Field .... !!');
</script>
<?php
}
else if($Object->save_contact_us_form_data($contact_name, $contact_email,$contact_phone, $contact_company_name, $contact_subject, $contact_message, $contact_date))
{
?>
<script>
alert('Data Submitted Successfully .... !!\nWe will get Back You Soon .... !!');
</script>
<?php
return true;
}
else
{
?>
<script>
alert('An Error Occured While Submitting Data .... !!');
</script>
<?php
return false;
}
}
?>
My PHP Code is Working Perfectly.
This is my AJAX Code (Not Working)
<script>
function foo()
{
var contact_name1 = document.getElementById( "contact_name_id" ).value;
var contact_email1 = document.getElementById( "contact_email_id" ).value;
var contact_phone1 = document.getElementById( "contact_phone_id" ).value;
var contact_company_name1 = document.getElementById( "contact_company_name_id" ).value;
var contact_subject1 = document.getElementById( "contact_subject_id" ).value;
var contact_message1 = document.getElementById( "contact_message_id" ).value;
$.ajax({
type: 'post',
url: 'Contact_Us.php',
data: {
contact_name:contact_name1,
contact_email:contact_email1,
contact_phone:contact_phone1,
contact_company_name:contact_company_name1,
contact_subject:contact_subject1,
contact_message:contact_message1
},
success: function (response) {
document.getElementById( "response_result" ).innerHTML = response;
}
});
}
</script>
When you submit your form with AJAX, make sure to suppress the default form submission logic using preventDefault. So your code should change to:
<form class="contact-form" method="POST" action="" name="form" id="form_id">
<input type="text" name="contact_name" id="contact_name_id" />
<input type="text" name="contact_email" id="contact_email_id" />
<input type="text" id="contact_phone_id" name="contact_phone" />
<input type="text" id="contact_company_name_id" name="contact_company_name"/>
<input type="text" name="contact_subject" id="contact_subject_id"/>
<textarea name="contact_message" id="contact_message_id"></textarea>
<input type="submit" name="contact_submit" value="Submit Message" id="contact_submit_id" />
</form>
<script>
$("#form_id").on("submit", function(e) {
e.preventDefault();
var contact_name1 = document.getElementById( "contact_name_id" ).value;
var contact_email1 = document.getElementById( "contact_email_id" ).value;
var contact_phone1 = document.getElementById( "contact_phone_id" ).value;
var contact_company_name1 = document.getElementById( "contact_company_name_id" ).value;
var contact_subject1 = document.getElementById( "contact_subject_id" ).value;
var contact_message1 = document.getElementById( "contact_message_id" ).value;
$.ajax({
type: 'post',
url: 'Contact_Us.php',
dataType: 'json',
data: {
contact_name:contact_name1,
contact_email:contact_email1,
contact_phone:contact_phone1,
contact_company_name:contact_company_name1,
contact_subject:contact_subject1,
contact_message:contact_message1,
contact_submit:"Submitted"
},
success: function (response) {
document.getElementById( "response_result" ).innerHTML = response;
}
});
});
</script>
I have added dataType to get the result as JSON. So let you PHP send JSON. (Note: Javascript alert won't work with AJAX). Hence your PHP code is:
<?php
$err = [];
if(isset($_POST['contact_submit']))
{
$contact_name = $_POST['contact_name'];
$contact_email = $_POST['contact_email'];
$contact_phone = $_POST['contact_phone'];
$contact_company_name = $_POST['contact_company_name'];
$contact_subject = $_POST['contact_subject'];
$contact_message = $_POST['contact_message'];
if ((strlen($contact_message) < 5) OR (strlen($contact_message) > 500))
{
$err[] = 'Your Message Should contains Characters between 5 to 500 ..... !!';
}
else if(($contact_name == "") OR ($contact_email == "") OR ($contact_phone == "") OR ($contact_company_name == "") OR ($contact_subject == "") OR ($contact_message == ""))
{
$err[] = "Please Supply Each Field .... !!";
}
else if($Object->save_contact_us_form_data($contact_name, $contact_email,$contact_phone, $contact_company_name, $contact_subject, $contact_message, $contact_date))
{
$err[] = 'Data Submitted Successfully .... !!\nWe will get Back You Soon .... !!';
}
else
{
$err[] = 'An Error Occured While Submitting Data .... !!';
}
echo json_encode($err);
}

Multiple AJAX forms with the same ID on the same page

I have two AJAX newsletter subscribe forms on the same page (top and bottom). Both forms have the same ID. The top form works perfectly, however I'm unable to get the alert messages to appear in the bottom form.
I found this question but wasn't sure how to implement the answer into my code.
Here's the form:
<div class="newsletter">
<form id="newsletter" class="newsletter-signup" action="" method="POST" accept-charset="UTF-8">
<input id="hero-section-newsletter-email-input" type="email" name="email">
<button class="button" type="submit">
Subscribe
</button>
<div id="newsletter-alert" style="display: none;" data-alert></div>
</form>
</div>
Here's the jQuery:
(function() {
'use strict';
var newsletterAlert = function(message) {
$('#newsletter-alert').text(message);
};
var isValidEmail = function(email) {
var pattern = new RegExp(/^[+a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);
return pattern.test(email);
};
$('#newsletter').on('submit', function(e) {
var data,
$form = $(this),
$email = $form.find('input[type="email"]');
e.preventDefault();
$('#newsletter-alert').show();
if ( !isValidEmail( $email.val() )) {
newsletterAlert('Looks like you entered an invalid email address! Please try again.');
} else {
newsletterAlert('Subscribing you now...');
data = $form.serialize();
$.ajax({
url: 'PATH_TO_SUBSCRIBE_PHP',
type: 'post',
data: data,
success: function(msg) {
if ( msg === 'success') {
newsletterAlert('Success! Please check your email to confirm.');
$email.val('');
} else {
newsletterAlert( msg );
}
},
error: function(msg) {
newsletterAlert('Error! ' + msg.statusText);
}
});
}
});
})();
Any help would be appreciated. Thanks
Don't use the same ID for the top and bottom forms.
An id must be unique in a document -- see MDN Docs.
Instead have two separate id's and reference them both in the one jQuery call when you are binding to the submit event:
$('#newsletter_top, #newsletter_bottom').on('submit', function(e) {
// ...
});
and in your HTML:
<form id="newsletter_top" ...>
</form>
<form id="newsletter_bottom" ...>
</form>

How to get name to save to mailchimp list with PHP+JS?

I am only getting the email address even though I entered my name on the form. Please forgive me I am not an expert in coding. I only know basic html and I just get some codes I find on the internet.
My newsletter form looks like this:
<form id="subscribe" class="form" action="<?=$_SERVER['PHP_SELF']; ?>" method="post">
<div class="form-group form-inline">
<input size="15" type="text" class="form-control required" id="NewsletterName"
name="NewsletterName" placeholder="Your name" />
<input size="25" type="email" class="form-control required" id="NewsletterEmail"
name="NewsletterEmail" placeholder="your#email.com" />
<input type="submit" class="btn btn-default" value="SUBSCRIBE" />
<span id="response">
<? require_once('assets/mailchimp/inc/store-address.php'); if($_GET['submit']){ echo
storeAddress(); } ?>
</span>
</div>
</form>
my js file looks like this:
jQuery(document).ready(function() {
jQuery('#subscribe').submit(function() {
// update user interface
jQuery('#response').html('<span class="notice_message">Adding email address...</span>');
var name = jQuery('#NewsletterName').val().split(' ');
var fname = name[0];
var lname = name[1];
if ( fname == '' ) { fname=""; }
if ( lname == '' || lname === undefined) { lname=""; }
// Prepare query string and send AJAX request
jQuery.ajax({
url: 'assets/mailchimp/inc/store-address.php',
data: 'ajax=true&email=' + escape(jQuery('#NewsletterEmail').val()),
success: function(msg) {
if (msg.indexOf("Success") !=-1) {
jQuery('#response').html('<span class="success_message">Success! You are now
subscribed to our newsletter!</span>');
} else {
jQuery('#response').html('<span class="error_message">' + msg + '</span>');
}
}
});
return false;
});
});
and my php file looks like this:
<?php
function storeAddress(){
require_once('MCAPI.class.php'); // same directory as store-address.php
// grab an API Key from http://admin.mailchimp.com/account/api/
$api = new MCAPI('mymailchimpapi');
$merge_vars = Array(
'EMAIL' => $_GET['email'],
'FNAME' => $_GET['fname'],
'LNAME' => $_GET['lname']
);
// grab your List's Unique Id by going to http://admin.mailchimp.com/lists/
// Click the "settings" link for the list - the Unique Id is at the bottom of that page.
$list_id = "myuniqueid";
if($api->listSubscribe($list_id, $_GET['email'], $merge_vars , $_GET['emailtype']) === true) {
// It worked!
return 'Success! Check your inbox or spam folder for a message containing a
confirmation link.';
}else{
// An error ocurred, return error message
return '<b>Error:</b> ' . $api->errorMessage;
}
}
// If being called via ajax, autorun the function
if($_GET['ajax']){ echo storeAddress(); }
?>
I don't know if i should also add
if($api->listSubscribe($list_id, $_GET['fname'], $merge_vars , $_GET['fname']) === true)
on the php file. Does anyone know where the problem is? Or is there something wrong in the JS file?
Your ajax query string only includes ajax=true&email= so $_GET['fname'] will be undefined. It would help if you did some validation of user input at server for security
A simpler way to compile the data from form is to use serialize()
jQuery('#subscribe').submit(function() {
var formData= $(this).serialize() ;
jQuery.ajax({
url: 'assets/mailchimp/inc/store-address.php',
data: formData,
success: function(....
........................
return false;
});
Reference: serialize() API Docs
Fixed!!!! Thanks Charlietfl for pointing out the problem. I Googled that part and was able to find a solution. I tried adding the serialize() code, but it's giving a page error upon clicking the submit button.
I added this on my JS file:
data: 'ajax=true&email=' + escape(jQuery('#NewsletterEmail').val()) + '&fname=' + escape(jQuery('#NewsletterName').val()),
so the whole code is:
jQuery(document).ready(function() {
jQuery('#subscribe').submit(function() {
// update user interface
jQuery('#response').html('<span class="notice_message">Adding email address...</span>');
var name = jQuery('#NewsletterName').val().split(' ');
var fname = name[0];
var lname = name[1];
if ( fname == '' ) { fname=""; }
if ( lname == '' || lname === undefined) { lname=""; }
// Prepare query string and send AJAX request
jQuery.ajax({
url: 'assets/mailchimp/inc/store-address.php',
data: 'ajax=true&email=' + escape(jQuery('#NewsletterEmail').val()) + '&fname=' +
escape(jQuery('#NewsletterName').val()),
success: function(msg) {
if (msg.indexOf("Success") !=-1) {
jQuery('#response').html('<span class="success_message">Success! You are now
subscribed to our newsletter!</span>');
} else {
jQuery('#response').html('<span class="error_message">' + msg + '</span>');
}
}
});
return false;
});
});

Categories