how to make a form submit without reloading the page [duplicate] - javascript

This question already has answers here:
Submit form without page reloading
(19 answers)
Closed 3 years ago.
how to make a form submit without reloading the page i know that i have to use ajax but how can I do this?
html file:
<form name='myform' method="post" action="send.php">
<span class="close-btn" id="close">✖</span>
<p>Введите свои контактные данные</p>
<p>Мы Вам перезвоним</p>
<input type="text" name="name" placeholder="Имя" maxlength="30">
<p class="Error" id="Error">Это поле обязательное для заполнения</p>
<p class="ErrorTwo" id="ErrorTwo">Некорректный ввод</p>
<input type="tel" name="phone" placeholder="Телефон" maxlength="13">
<p class="Error" id="telError">Это поле обязательное для заполнения</p>
<p class="ErrorTwo" id="telErrorTwo">Некорректный ввод</p>
<input type="submit" value="Отправить заявку" name="save" id="save" disabled>
<p>Данные не передаються третьим лицам</p>
</form>
php:
<?php
$ToEmail = 'myemail#gmail.com';
$EmailSubject = 'форма обратной связи';
$mailheader = "From: ".$_POST["email"]."\r\n";
$MESSAGE_BODY = "Имя: ".$_POST["name"]."";
$MESSAGE_BODY .= "Телефон: ".$_POST["phone"]."";
mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $mailheader) or die ("Failure");
?>
js:
/-----------------------------validation----------------------------------------/
//validation name
document.myform.name.onchange= function() {
var name = document.myform.name.value;
if (name === "") {
document.myform.name.removeAttribute("class", "ready");
document.myform.name.style.border = "1px solid #da3637";
document.getElementById("Error").style.display = "block";
document.getElementById("ErrorTwo").style.display = "none";
} else {
document.myform.name.style.border = "1px solid #509d12";
document.getElementById("Error").style.display = "none";
var pattern = new RegExp("^[a-z]+$", "i");
var isValid = this.value.search(pattern) >= 0;
if (!(isValid)) {
document.myform.name.style.border = "1px solid #da3637";
document.getElementById("ErrorTwo").style.display = "block";
document.myform.name.removeAttribute("class", "ready");
} else {
document.getElementById("ErrorTwo").style.display = "none";
document.myform.name.style.border = "1px solid #509d12";
document.myform.name.setAttribute("class", "ready");
}
}
};
//validation phone
document.myform.phone.onchange = function() {
var name = document.myform.phone.value;
if (name === "") {
document.myform.phone.removeAttribute("class", "ready");
document.myform.phone.style.border = "1px solid #da3637";
document.getElementById("telError").style.display = "block";
document.getElementById("telErrorTwo").style.display = "none";
} else {
document.myform.phone.style.border = "1px solid #509d12";
document.getElementById("telError").style.display = "none";
var pattern = new RegExp("^\\d+$");
var isValid = this.value.search(pattern) >= 0;
if (!(isValid)) {
document.myform.phone.style.border = "1px solid #da3637";
document.getElementById("telErrorTwo").style.display = "block";
} else {
document.getElementById("telErrorTwo").style.display = "none";
document.myform.phone.style.border = "1px solid #509d12";
document.myform.phone.setAttribute("class", "ready");
}
}
};
//filling the form
document.myform.onchange = function() {
var a = document.myform.name.getAttribute("class");
var c = document.myform.phone.getAttribute("class");
if (a === "ready" && c === "ready") {
document.getElementById("save").removeAttribute("disabled");
document.getElementById("save").style.cursor = "pointer";
document.getElementById("save").style.opacity = "1";
}
};

Use AJAX. I'd recommend enconding your form as JSON:
In HTML:
<form name='myForm' onsubmit='event.preventDefault(); sendForm("myForm");'>...</form>
In Js:
function sendForm(formName){
var http = new XMLHttpRequest();
http.open("POST","YourPage.php");
http.send(JSON.encodeForm(document.forms[formName]));
http.onreadystatechange = function(){
if(http.readyState == 4 && http.status == 200){
console.log(http.responseText); //PHP page's response handling
}
}
}
JSON.encodeForm = function(form){
var array = {};
for (key in form) {
var item=form[key];
if(form.hasOwnProperty(key) && item == "[object HTMLInputElement]"){
array[item.name]=item.value;
}
}
return JSON.stringify(array);
}
Then, in your PHP page:
$input = json_decode(file_get_contents("php://input") , true);
echo "Saved";

In my opinion better option is to validate data in the server-side file (some.php) and return response to client-side file.
php code will look like this:
$var = $_POST['some'];
if($var (bla bla bla))
{ echo 'ok.'; } else { echo 'Error'; }
response in your js file is echo message from your php file.
jsfiddle
EDIT (added input mask info):
if you need to validate your inputs in client-side file just use some input mask library (for example jquery input mask). This will be much easier way than creating own validation script.

Related

How to get value from input and comper value with local storage data to make email does not repeat?

container[i].input_email) /*this value from loacl storage */
function validEmail() {
for (var i = 0; i < container.length; i++) {
console.log(container[i].input_email);
if(container[i].input_email==input_email.value){
var element = document.getElementById("warnig");
element.innerHTML = 'email exiest';
}
}
}
Let's see if I understood right, you would check if the email input value is stored in localStorage and, if so, display a message that says email address already used...right?
<body>
<form>
<label for="email">Email:</label>
<input type="email" id="email">
<button type="submit">Submit</button>
<span class="message" style="display: block; font-weight: 700;"></span>
</form>
</body>
const form = document.querySelector('form');
const emailInput = document.querySelector('input');
const message = document.querySelector('.message');
function submitEmail() {
if (localStorage.getItem('email') === emailInput.value) {
message.style.color = 'red';
message.textContent = 'sorry email already exists';
} else {
localStorage.setItem('email', emailInput.value);
message.style.color = 'green';
message.textContent = 'email saved corectly';
}
}
form.addEventListener('submit', e => {
e.preventDefault();
submitEmail();
});

After submit a form, stay same page, show a word in the page

After clicking "submit", stay on the page.
Input data, like "computer number" and "profit", stay inside those blank square.
A word "Submitted", appear in the center of this page.
The following is my code, Please help, thank you!
<html>
<head>
<title></title>
</head>
<body>
<form name="form"
onsubmit="return validateForm()">
Computer Number:<br>
<input type="text" name="Computer" required><br>
<p>How much is your profit?
<input id="id1" name = "id1" required>
<button type = "button" onclick="myFunction()">My Answer</button>
<button type="button" id="btn1" onclick="Solution()" style="display:none;">Solution</button>
</p>
<p id="Q1"></p>
<script>
var errosCount = 0;
function myFunction() {
var x, text;
x = document.getElementById("id1").value;
if (isNaN(x) || x != 100) {
text = "Incorrect"; document.getElementById("Q1").style.color = "red";errosCount++;
} else {
text = "Correct"; document.getElementById("Q1").style.color = "green";
}
document.getElementById("Q1").innerHTML = text;
if(errosCount === 3){
errosCount = 0;
document.getElementById('btn1').style.display = 'block';
document.getElementById("Q1").innerHTML = '';
} else {
document.getElementById('btn1').style.display = 'none';
}
}
function Solution(){
text = "(P - w) * q<sub>o</sub> - I = (53 - 43) * 30 - 200 = 100"; document.getElementById("Q1").style.color = "red";
document.getElementById("Q1").innerHTML = text;
}
</script>
<input type="submit" value="Submit">
</form>
<script>
function validateForm() {
var q = document.forms["my form"]["Computer"].value;
if (q == "") {
alert("Computer Number is Missing!");
return false;}
var w = document.forms["my form"]["id1"].value;
if (w != "100") {
alert("Question 1 is Incorrect!");
return false;}
}
</script>
</body>
</html>
Firstly, you were having document.forms["my form"] which was invalid since your form name was form so I changed it to document.forms["form"].
And, on submit, I added return false at the bottom of the function to stay on the page. Also, before that, added "Submitted" text in the center of the page as shown below.
Here's working code snippet!
Hope that helps!
var errosCount = 0;
function myFunction() {
var x, text;
x = document.getElementById("id1").value;
if (isNaN(x) || x != 100) {
text = "Incorrect";
document.getElementById("Q1").style.color = "red";
errosCount++;
} else {
text = "Correct";
document.getElementById("Q1").style.color = "green";
}
document.getElementById("Q1").innerHTML = text;
if (errosCount === 3) {
errosCount = 0;
document.getElementById('btn1').style.display = 'block';
document.getElementById("Q1").innerHTML = '';
} else {
document.getElementById('btn1').style.display = 'none';
}
}
function Solution() {
text = "(P - w) * q<sub>o</sub> - I = (53 - 43) * 30 - 200 = 100";
document.getElementById("Q1").style.color = "red";
document.getElementById("Q1").innerHTML = text;
}
function validateForm() {
var q = document.forms["form"]["Computer"].value;
if (q == "") {
alert("Computer Number is Missing!");
return false;
}
var w = document.forms["form"]["id1"].value;
if (w != "100") {
alert("Question 1 is Incorrect!");
return false;
}
document.getElementById("submitted").innerHTML = "Submitted"
return false;
}
#submitted {
text-align: center
}
<form name="form" onsubmit="return validateForm()">
Computer Number:<br>
<input type="text" name="Computer"><br>
<p>How much is your profit?
<input id="id1" name="id1" required>
<button type="button" onclick="myFunction()">My Answer</button>
<button type="button" id="btn1" onclick="Solution()" style="display:none;">Solution</button>
</p>
<p id="Q1"></p>
<input type="submit" value="Submit">
</form>
<br/>
<div id="submitted">
</div>
Hello you should think abut using AJAX as you are sending a form.
This can be the button:
<button type="button"
onclick="validateForm('ajax_info.php', myFunction)"> Clic to Submit
</button>
And this the AJAX function:
function validateForm(url, cFunction) {
var xhttp;
xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
cFunction(this);
}
};
xhttp.open("GET", url, true); //can be POST
xhttp.send();
}
function myFunction(xhttp) {
document.getElementById("submited").innerHTML =
xhttp.responseText;
}

Using AJAX to call PHP function on button click

I am creating a file upload script.
What I wanted to do is to upload the file without refreshing the page
Here's my code:
upload.php
<?php
function upload(){
if(!empty($_FILES['file1']['name'][0])){
$files = $_FILES['file1'];
$uploaded = array();
$failed = array();
$allowed = array('jpg','txt','png');
foreach ($files ['name'] as $position => $file_name) {
$file_tmp = $files['tmp_name'][$position];
$file_size = $files['size'][$position];
$file_error = $files['error'][$position];
$file_ext = explode('.', $file_name);
$file_ext = strtolower(end($file_ext));
if (in_array($file_ext,$allowed)) {
if ($file_error === 0) {
if($file_size<=20971520){
$file_name_new = uniqid('',true).'.'.$file_ext;
$file_destination = 'test_uploads/'.$file_name_new;
if (move_uploaded_file($file_tmp, $file_destination)) {
$uploaded[$position] = $file_destination;
}else{
$failed[$position] = '[{$file_name}] failed to upload!';
}
}else{
$failed[$position] = '[{$file_name}] file is too large!';
}
}else {
$failed[$position] = '[{$file_name}] file extension is not allowed!';
}
}else{
$failed[$position] = '[{$file_name}] file extension not allowed!';
}
}
if (!empty($uploaded)) {
print_r($uploaded);
}
if (!empty($failed)) {
print_r($failed);
}
}
}
?>
<html>
<head>
</head>
<body>
<h2>Multiple File Upload </h2>
<form id="upload_form" enctype="multipart/form-data" method="post" action="upload.php">
<input type="file" name="file1[]" id="file1" multiple>
<input type="button" value="Upload File" onclick ="document.write('<?php upload(); ?>'')">
</form>
</body>
</html>
I wanted to do this on AJAX, I already searched for some examples but I want this to be simpler as possible.
By the way, is it possible for this to run without using any plugins or libraries?
I managed to find a solution for this. I separated the php script from the html and add a javascript file. I used ajax to call the PHP file to upload the files.
Here's my code;
index.php
<html>
<head>
<style type="text/css">
.upload{
width:500px;
background:#f0f0f0;
border: 1px solid #ddd;
padding: 20px;
}
.upload fieldset{
border: 0;
padding: 0;
margin-bottom:10px;
}
.uploads a, .uploads span{
display: block;
}
.bar{
width: 100%;
background: #eee;
padding: 3px;
margin-bottom:10px;
box-shadow: inset 0 1px 3px rgba(0,0,0,2);
border-radius: 3px;
box-sizing:border-box;
}
.barfill{
height: 20px;
display: block;
background: #ff6f01;
width:0px;
border-radius: 3px;
transition:width 0.8s ease;
}
.barfilltext{
color:#fff;
padding: 3px;
}
</style>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data" id="upload" class="upload">
<fieldset>
<legend>Upload Files</legend>
<input type="file" id="file" name="file[]" required multiple>
<input type="button" id="submit" value="Upload">
</fieldset>
<div class="bar">
<span class="barfill" id="pb"><span class="barfilltext" id="pt">40%</span></span>
</div>
<div id="uploads" class="uploads">
</div>
<script type="text/javascript" src="upload.js"></script>
<script type="text/javascript">
document.getElementById('submit').addEventListener('click', function(e){
e.preventDefault();
var f = document.getElementById('file'),
pb = document.getElementById('pb'),
pt = document.getElementById('pt');
app.uploader({
files:f,
progressBar:pb,
progressText:pt,
processor: 'upload.php',
finished: function(data){
var uploads = document.getElementById('uploads'),
succeeded = document.createElement('div'),
failed = document.createElement('div'), anchor, span, x;
if (data.failed.length) {
failed.innerHTML = '<p>The following files failed to upload</p>'
}
uploads.innerText = '' ;
for(x=0; x<data.succeeded.length; x = x+1){
anchor = document.createElement('a');
anchor.href = 'uploads/' + data.succeeded[x].file;
anchor.innerText = data.succeeded[x].name;
anchor.target = '_blank';
succeeded.appendChild(anchor);
}
for(x=0;x<data.failed.length; x=x+1){
span = document.createElement('span');
span.innerText = data.failed[x].name;
failed.appendChild(span);
}
uploads.appendChild(succeeded);
uploads.appendChild(failed);
},
error: function (){
console.log("Error");
}
});
});
</script>
</form>
</body>
</html>
upload.php
<?php
header('Content-Type: application/json');
$uploaded = [];
$allowed = ['jpg'];
$succeeded = [];
$failed = [];
if (!empty($_FILES['file'])) {
foreach ($_FILES['file']['name'] as $key => $name) {
if($_FILES['file']['error'][$key] === 0){
$temp = $_FILES['file']['tmp_name'][$key];
$ext = explode('.', $name);
$ext = strtolower(end($ext));
$file = md5_file($temp) . time() .'.'.$ext;
if (in_array($ext,$allowed) === true && move_uploaded_file($temp, "uploads/{$file}") === true) {
$succeeded [] = array('name' => $name, 'file' => $file);
# code...
}else{
$failed[] = array('name' => $name );
}
}else{
echo "Error";
}
}
}
if (!empty($_POST['ajax'])) {
echo json_encode(array(
'succeeded' => $succeeded,
'failed' =>$failed
));
}
?>
upload.js
var app = app || {};
(function (obj) {
"use stricts;"
//Private Methods
var ajax, getFormData, setProgress;
ajax = function(data){
var xmlhttp = new XMLHttpRequest(), uploaded;
xmlhttp.addEventListener('readystatechange', function(){
if (this.readyState === 4) {
if (this.status === 200) {
uploaded = JSON.parse(this.response);
if (typeof obj.options.finished === 'function') {
obj.options.finished(uploaded);
}
}else{
if (typeof obj.options.error === 'function') {
obj.options.error();
}
}
}
});
xmlhttp.upload.addEventListener('progress',function(){
var percent;
if (event.lengthComputable === true) {
percent = Math.round((event.loaded / event.total) * 100);
setProgress(percent);
}
});
xmlhttp.open('post', obj.options.processor);
xmlhttp.send(data);
};
getFormData = function(source){
var data = new FormData(), i;
for(i=0; i<source.length; i = i+1){
data.append('file[]',source[i]);
}
data.append('ajax', true);
return data;
};
setProgress = function (value){
if (obj.options.progressBar !== undefined) {
obj.options.progressBar.style.width = value ? value + '%': 0;
}
if (obj.options.progressText !== undefined) {
obj.options.progressText.innerText = value ? value + '%' : 0;
}
};
obj.uploader = function(options){
obj.options = options;
if (obj.options.files !== undefined) {
ajax(getFormData(obj.options.files.files));
}
}
}(app));
anyways, thanks for the help guys. those were gladly appreciated.
Thanks!
I think in your case the simplest way is to put it into an iframe. I assume you have all code in one PHP file which is called upload.php. You would get something like this:
<?php
//Check if the action is upload file. If it is start upload
if(isset($_GET['action']) && $_GET['action'] == 'uploadFile')
{
if(!empty($_FILES['file1']['name'][0])){
$files = $_FILES['file1'];
$uploaded = array();
$failed = array();
$allowed = array('jpg','txt','png');
foreach ($files ['name'] as $position => $file_name) {
$file_tmp = $files['tmp_name'][$position];
$file_size = $files['size'][$position];
$file_error = $files['error'][$position];
$file_ext = explode('.', $file_name);
$file_ext = strtolower(end($file_ext));
if (in_array($file_ext,$allowed)) {
if ($file_error === 0) {
if($file_size<=20971520){
$file_name_new = uniqid('',true).'.'.$file_ext;
$file_destination = 'test_uploads/'.$file_name_new;
if (move_uploaded_file($file_tmp, $file_destination)) {
$uploaded[$position] = $file_destination;
}else{
$failed[$position] = '[{$file_name}] failed to upload!';
}
}else{
$failed[$position] = '[{$file_name}] file is too large!';
}
}else {
$failed[$position] = '[{$file_name}] file extension is not allowed!';
}
}else{
$failed[$position] = '[{$file_name}] file extension not allowed!';
}
}
if (!empty($uploaded)) {
print_r($uploaded);
}
if (!empty($failed)) {
print_r($failed);
}
}
exit;
}
//Check if the action is getForm. If it is then display the form. This is to display the form in the iframe
elseif(isset($_GET['action']) && $_GET['action'] == 'getForm')
{
echo '
<form id="upload_form" enctype="multipart/form-data" method="post" action="upload.php?action=uploadFile">
<input type="file" name="file1[]" id="file1" multiple>
<input type="submit" value="Upload File">
</form>';
exit;
}
?>
<html>
<head>
</head>
<body>
<h2>Multiple File Upload </h2>
<!-- IFrame which loads the form !-->
<iframe id="uploadFileFrame" style="width:100%; height:auto; border:0px;" src="upload.php?action=getForm"></frame>
</body>
</html>
Showing uploaded image after successful upload
you just go through with this code I have already given the answer of this type of question

stop javascript to redirect after alert() function

I am using javascript to check file size. If it is bigger than 1m it shows an alert and after that it redirect to index page.
I want know how to make it stay in the same page without redirect and without refresh and keep all page information inserted by user as it is.
This is the code:
if(fileInput.files[0].size > 1050000) {
alert('File size is bigger than 1Mb!');
return false;
}
the hole code:
var handleUpload = function(event){
event.preventDefault();
event.stopPropagation();
var fileInput = document.getElementById('file');
var data = new FormData();
data.append('javascript', true);
if(fileInput.files[0].size > 1050000) {
//document.getElementById("image_id").innerHTML = "Image too big (max 1Mb)";
alert('File bigger than 1Mb!');
//window.location="upload.php";
return false;
}
for (var i = 0; i < fileInput.files.length; ++i){
data.append('file[]', fileInput.files[i]);
}
var request = new XMLHttpRequest();
request.upload.addEventListener('progress', function(event){
if(event.lengthComputable){
var percent = event.loaded / event.total;
var progress = document.getElementById('upload_progress');
while (progress.hasChildNodes()){
progress.removeChild(progress.firstChild);
}
progress.appendChild(document.createTextNode(Math.round(percent * 100) +' %'));
document.getElementById("loading-progress-17").style.width= Math.round(percent * 100) +'%';
}
});
request.upload.addEventListener('load', function(event){
document.getElementById('upload_progress').style.display = 'none';
});
request.upload.addEventListener('error', function(event){
alert('Upload failed');
});
request.addEventListener('readystatechange', function(event){
if (this.readyState == 4){
if(this.status == 200){
var links = document.getElementById('uploaded');
var uploaded = eval(this.response);
var div, a;
for (var i = 0; i < uploaded.length; ++i){
div = document.createElement('div');
a = document.createElement('a');
a.setAttribute('href', 'files/' + uploaded[i]);
a.appendChild(document.createTextNode(uploaded[i]));
div.appendChild(a);
links.appendChild(div);
}
}else{
console.log('server replied with HTTP status ' + this.status);
}
}
});
request.open('POST', 'upload.php');
request.setRequestHeader('Cache-Control', 'no-cache');
document.getElementById('upload_progress').style.display = 'block';
request.send(data);
}
window.addEventListener('load', function(event){
var submit = document.getElementById('submit');
submit.addEventListener('click', handleUpload);
});
the upload.php code with the html
<?php
foreach($_FILES['file']['name'] as $key => $name){
if ($_FILES['file']['error'][$key] == 0 && move_uploaded_file($_FILES['file']['tmp_name'][$key], "files/{$name}")){
$uploaded[] = $name;
}
}
if(!empty($_POST['javascript'])){
die(json_encode($uploaded));
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="upload.js"></script>
</head>
<body>
<div id="uploaded">
<?php
if (!empty($uploaded)){
foreach ($uploaded as $name){
echo '<div>',$name,'</div>';
}
}
?>
</div>
<div id="upload_progress"></div>
<div>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" id="file" name="file[]" />
<input type="submit" id="submit" value="upload" />
</form>
Thanks in advance
You may get rid of return it should work. Else, maybe you should try modals instead of alerts. They are more neat and pretty
Return false is preventing the redirect.
var val = $("#inputId").val();
if (val >= 0 || val <=9)
{
return true;
}
else
{
alert("Enter Digits Only");
return false;
}
```
Add event.preventDefault(); below the alert function.
This may help you to stay on the same page.

Mailchimp validation conflicting with Joomla slider

I am trying to embedd Mailchimp subscribe form on my Joomla site. However, it is conflicting with my 'Gavick PhotoSlide GK2'. to prevent this happened, I need to use the 'Naked form(no css or javascript)'. This will tick the user over to the MailChimp signup page when subscribing. But is it possible to have the validation working inline and not conflicting with my slider? This is the code:
<!-- Begin MailChimp Signup Form -->
<link href="http://cdn-images.mailchimp.com/embedcode/classic-081711.css" rel="stylesheet" type="text/css" />
<style type="text/css"><!--
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
--></style>
<div id="mc_embed_signup"><form action="http://thetrustsstadium.us4.list-manage1.com/subscribe/post?u=xxx&id=xxx" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank">
<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 name="EMAIL" class="required email" id="mce-EMAIL" type="email" /></div>
<div class="mc-field-group"><label for="mce-FNAME">First Name <span class="asterisk">*</span> </label> <input name="FNAME" class="required" id="mce-FNAME" type="text" /></div>
<div class="mc-field-group"><label for="mce-LNAME">Last Name <span class="asterisk">*</span> </label> <input name="LNAME" class="required" id="mce-LNAME" type="text" /></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>
<div class="clear"><input value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button" type="submit" /></div>
</form></div>
<script type="text/javascript"><!--
var fnames = new Array();var ftypes = new Array();fnames[0]='EMAIL';ftypes[0]='email';fnames[1]='FNAME';ftypes[1]='text';fnames[2]='LNAME';ftypes[2]='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 = 'http://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 script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://downloads.mailchimp.com/js/jquery.form-n-validate.js';
head.appendChild(script);
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;
}
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://thetrustsstadium.us4.list-manage.com/subscribe/post-json?u=xxx&id=xxx&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 {
this.value = fields[0].value+'/'+fields[1].value+'/'+fields[2].value;
}
});
});
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+'" mce_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>
<!--End mc_embed_signup-->
Sure it's possible, but there's no way to tell with just the code you posted. We'll need a link to a test page so we can take a look at the whole thing and see where the conflicts are. Before I spent a bunch of time messing with it though, I would try this component -
http://extensions.joomla.org/extensions/content-sharing/mailing-a-newsletter-bridges/13602
It comes with a sign up module and it seems to integrate pretty well with most 3rd party javascript. Try it before you do anything else, it may just work.
Otherwise you will likely have to rewrite the validation or switch to server side validation in order to fix the conflict.

Categories

Resources