I am reading a chapter from PHP Ajax Cookbook. Here is the code:
HTML:
<form class='simpleValidation'>
<div class='fieldRow'>
<label for='title'>Title *</label>
<input type='text' id='title' name='title' class='required'>
</div>
<div class='fieldRow'>
<label for='url'>URL</label>
<input type='text' id='url' name='url' value='http://'>
</div>
<div class='fieldRow'>
<label for='labels'>Labels</label>
<input type='text' id='labels' name='labels'>
</div>
<div class='fieldRow'>
<label for='textarea'>Text *</label>
<textarea id='textarea' class='required'></textarea>
</div>
<div class='fieldRow'>
<input type='submit' id='formSubmitter' value='Submit'>
</div>
</form>
jQuery:
$(document).ready(function() {
var timerId = 0;
$('.required').keyup(function() {
clearTimeout(timerId);
timerId = setTimeout(function() {
ajaxValidation($(this));
}, 200);
});
});
var ajaxValidation = function (object) {
var $this = $(object);
var param = $this.attr('name');
var value = $this.val();
$.get(
'inputValidation.php',
{'param' : param, 'value' : value },
function (data) {
if (data.status == 'OK') {
validateRequiredInputs();
} else {
$this.addClass('failed');
}
},
'json'
);
var validateRequiredInputs = function() {
var numberOfMissingInputs = 0;
$('.required').each(function(i) {
var $item = $(this);
var itemValue = $item.val();
if (itemValue.length) {
$item.removeClass('failed');
} else {
$item.addClass('failed');
numberOfMissingInputs++;
}
});
var $submitButton = $('#formSubmitter');
if (numberOfMissingInputs > 0) {
$submitButton.prop('disabled', true)
} else {
$submitButton.prop('disabled', false)
}
}
}
PHP (inputValidation.php):
<?php
$result = array();
if (isset($_GET['param'])) {
$result['status'] = 'OK';
$result['message'] = 'Input is valid!';
} else {
$result['status'] = 'ERROR';
$result['message'] = 'Input IS NOT valid';
}
echo json_encode($result)
?>
When I start typing in the Title * field I get the following error from the console: Uncaught TypeError: Cannot read property 'toLowerCase' of undefined
Note: I am using jQuery 2.2.1
So far I have checked the code for mis-spelling but cannot find any.
The this bit in ajaxValidation($(this)) isn't what you think it is: it's actually window, since it's being called by setTimeout().
One solution is to assign $(this) to a variable outside the function, like so:
$('.required').keyup(function() {
clearTimeout(timerId);
var $this = $(this);
timerId = setTimeout(function() {
ajaxValidation($this);
}, 200);
});
Related
I am trying to get values Y and N on change switchery button, but with the following piece of codes whatever I've written, I am getting 'Y' all the time. please help
var lang_dis_button = document.querySelector('.lang-disable');
var lang_disable = new Switchery(lang_dis_button, { color: '#ED5565' });
var changeStatus = document.querySelector('.lang-disable')
, changeField = document.querySelector('#disabled_status');
changeStatus.onchange = function() {
if (changeStatus.checked) {
changeField.innerHTML = 'Disabled';
} else {
changeField.innerHTML = 'Active';
}
};
<input type="checkbox" class="lang-disable" name="disabled" id="disabled" value="Y"
<?php IF ($disabled == 'Y') { ?> checked><label id="disabled_status">Disabled</label><?php }
else { ?><label id="disabled_status">Active<?php } ?></label>
I'm trying to create a login page. I need to validate username and password but my js does not seem to work. I made it simpler now just for the sake to make it work. This is my html:
<script type="text/javascript" src = "js/checklogin.js"></script>
<h3>Already have an account?</h3>
<span id = "feedback"></span>
<form id = "login" action = "login.html" method = "post">
<label for = "name">User name:</label><br>
<input type = "text" name = "username " id = "username"><br>
<label for = "password">Password:</label><br>
<input type = "password" name = "password" id = "password"><br>
<input type="submit" value="Login">
</form>
And this is my js:
var elUsername = document.getElementById('username');
var elPassword = document.getElementById('password')
var elMsg = document.getElementById('feedback');
function checkFilled(length) {
if (length == "") {
elMsg.innerHTML = 'Please fill out this field';
} else {
document.getElementById("login").submit();
}
}
elUsername.addEventListener('blur', checkFilled(elUsername.value),false);
elPassword.addEventListener('blur', checkFilled(elPassword.value),false);
I still cannot make it to work. Also, how can i make it to appear as a pop up right on the textbox? Something that looks like this:
Error image
There's several issues with the code you had, so here's a complete example of the way I would do it (use the same HTML you already have). This works for me as tested in JSFiddle and below in the snippet.
var elUsername = document.getElementById('username');
var elPassword = document.getElementById('password')
var elMsg = document.getElementById('feedback');
var elForm = document.getElementById('login');
function checkFilled() {
if (elUsername.value == "" || elPassword.value == "") {
elMsg.innerHTML = 'Please fill out this field';
event.preventDefault();
} else {
elMsg.innerHTML = '';
}
}
if (elForm.addEventListener) {
elForm.addEventListener('submit', function() {
checkFilled();
}, false);
} else {
elForm.attachEvent('onsubmit', function() {
checkFilled();
});
}
if (elUsername.addEventListener) {
elUsername.addEventListener('blur', function() {
checkFilled();
}, false);
} else {
elUsername.attachEvent('onblur', function() {
checkFilled();
});
}
if (elPassword.addEventListener) {
elPassword.addEventListener('blur', function() {
checkFilled();
}, false);
} else {
elPassword.attachEvent('onblur', function() {
checkFilled();
});
}
<!--<script type="text/javascript" src = "js/checklogin.js"></script>-->
<h3>Already have an account?</h3>
<span id = "feedback"></span>
<form id = "login" action = "login.html" method = "post">
<label for = "name">User name:</label><br>
<input type = "text" name = "username " id = "username"><br>
<label for = "password">Password:</label><br>
<input type = "password" name = "password" id = "password"><br>
<input type="submit" value="Login">
</form>
How do I make multiple alerts or validation in 1 form?
There is an PHP array option for birthday (date, month, year in array), array choice for job, radio button for gender, checkboxs for passion (can select more than 1 but not empty) and upload file in one form.
Can it be done with a single script?
How to make exclusive alert message to each value, and focus on empty or unselected value?
My form:
<form action="" method="post">
<table width="589" border="1" align="center">
<tr>
<td colspan="3">INPUT DATA</td>
</tr>
<tr style="text-align: left">
<td width="128">NAME</td>
<td width="3">:</td>
<td width="394"><input type="text" name="name" id="name"></td>
</tr>
<tr style="text-align: left">
<td>BIRTHDAY</td>
<td>:</td>
<td><?php
echo "<select name='date' id='date'>";
echo "<option selected='selected'>DATE</option>";
for($a=1; $a<=31; $a+=1)
{
echo"<option value=$a> $a </option>";
}
echo "</select>";
echo "<select name='month' id='month'>";
echo "<option selected='selected'>MONTH</option>";
$month=array(1=>"Januari","Februari","Maret","April","Mei","Juni","July","Agustus","September","Oktober","November","Desember");
for($months=1; $months<=12; $months++)
echo "<option value='$months'>$month[$months]</option>";
echo "</select>";
$now=date('Y');
echo "<select id='year' name='year'>";
echo "<option selected='selected'>YEAR</option>";
for ($a=1980;$a<=$now;$a++)
{
echo "<option value='$a'>$a</option>";
}
echo "</select>";
?>
</td>
</tr>
<tr style="text-align: left">
<td>MAJOR</td>
<td>:</td>
<td> <select name="major" id="major">
echo "<option selected>--SELECT MAJOR--</option>";
<?php
$major=array("INFORMATION SYSTEM"=>"IS","COMPUTER ENGINERING"=>"CE");
foreach($major as $j=>$value)
{echo"<option value='".$value."'>".$j."</option>";
}
?>
</select></td>
</tr>
<tr style="text-align: left">
<td>JOB</td>
<td>:</td>
<td><select name="job" id="job">
echo "<option selected>--SELECT JOB--</option>";
<?php
$choise = array('Actuarial analyst','Business analyst','IT consultant','Network engineer');
for ($job=0;$job<=3;$job++)
{
echo "<option value='".$choise[$job]."'>
".$choise[$job]."</option>";
}
?>
</select></td>
</tr>
<tr style="text-align: left">
<td>SEX</td>
<td>:</td>
<td><input type="radio" name="sex" id="sex" value="MALE">
<label for="radio">MALE
<input type="radio" name="sex" id="sex2" value="FEMALE">
FEMALE</label></td>
</tr>
<tr style="text-align: left">
<td>PASSION</td>
<td>:</td>
<td><input type="checkbox" name="pass[]" value="WRITING">Writing
<input type="checkbox" name="pass[]" value="NETWORKING">Networking
<input type="checkbox" name="pass[]" value="PROGRAMMING">Programming
<input type="checkbox" name="pass[]" value="ENGINERING">Enginering
<input type="checkbox" name="pass[]" value="ETC">Etc</td>
</tr>
<tr style="text-align: left">
<td>FOTO</td>
<td>:</td>
<td><input type="file" name="photo" id="photo"></td>
</tr>
<tr>
<td colspan="3"><input type="submit" name="button" id="submit" value="SAVE"></td>
</tr>
</table>
<label for="name"></label>
</form>
Yo can learn more on validating forms in the following link: Form validation
You need to add a validator script to your form. this is a simple form, it is not working in snippet but you can see it working in this codepen
you just need to add required at the end of required fields
+function ($) {
'use strict';
// VALIDATOR CLASS DEFINITION
// ==========================
var Validator = function (element, options) {
this.$element = $(element)
this.options = options
options.errors = $.extend({}, Validator.DEFAULTS.errors, options.errors)
for (var custom in options.custom) {
if (!options.errors[custom]) throw new Error('Missing default error message for custom validator: ' + custom)
}
$.extend(Validator.VALIDATORS, options.custom)
this.$element.attr('novalidate', true) // disable automatic native validation
this.toggleSubmit()
this.$element.on('input.bs.validator change.bs.validator focusout.bs.validator', $.proxy(this.validateInput, this))
this.$element.on('submit.bs.validator', $.proxy(this.onSubmit, this))
this.$element.find('[data-match]').each(function () {
var $this = $(this)
var target = $this.data('match')
$(target).on('input.bs.validator', function (e) {
$this.val() && $this.trigger('input.bs.validator')
})
})
}
Validator.INPUT_SELECTOR = ':input:not([type="submit"], button):enabled:visible'
Validator.DEFAULTS = {
delay: 500,
html: false,
disable: true,
custom: {},
errors: {
match: 'Does not match',
minlength: 'Not long enough'
},
feedback: {
success: 'glyphicon-ok',
error: 'glyphicon-remove'
}
}
Validator.VALIDATORS = {
'native': function ($el) {
var el = $el[0]
return el.checkValidity ? el.checkValidity() : true
},
'match': function ($el) {
var target = $el.data('match')
return !$el.val() || $el.val() === $(target).val()
},
'minlength': function ($el) {
var minlength = $el.data('minlength')
return !$el.val() || $el.val().length >= minlength
}
}
Validator.prototype.validateInput = function (e) {
var $el = $(e.target)
var prevErrors = $el.data('bs.validator.errors')
var errors
if ($el.is('[type="radio"]')) $el = this.$element.find('input[name="' + $el.attr('name') + '"]')
this.$element.trigger(e = $.Event('validate.bs.validator', {relatedTarget: $el[0]}))
if (e.isDefaultPrevented()) return
var self = this
this.runValidators($el).done(function (errors) {
$el.data('bs.validator.errors', errors)
errors.length ? self.showErrors($el) : self.clearErrors($el)
if (!prevErrors || errors.toString() !== prevErrors.toString()) {
e = errors.length
? $.Event('invalid.bs.validator', {relatedTarget: $el[0], detail: errors})
: $.Event('valid.bs.validator', {relatedTarget: $el[0], detail: prevErrors})
self.$element.trigger(e)
}
self.toggleSubmit()
self.$element.trigger($.Event('validated.bs.validator', {relatedTarget: $el[0]}))
})
}
Validator.prototype.runValidators = function ($el) {
var errors = []
var deferred = $.Deferred()
var options = this.options
$el.data('bs.validator.deferred') && $el.data('bs.validator.deferred').reject()
$el.data('bs.validator.deferred', deferred)
function getErrorMessage(key) {
return $el.data(key + '-error')
|| $el.data('error')
|| key == 'native' && $el[0].validationMessage
|| options.errors[key]
}
$.each(Validator.VALIDATORS, $.proxy(function (key, validator) {
if (($el.data(key) || key == 'native') && !validator.call(this, $el)) {
var error = getErrorMessage(key)
!~errors.indexOf(error) && errors.push(error)
}
}, this))
if (!errors.length && $el.val() && $el.data('remote')) {
this.defer($el, function () {
var data = {}
data[$el.attr('name')] = $el.val()
$.get($el.data('remote'), data)
.fail(function (jqXHR, textStatus, error) { errors.push(getErrorMessage('remote') || error) })
.always(function () { deferred.resolve(errors)})
})
} else deferred.resolve(errors)
return deferred.promise()
}
Validator.prototype.validate = function () {
var delay = this.options.delay
this.options.delay = 0
this.$element.find(Validator.INPUT_SELECTOR).trigger('input.bs.validator')
this.options.delay = delay
return this
}
Validator.prototype.showErrors = function ($el) {
var method = this.options.html ? 'html' : 'text'
this.defer($el, function () {
var $group = $el.closest('.form-group')
var $block = $group.find('.help-block.with-errors')
var $feedback = $group.find('.form-control-feedback')
var errors = $el.data('bs.validator.errors')
if (!errors.length) return
errors = $('<ul/>')
.addClass('list-unstyled')
.append($.map(errors, function (error) { return $('<li/>')[method](error) }))
$block.data('bs.validator.originalContent') === undefined && $block.data('bs.validator.originalContent', $block.html())
$block.empty().append(errors)
$group.addClass('has-error')
$feedback.length
&& $feedback.removeClass(this.options.feedback.success)
&& $feedback.addClass(this.options.feedback.error)
&& $group.removeClass('has-success')
})
}
Validator.prototype.clearErrors = function ($el) {
var $group = $el.closest('.form-group')
var $block = $group.find('.help-block.with-errors')
var $feedback = $group.find('.form-control-feedback')
$block.html($block.data('bs.validator.originalContent'))
$group.removeClass('has-error')
$feedback.length
&& $feedback.removeClass(this.options.feedback.error)
&& $feedback.addClass(this.options.feedback.success)
&& $group.addClass('has-success')
}
Validator.prototype.hasErrors = function () {
function fieldErrors() {
return !!($(this).data('bs.validator.errors') || []).length
}
return !!this.$element.find(Validator.INPUT_SELECTOR).filter(fieldErrors).length
}
Validator.prototype.isIncomplete = function () {
function fieldIncomplete() {
return this.type === 'checkbox' ? !this.checked :
this.type === 'radio' ? !$('[name="' + this.name + '"]:checked').length :
$.trim(this.value) === ''
}
return !!this.$element.find(Validator.INPUT_SELECTOR).filter('[required]').filter(fieldIncomplete).length
}
Validator.prototype.onSubmit = function (e) {
this.validate()
if (this.isIncomplete() || this.hasErrors()) e.preventDefault()
}
Validator.prototype.toggleSubmit = function () {
if(!this.options.disable) return
var $btn = $('button[type="submit"], input[type="submit"]')
.filter('[form="' + this.$element.attr('id') + '"]')
.add(this.$element.find('input[type="submit"], button[type="submit"]'))
$btn.toggleClass('disabled', this.isIncomplete() || this.hasErrors())
}
Validator.prototype.defer = function ($el, callback) {
callback = $.proxy(callback, this)
if (!this.options.delay) return callback()
window.clearTimeout($el.data('bs.validator.timeout'))
$el.data('bs.validator.timeout', window.setTimeout(callback, this.options.delay))
}
Validator.prototype.destroy = function () {
this.$element
.removeAttr('novalidate')
.removeData('bs.validator')
.off('.bs.validator')
this.$element.find(Validator.INPUT_SELECTOR)
.off('.bs.validator')
.removeData(['bs.validator.errors', 'bs.validator.deferred'])
.each(function () {
var $this = $(this)
var timeout = $this.data('bs.validator.timeout')
window.clearTimeout(timeout) && $this.removeData('bs.validator.timeout')
})
this.$element.find('.help-block.with-errors').each(function () {
var $this = $(this)
var originalContent = $this.data('bs.validator.originalContent')
$this
.removeData('bs.validator.originalContent')
.html(originalContent)
})
this.$element.find('input[type="submit"], button[type="submit"]').removeClass('disabled')
this.$element.find('.has-error').removeClass('has-error')
return this
}
// VALIDATOR PLUGIN DEFINITION
// ===========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var options = $.extend({}, Validator.DEFAULTS, $this.data(), typeof option == 'object' && option)
var data = $this.data('bs.validator')
if (!data && option == 'destroy') return
if (!data) $this.data('bs.validator', (data = new Validator(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.validator
$.fn.validator = Plugin
$.fn.validator.Constructor = Validator
// VALIDATOR NO CONFLICT
// =====================
$.fn.validator.noConflict = function () {
$.fn.validator = old
return this
}
// VALIDATOR DATA-API
// ==================
$(window).on('load', function () {
$('form[data-toggle="validator"]').each(function () {
var $form = $(this)
Plugin.call($form, $form.data())
})
})
}(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form data-toggle="validator" action="contact_script" method="post" role="form">
<div class="form-group">
<input name="name" type="text" class="form-control input-lg" placeholder="Your Name" required>
</div>
<div class="form-group">
<input name="email" type="email" class="form-control input-lg" placeholder="E-mail" required>
</div>
<div class="form-group">
<input name="phone" type="text" class="form-control input-lg" placeholder="Contact No." required>
</div>
<div class="form-group">
<input name="subject" type="text" class="form-control input-lg" placeholder="Subject" required>
</div>
<div class="form-group">
<textarea name="message" class="form-control input-lg" rows="5" placeholder="Message"></textarea>
</div>
<button type="submit" class="btn wow bounceInRight" data-wow-delay="0.8s">Send</button>
</form>
I am using mailchimp and I have different lists on mail chimp. I have a dynamic webpage using PHP and for every different link, I have created a new list. I have a database table with the list urls and I have copied a code that mailchimp provides and changed url of form onsubmit to new url and also in javascript but it does not work. It only works with url through which the code was generated.
Here is the code that mailchimp provides
<div id="mc_embed_signup">
<form action="http://worldacademy.us7.list-manage.com/subscribe/post?u=3aff75083c84f012673478808&id=175e779a1a" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
<h2>Subscribe to our mailing list</h2>
<div class="indicates-required"><span class="asterisk">*</span> indicates required</div>
<div class="mc-field-group">
<label for="mce-EMAIL">Email Address <span class="asterisk">*</span>
</label>
<input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">
</div>
<div class="mc-field-group">
<label for="mce-NAME">First Name <span class="asterisk">*</span>
</label>
<input type="text" value="" name="NAME" class="required" id="mce-NAME">
</div>
<div id="mce-responses" class="clear">
<div class="response" id="mce-error-response" style="display:none"></div>
<div class="response" id="mce-success-response" style="display:none"></div>
</div> <!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
<div style="position: absolute; left: -5000px;"><input type="text" name="b_3aff75083c84f012673478808_175e779a1a" value=""></div>
<div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
</form>
</div>
Javascript code
<script type="text/javascript">
var fnames = new Array();var ftypes = new Array();fnames[0]='EMAIL';ftypes[0]='email';fnames[1]='NAME';ftypes[1]='text';
try {
var jqueryLoaded=jQuery;
jqueryLoaded=true;
} catch(err) {
var jqueryLoaded=false;
}
var head= document.getElementsByTagName('head')[0];
if (!jqueryLoaded) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = '//ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js';
head.appendChild(script);
if (script.readyState && script.onload!==null){
script.onreadystatechange= function () {
if (this.readyState == 'complete') mce_preload_check();
}
}
}
var err_style = '';
try{
err_style = mc_custom_error_style;
} catch(e){
err_style = '#mc_embed_signup input.mce_inline_error{border-color:#6B0505;} #mc_embed_signup div.mce_inline_error{margin: 0 0 1em 0; padding: 5px 10px; background-color:#6B0505; font-weight: bold; z-index: 1; color:#fff;}';
}
var head= document.getElementsByTagName('head')[0];
var style= document.createElement('style');
style.type= 'text/css';
if (style.styleSheet) {
style.styleSheet.cssText = err_style;
} else {
style.appendChild(document.createTextNode(err_style));
}
head.appendChild(style);
setTimeout('mce_preload_check();', 250);
var mce_preload_checks = 0;
function mce_preload_check(){
if (mce_preload_checks>40) return;
mce_preload_checks++;
try {
var jqueryLoaded=jQuery;
} catch(err) {
setTimeout('mce_preload_check();', 250);
return;
}
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://downloads.mailchimp.com/js/jquery.form-n-validate.js';
head.appendChild(script);
try {
var validatorLoaded=jQuery("#fake-form").validate({});
} catch(err) {
setTimeout('mce_preload_check();', 250);
return;
}
mce_init_form();
}
function mce_init_form(){
jQuery(document).ready( function($) {
var options = { errorClass: 'mce_inline_error', errorElement: 'div', onkeyup: function(){}, onfocusout:function(){}, onblur:function(){} };
var mce_validator = $("#mc-embedded-subscribe-form").validate(options);
$("#mc-embedded-subscribe-form").unbind('submit');//remove the validator so we can get into beforeSubmit on the ajaxform, which then calls the validator
options = { url: 'http://worldacademy.us7.list-manage.com/subscribe/post-json?u=3aff75083c84f012673478808&id=175e779a1a&c=?', type: 'GET', dataType: 'json', contentType: "application/json; charset=utf-8",
beforeSubmit: function(){
$('#mce_tmp_error_msg').remove();
$('.datefield','#mc_embed_signup').each(
function(){
var txt = 'filled';
var fields = new Array();
var i = 0;
$(':text', this).each(
function(){
fields[i] = this;
i++;
});
$(':hidden', this).each(
function(){
var bday = false;
if (fields.length == 2){
bday = true;
fields[2] = {'value':1970};//trick birthdays into having years
}
if ( fields[0].value=='MM' && fields[1].value=='DD' && (fields[2].value=='YYYY' || (bday && fields[2].value==1970) ) ){
this.value = '';
} else if ( fields[0].value=='' && fields[1].value=='' && (fields[2].value=='' || (bday && fields[2].value==1970) ) ){
this.value = '';
} else {
if (/\[day\]/.test(fields[0].name)){
this.value = fields[1].value+'/'+fields[0].value+'/'+fields[2].value;
} else {
this.value = fields[0].value+'/'+fields[1].value+'/'+fields[2].value;
}
}
});
});
$('.phonefield-us','#mc_embed_signup').each(
function(){
var fields = new Array();
var i = 0;
$(':text', this).each(
function(){
fields[i] = this;
i++;
});
$(':hidden', this).each(
function(){
if ( fields[0].value.length != 3 || fields[1].value.length!=3 || fields[2].value.length!=4 ){
this.value = '';
} else {
this.value = 'filled';
}
});
});
return mce_validator.form();
},
success: mce_success_cb
};
$('#mc-embedded-subscribe-form').ajaxForm(options);
});
}
function mce_success_cb(resp){
$('#mce-success-response').hide();
$('#mce-error-response').hide();
if (resp.result=="success"){
$('#mce-'+resp.result+'-response').show();
$('#mce-'+resp.result+'-response').html(resp.msg);
$('#mc-embedded-subscribe-form').each(function(){
this.reset();
});
} else {
var index = -1;
var msg;
try {
var parts = resp.msg.split(' - ',2);
if (parts[1]==undefined){
msg = resp.msg;
} else {
i = parseInt(parts[0]);
if (i.toString() == parts[0]){
index = parts[0];
msg = parts[1];
} else {
index = -1;
msg = resp.msg;
}
}
} catch(e){
index = -1;
msg = resp.msg;
}
try{
if (index== -1){
$('#mce-'+resp.result+'-response').show();
$('#mce-'+resp.result+'-response').html(msg);
} else {
err_id = 'mce_tmp_error_msg';
html = '<div id="'+err_id+'" style="'+err_style+'"> '+msg+'</div>';
var input_id = '#mc_embed_signup';
var f = $(input_id);
if (ftypes[index]=='address'){
input_id = '#mce-'+fnames[index]+'-addr1';
f = $(input_id).parent().parent().get(0);
} else if (ftypes[index]=='date'){
input_id = '#mce-'+fnames[index]+'-month';
f = $(input_id).parent().parent().get(0);
} else {
input_id = '#mce-'+fnames[index];
f = $().parent(input_id).get(0);
}
if (f){
$(f).append(html);
$(input_id).focus();
} else {
$('#mce-'+resp.result+'-response').show();
$('#mce-'+resp.result+'-response').html(msg);
}
}
} catch(e){
$('#mce-'+resp.result+'-response').show();
$('#mce-'+resp.result+'-response').html(msg);
}
}
}
</script>
Now I change this link in two location i.e. on form submit and in javacript from
http://worldacademy.us7.list-manage.com/subscribe/post-json?u=3aff75083c84f012673478808&id=175e779a1a&c=?
to the new link which is
http://worldtradeadvisors.us7.list-manage.com/subscribe/post?u=3aff75083c84f012673478808&id=0f6cad50b6
But this is not working. Any help will be much appreciated.
Thanks
I have solved this
The link in javascript needed to be changed from
http://worldtradeadvisors.us7.list-manage.com/subscribe/post?u=3aff75083c84f012673478808&id=0f6cad50b6
to
http://worldtradeadvisors.us7.list-manage2.com/subscribe/post-json?u=3aff75083c84f012673478808&id=0f6cad50b6&c=?
Given the following form:
<form class="email-form" action="" method="PUT" data-remote="true" data-method="put">
<ul>
<li>
<label for="sEmail1">
<input type="text" id="sEmail1" name="emails[]" value="d#google.com"
placeholder="">
</label>
</li>
<li>
<label for="sEmail2">
<input type="text" id="sEmail2" name="emails[]" value="d2#google.com"
placeholder="">
</label>
</li>
<li>
<label for="sEmail3">
<input type="text" id="sEmail3" name="emails[]" value="d3#google.com"
placeholder="">
</label>
</li>
</ul>
<button type="submit">Continue</button>
</form>
How can I use query to get the full list of emails and post it as follows to rails:
Parameters: {"emails"=>{"list"=>["d#google.com", "d2#google.com","d2#google.com"]}}
I have the following:
$.ajax({
type: 'POST',
url: '/send_invites',
data: {
emails : {
list : $('.email-form').serialize()
},
_method : 'PUT'
},
success : function() {
}
});
try this:
emails = new Object();
emails.list = [];
i = 0;
$("input[name^='email']").each(function(){
if(i < 3) {
emails.list[i] = $(this).val();
i++
}
})
alert(JSON.stringify(emails));
or:
parameters = new Object();
parameters.emails = new Object()
parameters.emails.list= [];
i = 0;
$("input[name^='email']").each(function(){
if(i < 3) {
parameters.emails.list[i] = $(this).val();
i++
}
})
alert(JSON.stringify(parameters));
http://jsfiddle.net/jgjpD/1/
here's a quick way to serialize a form by extending jQuery and adding a serializeObject method.
$(function() {
//form to object
$.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
//test it out
$('form').on('submit', function() {
var serialized = $(this).serializeObject();
console.log(serialized);
console.log(JSON.stringify(serialized));
return false;
});
});
Here is a way to do that
var listval = [];
$("input['name=emails\[\]']").each(function() {
listval.push($(this).val());
}