I am working on a site which having 2 contact forms, and I use ajax jquery to send mail via php.
When I use single form and jQuery, it works fine.
And when I paste the jQuery code and modify as per form 2 variables, it works, but then first jQuery code is sending blank values.
Over all at a time, only 1 form is working for my HTML forms on different page.
I appreciate your help in advance.
Jquery code
var form=$('#contactform_forms');
var formMessages=$('#message');
$(form).submit(function(e){
$('#submit_btns')
.after('<img src="images/AjaxLoader.gif" class="loader" />')
.attr('disabled','disabled');
e.preventDefault();
var formData=$(form).serialize();
$.ajax({
type:'POST',
url:'contact.php',
data:formData
})
.done(function(response){
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
$(formMessages).text('Thanks! Message has been sent.');
$(formMessages).fadeOut(10000);
$('#contactform_forms img.loader').fadeOut('slow',function(){$(this).remove()});
$('#submit_btns').removeAttr('disabled');
$('#contact_name').val('');
$('#contact_email').val('');
$('#contact_phone').val('');
$('#contact_message').val('');
}).fail(function(data){
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
if(data.responseText!==''){
$(formMessages).text(data.responseText);
}else{
$(formMessages).text('Oops! An error occured.');
}
});
});
jQuery code for form 2 with the same js file:
var form=$('#wholesalers_forms');
var formMessages=$('#message');
$(form).submit(function(e){
$('#submit_btns1')
.after('<img src="images/AjaxLoader.gif" class="loader" />')
.attr('disabled','disabled');
e.preventDefault();
var formData=$(form).serialize();
$.ajax({
type:'POST',
url:'wholesalers.php',
data:formData
})
.done(function(response){
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
$(formMessages).text('Thanks! Message has been sent.');
$(formMessages).fadeOut(10000);
$('#wholesalers_forms img.loader').fadeOut('slow',function(){$(this).remove()});
$('#submit_btns1').removeAttr('disabled');
$('#hs_name').val('');
$('#hs_email').val('');
$('#hs_company').val('');
$('#hs_vat').val('');
$('#hs_address').val('');
$('#hs_postcode').val('');
$('#hs_city').val('');
$('#hs_phone').val('');
$('#hs_message').val('');
}).fail(function(data){
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
if(data.responseText!==''){
$(formMessages).text(data.responseText);
}else{
$(formMessages).text('Oops! An error occured.');
}
});
});
When I use both as the above order: 1st one send empty value and second form working perfectly, if i remove 2nd jQuery then first code working fine, but second do not have code to send.
There are a few issues here. First I can see you've got duplicate element IDs on the page which will produce undefined results. Second, you shouldn't be copying and pasting code but iterating through (or making generic) your code, depending on the usage. This keeps your code DRY. Further reading here: https://en.wikipedia.org/wiki/Don%27t_repeat_yourself.
If you are still having trouble, add a jsFiddle with the specific parts of the code you are having trouble with.
I'd do something like this:
function getFormData(form_id) {
var form_data = {};
$.each($("#" + form_id).serializeArray(), function(i, obj) {
if (form_data[obj.name] == undefined) {
form_data[obj.name] = obj.value;
} else if (typeof form_data[obj.name] == Array) {
form_data[obj.name].push(obj.value);
} else {
form_data[obj.name] = [form_data[obj.name], obj.value];
}
});
return form_data;
}
function validate(form_id) {
var error = false;
//run some validation, which alters display and sets error to true on failure.
return error;
}
$(document).on("submit", "form", function(event) {
var form_id = $(this).attr("id");
if (validate(form_id)) { //If error is found.
event.preventDefault();
} else { //Else the form is good.
var form_data = getFormData(form_id),
url = (form_id == "contactform_forms") ? "contact.php" : "wholsalers.php";
$.ajax({
type: "post",
url: url,
data: form_data,
success: function(data) {
//Display a confirmation message.
}
})
}
});
Related
I have a ajax section to submit data in laravel. I want if I submit success then don't reload the page and submit the error then reload the page. In the code below, when the error reloads the page correctly, I am having a problem in the success case, the page must not be reloaded, but the result is reloaded. I have added the line e.preventDefault () then true in the success case but wrong in the error case
$(document).ready(function() {
$('form').submit(function(e){
//e.preventDefault();
var form_data = $(this).serialize();
$.ajax({
url:'{{ route('contracts.store') }}',
method: "POST",
data: form_data,
dataType: "json",
success: function(data) {
$("#mgsContract").text("Add successfully");
$("#hideForm").css("visibility", "visible");
$("#hideForm").css("height", "auto");
$("#result-contract-id").val(data.contract_obj);
},
error: function(data) {
$("#mgsContract").text("Something wrong");
}
})
});
});
Add back that e.preventDefault() to prevent the form submission, and in the error case, call location.reload(). (Or if you want to submit the form conventionally in the error case, use e.target.submit(); instead. Since that's calling submit on the DOM element [not a jQuery wrapper], it won't call your submit handler again. [This is one of the differences between programmatically calling submit on a DOM element vs. calling it on a jQuery object.])
when you use ajax, laravel automatically responds in JSON for validation errors. therefore to access the validation errors you can use this.responseJSON.errors in error section of your ajax. there is no need to reload the page to access validation errors.
however in any case if you need to reload or go to specific location you can use window.location
window.location.href = "an address"; // going to specific location
window.location.reload(); //reloading the page
an ajax example is the following, in which a loop for showing all errors inside the form is specified.
$("#form_id").submit(function (e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
var form = $(this);
var url = form.attr('action');
$.ajax({
method: "POST",
url: url,
data: form.serialize(), // serializes the form's elements.
success: function (data) {
// code in the case of success
},
error: function (err) {
if (err.status == 422) { // when status code is 422, it's a validation issue
// code in the case of error
console.log(err.responseJSON);
// you can loop through the errors object and show it to the user
console.warn(err.responseJSON.errors);
// display errors on each form field
$.each(err.responseJSON.errors, function (i, error) {
var el = $(document).find('[name="' + i + '"]');
el.removeClass('is-valid');
el.addClass('is-invalid');
var parent = el.parents('.form-group');
parent.append("<small class='error-message text-right text-danger d-block pr-5 ' role='alert'>" + error + "</small >");
});
}
},
});
});
I am working on a project where i have an issue with the commenting function i've made. Whenever i comment and use special characters the console displays this error: syntax error, unrecognized expression. Furthermore the request goes through and my backend (PHP) inserts the data to the DB but i then have to refresh to get the updated version of the post with that new comment. I can't figure out why even after a couple of searches here on stack and i could really use a new pair of eyes on the code.
I figure that the backend isn't the issue which is why it's left out of this post. Furthermore the form just contains a text input and a submit button. It might be important to mention that i use jQuery v3.3.1.
Finally when the form is submitted an ajax call gets triggered. Here it is:
var newComment;
$(document).on("submit", "form[data-comment]", function(e){
e.preventDefault();
var where = $(this);
var updateThis = $(where).parent().parent();
var data = $(where).attr("data-comment").split(",");
var comment = $(where).find("input[name='commenter']").val().toString();// <= this might be the issue?
if (data[0] == 1){
if (data[1] != "" && data[2] != "" && data[3] != ""){
//insert comment via ajax and return post and insert post
if (newComment){ <= prevent firing until newComment = false
newComment.abort();
return false;
}
$(where).find("input[type='submit']").prop("disabled", true);
$(where).find("input[type='submit']").val("commenting...");
newComment = $.ajax({
url: "mypage/core/AjaxRequests.php", <= call to php handler
type: "POST",
data: { type: "15", data: data, comment: comment }
});
$(comment).val("");
newComment.done(function(response, textStatus, jqXHR){
newComment = false;
$(where).find("input[type='submit']").prop("disabled", false);
$(where).find("input[type='submit']").val("Comment");
if (response.length > 200){
$(updateThis).parent().fadeTo(0,0);
$(updateThis).parent().prop('outerHTML', response);
$(updateThis).parent().fadeTo(1,1);
}
});
}
}
});
I have two buttons on the form I'm getting, this first piece of coce allow me to know which was the button clicked by getting the id of it.
var button;
var form = $('.register_ajax');
$('#vote_up, #vote_down').on("click",function(e) {
e.preventDefault();
button = $(this).attr("id");
});
and this other send the form data through AJAX using the info already obtained from the button using the script above.
form.bind('submit',function () {
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
cache: false,
dataType: 'json',
data: form.serialize() + '&' + encodeURI(button.attr('name')) + '=' + encodeURI(button.attr('value')) ,
beforeSend: function() {
//$("#validation-errors").hide().empty();
},
success: function(data) {
if(data.message == 0){
$("#fave").attr('src','interactions/favorite.png');
$("#favorite").attr('value',1);
console.log(data.errors);
}
if(data.message == 1)
{
$("#fave").attr('src','interactions/favorite_active.png');
$("#favorite").attr('value',0);
}
if(data.message == "plus")
{
$("#vote_up").attr('class','options options-hover');
$("#vote_down").attr('class','options');
console.log(data.message);
}
if(data.message == "sub")
{
$("#vote_down").attr('class','options options-hover');
$("#vote_up").attr('class','options');
console.log("sub");
}
},
error: function(xhr, textStatus, thrownError) {
console.log(data.message);
}
});
return false;
});
The problem is that the data is not being passed to the ajax function, the button info is being saved on the button var, but it's not being obtained at time on the ajax call to work with it (or at least that is what I think). I'd like to know what can I do to make this work, any help appreciated.
1st edit: If I get the button data directly like button = $('#vote_up'); it doesn't work either, it only works if I get the button directly like this but without using the function.
2nd edit: I found the solution, I posted below.
var button is in the scope of the .on('event', function(){})
You need to declare the variable in the shared scope, then you can modify the value inside the event callback, i.e.
var button,
form = $('.register_ajax');
$('#vote_up, #vote_down').on("click",function(e) {
e.preventDefault();
button = $(this).attr("id");
});
You are being victim of a clousure. Just as adam_bear said you need to declare the variable outside of the function where you are setting it, but you are going to keep hitting these kind of walls constantly unless you dedicate some hours to learn the Good Parts :D, javascript is full of these type of things, here is a good book for you and you can also learn more from the author at http://www.crockford.com/.
I Found the solution, I just changed a little bit the click function like this:
var button;
var form = $('.register_ajax');
var data = form.serializeArray();
$('#vote_up, #vote_down').on("click",function(e) {
e.preventDefault();
button = $(this).attr("id");
data.push({name: encodeURI($(this).attr('name')), value: encodeURI($(this).attr('value'))});
form.submit();
});
using e.preventDefault(); and form.submit(); to send the form. also I changed the data.serialize to serializeArray(); because it's more effective to push data into the serializeArray(). in the second script I just changed the data.serialize() and used the data variable that I already filled with the serializeArray() and the data.push():
form.bind('submit',function () {
alert(button);
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
cache: false,
dataType: 'json',
data: data,
//here goes the rest of the code
//...
});
return false;
});
it worked for me, it solved the problem between the click and submit event that wasn't allowing me to send the function through ajax.
Hi I'am trying to make HTML form, and need to validate it before executing the form action. But the AJAX respond always returns a blank message?
$(function(){
$("#ajax-payment-form input[type='submit']").click(function(e) {
// Prevent form submission
e.preventDefault();
// Serialize data, make AJAX call
var str = $(this).serialize();
$.ajax({
type: "POST",
url: templateDir+"/payment_form/payment_process.php",
data: str,
context: this
}).done(function(msg) {
if(msg == 'OK') {
console.log('Validation passed, will submit form');
$(this).closest('form').submit();
} else {
console.log(msg);
}
}).fail(function() {
// Catch ajax errors here
console.log('AJAX error');
});
});
});
PHP:
$post = (!empty($_POST)) ? true : false;
if ($post) {
$orderid = stripslashes($_POST['orderid']);
$amount = stripslashes($_POST['amount']);
$betingelser = stripslashes($_POST['betingelser']);
$error = ''; // Check ordreid
if (!$orderid) {
$error. = 'Venligst indtast dit ordreid.<br />';
} // Check amount
if (!$amount) {
$error. = 'Venligst indtast et beløb.<br />';
}
if (!$error) {
echo 'OK';
} else {
echo '<div class="notification_error">'.$error.
'</div>';
}
}
Can anyone tell me what wrong?
You're in the click handler of a submit button. You're calling $(this).serialize(), where this is that submit button. Calling serialize on the submit button is going to return an empty string.
So, you're not passing any data to the server. The first thing you do server-side is check empty($_POST), which it will be, so if ($post) is false, and none of your server-side code is eve executed.
You need to serialize the form, not the submit button.
A simple solution would be to serialize the form itself....
str = $('"#ajax-payment-form').serialize()
but really, the larger problem is that you're binding to the click of the submit button, instead of to the submit event on the form itself.
Instead of this rather convoluted way of handling form submits...
$("#ajax-payment-form input[type='submit']").click(function(e) {
Just do this:
$("#ajax-payment-form").submit(function (e) {
try this in jquery:
$.ajax({
type: "POST",
url: templateDir+"/payment_form/payment_process.php",
data: str,
context: this,
success: function(msg){
if(msg == 'OK') {
console.log('Validation passed, will submit form');
$(this).closest('form').submit();
}
else {
console.log(msg);
}
}
error: function(msg){
// if call fails or any error occurs
}
});
Comment Form is submitting and also data getting saved to the database. But not displaying on the browser without refreshing the page.
here is the code:
$("#post_reply").click(function (event) {
$("#data_status").html("");
$('#ajax_loading').show();
event.preventDefault();
if (document.getElementById('_comment').value.trim() == "") {
return false;
}
$.post('../services/leave_comment.php', $("#open_status").serialize(), function (data) {
$('#ajax_loading').hide();
if (data.split("::")[1] == true) {
$("#data_status").html("Commented Successfully..");
$("#data_status").fadeOut(3000);
document.getElementById('_comment').value = '';
$('#_comment').html("");
} else if (data.split("::")[1] == false) {
$("#data_status").html("Error occured in Comment Submission.. TryAgain..");
$("#data_status").fadeOut(3000);
}
});
});
EDIT:
All i can understand is i haven't published the data with ajax??
Is this what i need to do??
$("#post_reply").click(function (event) {
$("#data_status").html("");
$('#ajax_loading').show();
event.preventDefault();
if (document.getElementById('_comment').value.trim() == "") {
return false;
}
$.post('../services/leave_comment.php', $("#open_status").serialize(), function (data) {
$('#ajax_loading').hide();
if (data.split("::")[1] == true) {
$("#data_status").html("Commented Successfully..");
$("#data_status").fadeOut(3000);
document.getElementById('_comment').value = '';
$('#_comment').html("");
$.ajax({
type: 'POST',
url : 'http://localhost/tech1/services/get_more_comments.php',
data: 'last_id='+last_id,
success: function(data){
$('.view_container').append(data);
},
complete: function(){
console.log('DONE');
}
});
} else if (data.split("::")[1] == false) {
$("#data_status").html("Error occured in Comment Submission.. TryAgain..");
$("#data_status").fadeOut(3000);
}
});
});
All your code does is post the data to the server. There is nothing that fetches the new comments from the server or manually appends the posted comment. You can either use ajax again to refresh comments or more simply append a comment with the posted content.
I would say to search the web for jQuery's .load :
example:
function updateShouts(){
// Assuming we have #shoutbox
$('#shoutbox').load('latestShouts.php');
}
in this case shoutbox would be the containing div with your comments,
you would call this function on the success of your ajax post
latestshouts.php would only contain the content of that div.
kinda hard to explain, i hope it makes sense to you
link: http://api.jquery.com/load/