ajaxupload el is undefined - ajax

i haved trying to use ajax upload image. here is my code
$(function () {
var btnUpload = $('#post_pd_thumnail');
if ($("#id").val()) var post_id = $("#id").val();
else var post_id = 0;
new AjaxUpload(btnUpload, {
action: site_root_domain + "/product/upload_image/" + post_id,
name: 'file_upload',
onSubmit: function (file, ext) {
if ($('#post_pd_thumnail').val() != '') {
if (!(ext && /^(jpg|png|jpeg|gif)$/.test(ext))) {
jAlert(lang_error_upload_avatar, lang_alert_notice);
return false;
}
}
$('#preview').html('<img style="margin-left:45px;margin-top:45px;" border="0" width="16" height="11" src="' + site_root_domain + '/templates/images/icons/loading_2.gif" />');
},
onComplete: function (file, response) {
if (!response) {
jAlert(lang_error_upload_avatar, lang_alert_notice);
} else {
img_upload = 1;
$('#preview').html(response);
}
return;
}
});
});
And my HTML is:
<div id="preview">{$preview}</div>
<div class="fileupload">
<input type="file" name="post_pd_thumnail" id="post_pd_thumnail" value="" />
</div>
<input type="hidden" name="id" id="id" value="{$data['product']['post_id']}" />
and i got this error when upload image "el is undefined" and the function does not work correctly can anyone help me solve this problem please

Try to change the file element to button like,
<div class="fileupload">
<input type="button" name="post_pd_thumnail" id="post_pd_thumnail" value="" />
</div>

Here is the solution.
* Attaches event to a dom element
*/
function addEvent(el, type, fn){
// 610 BUG
if (el == undefined) return;
if (w.addEventListener){
el.addEventListener(type, fn, false);
} else if (w.attachEvent){
var f = function(){
fn.call(el, w.event);
};
el.attachEvent('on' + type, f)
}
}

Related

How to refresh only particular portion of page afte I upload Image file

So here I want to get the latest data from dbs after uploading a image. with reloading the whole page again. Instead I want only to refresh the image div to show the latest uploaded image. I guess we can use Ajax for this, but I don't have any expertise in ajax so anyone who can help will be glad.
Thank you :)
Here is my code :-----------
.cshtml file
#for (int i = 0; i < Model.DailyMenuProducts.Count; i++)
{
<li class="list-group-item">
<input asp-for="#Model.DailyMenuProducts[i].IsChecked" type="checkbox" />
<label asp-for="#Model.DailyMenuProducts[i].ProductId"> #Model.DailyMenuProducts[i].ProductName</label>
<input type="hidden" asp-for="#Model.DailyMenuProducts[i].ProductId"/>
<input type="hidden" asp-for="#Model.DailyMenuProducts[i].ProductName" asp-route-productId/>
#if(#Model.DailyMenuProducts[i].DisplayImage != null)
{
<div class="uploadFile float-end" id="div_#Model.DailyMenuProducts[i].ProductId">
<label class="file-label">
<img src="data:image/jpeg;base64,#Model.DailyMenuProducts[i].DisplayImage" width="80" height="80" style="border: 1px solid #000000; cursor:pointer;"/>
</label>
<input asp-for="#Model.DailyMenuProducts[i].ProductImage" asp-for-ProductId="#Model.DailyMenuProducts[i].ProductId" type="file" class="productImage" id="#Model.DailyMenuProducts[i].ProductId" style="visibility:none; display:none"/>
</div> }
else
{
<div class="uploadFile float-end" id="div_#Model.DailyMenuProducts[i].ProductId">
<a class="file-label btn btn-primary text-white" type="button">
#SharedLocalizer[CashlessCloudConstants.cacheKey_UploadImage]
</a>
<input asp-for="#Model.DailyMenuProducts[i].ProductImage" asp-for-ProductId="#Model.DailyMenuProducts[i].ProductId" type="file" class="productImage" id="#Model.DailyMenuProducts[i].ProductId" style="visibility:none; display:none"/>
</div>
}
</li>
}
.js file
$(".file-label").click(function () {
var parent = $(this).parent();
var target = $(parent).find(".productImage");
$(target).click();
});
$(".uploadFile").on('change', function () {
console.log('new file uploaded')
var imagefiles = event.target.files;
var id = event.target.id;
$(this).find(".imageViewer").attr("src", window.URL.createObjectURL(imagefiles[0]));
var formData = new FormData();
formData.append("productId", id);
formData.append("productImage", imagefiles[0]);
console.log(formData.getAll("productId"));
console.log(formData.getAll("productImage"));
console.log(imagefiles[0])
$.ajax({
url: "/DailyMenuPlanner/AddPhoto",
contentType: false,
processData: false,
data: formData,
method: "POST",
success: function (result) {
window.onbeforeunload = null;
location.reload();
}
});
});
.cs file [Controller Method for AddPhoto]
[HttpPost]
public async Task<IActionResult> AddPhoto([FromForm] DailySelectedProductViewModel dataModel)
{
var userSession = await _userSessionCache.GetUserSessionWithUserIdAsync();
if (dataModel == null)
{
return View("ProductSelection", dataModel);
}
var existing = await _productImageApiService.GetSingleProductImage(userSession.TenantId,dataModel.ProductId);
ProductImages productImage = new ProductImages();
HttpRequest request = HttpContext.Request;
IFormFile file = dataModel.ProductImage;
if (file.Length > 0)
{
using (var memoryStream = new MemoryStream())
{
await file.CopyToAsync(memoryStream);
byte[] imageAsArray = memoryStream.ToArray();
productImage.ProductImage = imageAsArray;
}
productImage.ProductId = dataModel.ProductId;
}
if (existing.Content != null)
{
await _productImageApiService.Delete(userSession.TenantId,dataModel.ProductId);
var createProductPhoto = await _productImageApiService.Create(userSession.TenantId, productImage);
}
else
{
var createProductPhoto = await _productImageApiService.Create(userSession.TenantId, productImage);
}
return Ok();
}

Submit form within bootstrap modal using ajax and codeigniter without page change

I am trying to submit a form within a bootstrap modal using ajax. And my form is successfully submitted, but the success statements within ajax are not executed. The page is redirected to a blank page saying {"msg":"ok"}.
I am pasting the code from controller and view. Please help.
Controller
$update_profile_details = $this->userp_m->edit_profile_m($uname,$uemail,$data1,$new_email);
if($update_profile_details == true)
{
$status['msg'] = 'ok';
}
else
{
$status['msg'] = 'err';
}
echo json_encode ($status);
View
$(document).ready(function()
{
$("#myForm").submit(function(e)
{
e.preventDefault();
var reg = /^[A-Z0-9._%+-]+#([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
var name = $('#inputName').val();
var email = $('#inputEmail').val();
if (name.trim() == '') {
alert('Please enter your name.');
$('#inputName').focus();
return false;
} else if (email.trim() == '') {
alert('Please enter your email.');
$('#inputEmail').focus();
return false;
} else if (email.trim() != '' && !reg.test(email)) {
alert('Please enter valid email.');
$('#inputEmail').focus();
return false;
} else {
var fd = new FormData(this);
$.ajax({
type: 'POST',
url: $('#myForm').attr('action'),
dataType: "json",
data: $('#myform').serialize(), fd,
contentType: false,
cache: false,
processData:false,
beforeSend: function()
{
$('.submitBtn').attr("disabled", "disabled");
$('.modal-body').css('opacity', '.5');
},
success: function(status)
{
alert(status);
if (status.msg == 'ok') {
$('#inputName').val('');
$('#inputEmail').val('');
$('.statusMsg').html('<span style="color:green;">Changes have been saved successfully.</p>');
} else
{
$('.statusMsg').html('<span style="color:red;">Some problem occurred, please try again.</span>');
}
$('.submitBtn').removeAttr("disabled");
$('.modal-body').css('opacity', '');
},
error: function(status)
{
alert("Some error, please try again");
}
});
}
});
HTML
<form id="myform" method="post" enctype="multipart/form-data" action="<?php echo site_url('User/user_index_c/edit_profile_c'); ?>">
<label>Full Name : </label>
<input class="name_styling" type="text" placeholder="Enter name" id="inputName" name="uname">
<label>Email Id : </label>
<input class="email_styling" type="email" placeholder="Enter email" id="inputEmail" name="new_email">
<div class="controls">
<label>Profile Photo : </label>
<input name="file1" type="file" id="image_file" />
<img id="blah" class="logoupload" src="#" alt="your image" />
<span class="filename"></span>
</div>
<center><input class="submitBtn" id="submit" type="submit" value="Save Changes" name="submit" ></center>
</form>
Instead of function you have to write jquery code like below.
Remove function submitContactForm(e){}
Add $(document).on('submit', '#myform', function(e) { })
$(document).on('submit', '#myform', function(e) {
e.preventDefault();
var reg = /^[A-Z0-9._%+-]+#([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
var name = $('#inputName').val();
var email = $('#inputEmail').val();
if (name.trim() == '') {
alert('Please enter your name.');
$('#inputName').focus();
return false;
} else if (email.trim() == '') {
alert('Please enter your email.');
$('#inputEmail').focus();
return false;
} else if (email.trim() != '' && !reg.test(email)) {
alert('Please enter valid email.');
$('#inputEmail').focus();
return false;
} else {
$('.submitBtn').prop("disabled", true);
$('.modal-body').css('opacity', '.5');
var myFormData = new FormData();
e.preventDefault();
var inputs = $('#myForm input[type="file"]');
$.each(inputs, function(obj, v) {
var file = v.files[0];
var filename = $(v).attr("data-filename");
var name = $(v).attr("name");
myFormData.append(name, file, filename);
});
var inputs = $('#myForm input[type="text"],input[type="email"]');
$.each(inputs, function(obj, v) {
var name = $(v).attr("name");
var value = $(v).val();
myFormData.append(name, value);
});
var xhr = new XMLHttpRequest;
xhr.open('POST', '<?php echo base_url(); ?>index.php/User/user_index_c/edit_profile_c/', true);
xhr.send(myFormData);
xhr.onload = function() {
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
$('#inputName').val('');
$('#inputEmail').val('');
$('.statusMsg').html('<span style="color:green;">Changes have been saved successfully.</p>');
$('.submitBtn').removeAttr("disabled");
$('.modal-body').css('opacity', '');
}
}
};
}
});
Let me know if it not works.
try this: in your file.js:
$(document).ready(function () {
$('#submit').click(function () {
var name= $("#inputName").val();
var mail = $("#inputEmail").val();
var img = $("#image_file").val();
$.post("User/user_index_c/edit_profile_c", {send_name:name,send_mail:mail, send_igm:img},
function (data) {
if (data.trim() != "ok") {
alert('error');
}
else{
//action for "success" exemple: alert("send with success!"); and insert a code for clean fields
}
});
});
});
in your controller's method:
$uname = $this->input->post("send_name");
$uemail = $this->input->post("send_mail");
$new_email = $this->input->post("send_igm");
$update_profile_details = $this->userp_m->edit_profile_m($uname,$uemail,$data1,$new_email);
if($update_profile_details == true){
echo 'ok';
}
else
{
echo 'err';
}
I hope I have helped

Uploading files with VueJS, axios and Laravel

Hello I am building one project. Where user can send up to 5 images and up to 10 songs with the text. But when I send request to the server, where I handle with Laravel, I can't get those files.
// my data object from VueJS
data() {
return {
formData: new FormData(),
pikir: {
body: '',
},
isLoading: false,
images: [],
songs: [],
}
}
// imagePreview method from VuejS
imagePreview(event) {
let input = event.target;
if (input.files[0]) {
if (input.files.length <= 5) {
for (let i = 0; i < input.files.length; i++) {
let reader = new FileReader();
reader.onload = e => {
this.images.push(e.target.result);
}
reader.readAsDataURL(input.files[i]);
}
Array.from(Array(event.target.files.length).keys())
.map(x => {
this.formData
.append('images',
event.target.files[x], event.target.files[x].name);
});
} else {
alert('You can upload up to 5 images');
}
}
}
// musicPreview method from VueJS
musicPreview(event) {
let input = event.target;
if (input.files.length <= 5) {
for (let i = 0; i < input.files.length; i++) {
this.songs.push(input.files[i].name.replace('.mp3', ''));
}
Array.from(Array(event.target.files.length).keys())
.map(x => {
this.formData
.append('songs',
event.target.files[x], event.target.files[x].name);
});
} else {
alert('You can upload up to 10 songs');
}
}
// sharePikir method from VueJS
sharePikir() {
this.formData.append('body', this.pikir.body);
axios.put('/api/pikirler', this.formData)
.then(response => {
this.pikir.body = '';
this.isLoading = false;
})
.catch(() => {
this.isLoading = false;
});
},
<form action="#" id="share-pikir">
<label for="pikir">
Näme paýlaşmak isleýärsiňiz? {{ pikirSymbolLimit }}
</label>
<input type="text" name="pikir" id="pikir" maxlength="255"
v-model="pikir.body"
#keyup="handleSymbolLimit()">
<div class="emoji">
<i class="fa fa-smile-o"></i>
</div>
<div class="photo-music left">
<label for="music-upload">
<i class="fa fa-music"></i>
</label>
<input type="file" name="songs[]" id="music-upload"
accept="audio/mp3"
#change="musicPreview($event)"
multiple>
<i class="divider"></i>
<label for="image-upload">
<i class="fa fa-image"></i>
</label>
<input type="file" name="images[]" id="image-upload"
#change="imagePreview($event)"
multiple>
</div>
<div class="share right">
<button
:class="{ 'btn-medium': true, 'is-loading': isLoading }"
#click.prevent="sharePikir($event)">
Paýlaşmak
</button>
</div>
</form>
I put my front end stuff above and in my Laravel side I just return all requests:
public function store(){
return request()->all();
}
And these are what I get from request:
I couldn't found what is wrong. Thank you in advance.
Oh yeah! you're missing this part. You need to define this.
axios.defaults.headers.post['Content-Type'] = 'multipart/form-data';
this my solutuion
export default {
data (){
return {
attachment : { name : null,file: null }
}
},
methods : {
onFileChange(event) {
this.attachment.file = event.target.files[0]
},
attachmentCreate() {
var form = new FormData();
form.append('name',this.attachment.name);
form.append('file',this.attachment.file);
this.$http.post('attachment',form).then(response=>{
console.log("oke")
})
},
}
}
<input type="file" class="form-control" #change="onFileChange">
Check this post, maybe your problem is solved:
[https://stackoverflow.com/questions/55895941/success-upload-file-via-postman-but-fail-on-front-end-vue/73698108#73698108][1]

Can't prevent file upload on failed validation using jQuery Form plugin

Here's my form:
<form id="frmUpload" action="../scripts/upload.php" method="post" enctype="multipart/form-data">
<div id="sermonInfo">
File: <input type="file" id="uploadedFile" name="uploadedFile" class="error"><br>
<br>
Title: <input type="text" id="title" name="sermonTitle" size="35" maxlength="100">
</div>
</form>
<div id="uploadInfo">
<div class="progress">
<div class="statusBar" style="width: 0%;"></div>
<div class="percent">0%</div>
</div>
<div id="status"></div>
<br>
<div id="required">Only mp3 files are allowed!</div>
</div>
And here's the JS I'm using:
<script>
$(function() {
/*
* Upload
*/
// Reset validation and progress elements
var formValid = true,
percentVal = '0%';
$('#uploadedFile, #title').removeClass('error');
$('#status, #required').empty().removeClass();
$('.statusBar').width(percentVal)
$('.percent').html(percentVal);
$('form').ajaxForm({
beforeSend: function(e) {
if (!ValidateUploadForm()) {
formValid = false;
console.log('validateuploadform returned false');
} else {
console.log('validateuploadform returned true');
formValid = true;
}
console.log('in beforeSend. formValid: ' + formValid);
if (!formValid) {
return false;
}
},
uploadProgress: function(event, position, total, percentComplete) {
console.log('in uploadProgress function. formValid: ' + formValid);
if (formValid) {
var percentVal = percentComplete + '%';
$('.statusBar').width(percentVal)
$('.percent').html(percentVal);
}
},
complete: function(xhr) {
console.log('in complete function. formValid: ' + formValid);
if (formValid) {
console.log('xhr.responseText: ' + xhr.responseText);
console.log('formValid: ' + formValid);
if (xhr.responseText === 'success') {
$('.statusBar').width('100%');
$('.percent').html('100%');
$('#status').html('Successfully uploaded the file.').addClass('successUpload');
// Clear the form
ClearForm();
} else if (xhr.responseText === 'fail') {
$('#status').html('There was a problem uploading the file. Try again.<br>If the problem persists, contact your system administrator.').addClass('errorUpload');
}
}
}
}); // End Upload Status Bar
});
function ValidateUploadForm() {
// Reset errors and clear message
$('#uploadedFile, #title').removeClass('error');
$('#required').empty();
var result = true;
title = $('#title').val(),
fileName = $('#uploadedFile').val();
extension = $('#uploadedFile').val().split('.').pop();
if (fileName !== '' && extension !== 'mp3') {
$('#uploadedFile').addClass('error');
$('#required').html('Only mp3 files are allowed!');
return false;
} else if (fileName === '') {
result = false;
} else if (title === '') {
$('#title').addClass('error');
result = false;
}
console.log('returning ' + result + ' from the validateuploadform function');
if (!result) { $('#required').html('All fields are required.'); }
return result;
}
function ClearForm() {
$('#uploadedFile, #title').val('').removeClass();
}
</script>
As you can see, I'm using console output the keep an eye on what's going on.
My problem is, if a file is selected, the file still uploads, whether formValid (in beforeSend) is true or false.
I've tried adding preventDefault before return false;. I've also tried clearing the file input in the if (!formValid) {} block. As you can see, I've wrapped the uploadProgress and complete functions to check if formValid is false. If the console output in uploadProgress shows formValid to be false, the file still uploads.
What am I missing here? How can I prevent the file upload if the validation fails?
I finally figured out the issue: I was comparing my script to some examples online and noticed that the examples' callback was named beforeSubmit, but I was using beforeSend.
Oddly, the validation code was still executing, but returning false didn't stop the upload.
Basically, it looks like you might be missing the jquery.form.js extension. Without JavaScript console output, I can only guess that that ought to be the problem. Try the following (entire) page as a reference, where stopping the upload works:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Test Page</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js" type="text/javascript">
</script>
<script src="http://malsup.github.com/jquery.form.js" type="text/javascript">
</script>
<style type="text/css">
div.c1 {width: 0%;}
</style>
</head>
<body>
<form id="frmUpload" action="%3C?php%20basename(__FILE__,%20'.php');%20?%3E" method="post" enctype="multipart/form-data" name="frmUpload">
<div id="sermonInfo">File: <input type="file" id="uploadedFile" name="uploadedFile" class="error"><br>
<br>
Title: <input type="text" id="title" name="sermonTitle" size="35" maxlength="100"></div>
<input type="submit" value="Submit"></form>
<div id="uploadInfo">
<div class="progress">
<div class="statusBar c1"></div>
<div class="percent">0%</div>
</div>
<div id="status"></div>
<br>
<div id="required">Only mp3 files are allowed!</div>
</div>
<script type="text/javascript">
$(function() {
/*
* Upload
*/
// Reset validation and progress elements
var formValid = true,
percentVal = '0%';
$('#uploadedFile, #title').removeClass('error');
$('#status, #required').empty().removeClass();
$('.statusBar').width(percentVal)
$('.percent').html(percentVal);
$('form').ajaxForm({
beforeSend: function(e) {
if (!ValidateUploadForm()) {
formValid = false;
console.log('validateuploadform returned false');
} else {
console.log('validateuploadform returned true');
formValid = true;
}
console.log('in beforeSend. formValid: ' + formValid);
if (!formValid) {
return false;
}
},
uploadProgress: function(event, position, total, percentComplete) {
console.log('in uploadProgress function. formValid: ' + formValid);
if (formValid) {
var percentVal = percentComplete + '%';
$('.statusBar').width(percentVal)
$('.percent').html(percentVal);
}
},
complete: function(xhr) {
console.log('in complete function. formValid: ' + formValid);
if (formValid) {
console.log('xhr.responseText: ' + xhr.responseText);
console.log('formValid: ' + formValid);
if (xhr.responseText === 'success') {
$('.statusBar').width('100%');
$('.percent').html('100%');
$('#status').html('Successfully uploaded the file.').addClass('successUpload');
// Clear the form
ClearForm();
} else if (xhr.responseText === 'fail') {
$('#status').html('There was a problem uploading the file. Try again.<br>If the problem persists, contact your system administrator.').addClass('errorUpload');
}
}
}
}); // End Upload Status Bar
});
function ValidateUploadForm() {
// Reset errors and clear message
$('#uploadedFile, #title').removeClass('error');
$('#required').empty();
var result = true;
title = $('#title').val(),
fileName = $('#uploadedFile').val();
extension = $('#uploadedFile').val().split('.').pop();
if (fileName !== '' && extension !== 'mp3') {
$('#uploadedFile').addClass('error');
$('#required').html('Only mp3 files are allowed!');
return false;
} else if (fileName === '') {
result = false;
} else if (title === '') {
$('#title').addClass('error');
result = false;
}
console.log('returning ' + result + ' from the validateuploadform function');
if (!result) { $('#required').html('All fields are required.'); }
return result;
}
function ClearForm() {
$('#uploadedFile, #title').val('').removeClass();
}
</script>
</body>
</html>
As a side note, you might want to use
extension = $('#uploadedFile').val().split('.').pop().toLowerCase();
to make sure that the form also accepts MP3, as this is seen relatively often too in the wild.
If this doesn't fix your problem, it would help if you could upload the full HTML of one page in question.
UPDATE
With respect to the uploaded files, you have a simple typo in line 91 of testUpload.php:
if ((fileName === '') || (extension !== 'mp3'))
should be
if ((fileName === '') || (extension !== 'mp3')) {

Ajax Contact form validation and submit

I'm trying to make a HTML contact form. Here's my code
`Get in Touch
<p class="success-sending-message">Thank you, your message has been sent!</p>
<p class="error-sending-message">There has been an error, please try again.</p>
<div id="contact-form">
<form action="" id="contactForm" class="styled" method="post">
<label for="contact_name">Name</label>
<input type="text" tabindex="3" id="contact_name" name="contact_name" value="" class="requiredField textbox" />
<label for="contact_email">Email</label>
<input type="text" tabindex="4" id="contact_email" name="contact_email" value="" class="requiredField email textbox" />
<label for="contact_subject">Subject</label>
<input type="text" tabindex="5" id="contact_subject" name="contact_subject" value="" class="requiredField textbox" />
<label for="contact_message">Your Message</label>
<div class="textarea-wrap">
<textarea cols="65" rows="9" tabindex="6" id="contact_message" name="contact_message" class="requiredField"></textarea>
</div>
<div class="form-section">
<button class="button" tabindex="7" type="submit" id="born-submit" name="born-submit">Send Message</button>
<input type="hidden" name="submitted" id="submitted" value="true" />
<span class="sending-message"><img src="css/images/loading-light.gif" /> Sending...</span>
</div>
</form>
</div>`
And here's my validation script
$(window).load(function() {
/* Ajax Contact form validation and submit */
jQuery('form#contactForm').submit(function() {
jQuery(this).find('.error').remove();
var hasError = false;
jQuery(this).find('.requiredField').each(function() {
if(jQuery.trim(jQuery(this).val()) == '') {
if (jQuery(this).is('textarea')){
jQuery(this).parent().addClass('input-error');
} else {
jQuery(this).addClass('input-error');
}
hasError = true;
} else if(jQuery(this).hasClass('email')) {
var emailReg = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if(!emailReg.test(jQuery.trim(jQuery(this).val()))) {
jQuery(this).addClass('input-error');
hasError = true;
}
}
});
if(!hasError) {
jQuery(this).find('#born-submit').fadeOut('normal', function() {
jQuery(this).parent().parent().find('.sending-message').show('normal');
});
var formInput = jQuery(this).serialize();
var contactForm = jQuery(this);
jQuery.ajax({
type: "POST",
url: jQuery(this).attr('action'),
data: formInput,
success: function(data){
contactForm.parent().fadeOut("normal", function() {
jQuery(this).prev().prev().show('normal'); // Show success message
});
},
error: function(data){
contactForm.parent().fadeOut("normal", function() {
jQuery(this).prev().show('normal'); // Show error message
});
}
});
}
return false;
});
jQuery('.requiredField').blur(function() {
if(jQuery.trim(jQuery(this).val()) != '' && !jQuery(this).hasClass('email')) {
if (jQuery(this).is('textarea')){
jQuery(this).parent().removeClass('input-error');
} else {
jQuery(this).removeClass('input-error');
}
} else {
if (jQuery(this).is('textarea')){
jQuery(this).parent().addClass('input-error');
} else {
jQuery(this).addClass('input-error');
}
}
});
jQuery('.email').blur(function() {
emailReg = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if(emailReg.test(jQuery.trim(jQuery(this).val())) && jQuery(this).val() != '') {
jQuery(this).removeClass('input-error');
} else {
jQuery(this).addClass('input-error');
}
});
jQuery('.requiredField, .email').focus(function(){
if (jQuery(this).is('textarea')){
jQuery(this).parent().removeClass('input-error');
} else {
jQuery(this).removeClass('input-error');
}
});
});
My form is working properly, After filling details It is showing me "Thank you, your message has been sent!" But where is this message going, I don't have any of the process.php file and all. I want that email should be send to my email id.
Bonjour ... Look in the firebug or chrome developper tools console to see the post trace.
In your php file, you can put echos or var_dump to be sure all it's ok.
Another thing ... the form action is empty.
Currently there's no where it is going. Give where it needs to go in the action="" attribute of the <form>. And also, in the actioned URL, typically, a PHP file, give this code:
<?php
if (count($_POST))
{
$name = $_POST["contact_name"];
$email = $_POST["contact_email"];
$subject = $_POST["contact_subject"];
$message = $_POST["contact_message"];
$mail = "Name: $name\nEmail: $email\nSubject: $subject\nMessage: $message";
if (mail("mymail#domain.com", "New Mail from Contact Form", $mail))
die ("OK");
else
die ("Fail");
}
?>
Also, you need to make a small correction in your JavaScript AJAX Call. Replace this way:
jQuery.ajax({
type: "POST",
url: jQuery(this).attr('action'),
data: formInput,
success: function(data){
if (data == "OK")
contactForm.parent().fadeOut("normal", function() {
jQuery(this).prev().prev().show('normal'); // Show success message
});
else
alert ("Message not sent!");
},
error: function(data){
contactForm.parent().fadeOut("normal", function() {
jQuery(this).prev().show('normal'); // Show error message
});
}
});
Test if your server supports SMTP through PHP Script
Create a small file, which has this content, say mail.php:
<?php
var_dump(mail("yourmail#gmail.com", "Testing Message", "This mail was sent from PHP Script."));
?>
And try to access the file and see what you are getting. Please update the same in your question.

Resources