How can i prevent page from jumping to bottom? - javascript

The page is jumping to the bottom when the submit button is pushed on the contact form. I think this is caused by js. When you want to try it, push the link below, next contact, fill in the form and press "verstuur"
http://expertlemmer.nl/PC-laptop-reparatie-Lemmer/
javascript:
$('form#contactForm button.submit').on('click', function() {
$('#image-loader').fadeIn();
var contactFname = $('#contactForm #contactFname').val();
var contactLname = $('#contactForm #contactLname').val();
var contactStraat = $('#contactForm #contactStraat').val();
var contactPostcode = $('#contactForm #contactPostcode').val();
var contactTel = $('#contactForm #contactTel').val();
var contactEmail = $('#contactForm #contactEmail').val();
var contactSubject = $('#contactForm #contactSubject').val();
var contactMessage = $('#contactForm #contactMessage').val();
var data = 'contactFname=' + contactFname + '&contactLname=' + contactLname +
'&contactEmail=' + contactEmail + '&contactSubject=' + contactSubject +
'&contactStraat=' + contactStraat + '&contactPostcode=' + contactPostcode +
'&contactTel=' + contactTel + '&contactMessage=' + contactMessage;
$.ajax({
type: "POST",
url: "inc/sendEmail.php",
data: data,
success: function(msg) {
// Message was sent
if (msg == 'OK') {
$('#image-loader').fadeOut();
$('#message-warning').hide();
$('#contactForm').fadeOut();
$('#message-success').fadeIn();
}
// There was an error
else {
$('#image-loader').fadeOut();
$('#message-warning').html(msg);
$('#message-warning').fadeIn();
}
}
});
return false;
});

Hello i was on your webpage. And you are using in your script :
$('form#contactForm button.submit').on('click', function() {
e.preventDefault();
// and so on
The problem is that, you do not pass the e in the function. You have to use it like this :
$('form#contactForm button.submit').on('click', function(e) {
e.preventDefault();
// and so on
Then it will prevent the form from refreshing the page. I am just guessing that you want to send the form through ajax.

Your form has no "ACTION" attribute, this means it's posting to the current URL. The current URL has an anchor : #contact, this means you'll jump straight to the contact part.
See what you get when you go into this link and scroll down(Scroll, don't click contact), you'll jump to the review section.
http://expertlemmer.nl/PC-laptop-reparatie-Lemmer/#journal
Long story short, Put an action tag on your form :)

Related

Reloading Ajax function with setTimeout doesnt clear previous timeout first

I am trying to load a chat box when a contact name is clicked. On initial load it displays the inbox. All functionality works ok until I try and click the contact name a second time. It loads the new contacts chat but also displays the original contact chat even though I set clearTimeout().
Here is the JS file -
$(document).ready(function(){
var contactTimeout;
var inboxTimeout;
function contact() {
var fromName = $('#from').val();
var toName = $("#to").val();
$(".chat-title").replaceWith("<div class='chat-title'>" + toName + "</div>");
$(".chat-form").fadeIn(100);
$.ajax('chat/get-chat.php', {
data: ({ to: toName,from: fromName}),
type: "POST",
success: function(data) {
$(".chat-body").replaceWith("<div class='chat-body'>" + data + "</div>");
contactTimeout = setTimeout(contact, 2000);
}
});
}
function inbox() {
var user = $('#from').val();
$.ajax('chat/get-chat-inbox.php', {
data: ({ user: user}),
type: "POST",
success: function(data) {
$(".chat-body").replaceWith("<div class='chat-body'>" + data + "</div>");
inboxTimeout = setTimeout(inbox, 2000);
}
});
}
// Load inbox when chat box is opened
$(".chat-arrow").click(function(){
clearTimeout(contactTimeout);
inbox();
});
// Load chat from contact name
$(".contact-name").click(function() {
clearTimeout(contactTimeout); // Here I try and kill previous timeout
clearTimeout(inboxTimeout);
var contactName = $(this).attr('id');
$("#to").val(contactName);
contact();
});
});
Why would it just add more timeout functions rather than replace them when a new contact name is clicked?
First i would suggest you instead of using replace each time, you could easily use .html(data) to put new data in existing content of chat-body.
And explanation is you call your function on ajax success (there's wait time to server respond to your request) and if you click in meanwhile on your another call, you will have two calls instead of one, because you can't clear timer that's not started yet.
Well one of the solutions would be, let timer works only through it's default state, and when you need some fast data, you can call your contact without calling the next timer.
$(document).ready(function(){
var contactTimeout;
var inboxTimeout;
/* add parameter which will mean will we call timer or not */
function contact(dotimer) {
var fromName = $('#from').val();
var toName = $("#to").val();
$(".chat-title").replaceWith("<div class='chat-title'>" + toName + "</div>");
$(".chat-form").fadeIn(100);
$.ajax('chat/get-chat.php', {
data: ({ to: toName,from: fromName}),
type: "POST",
success: function(data) {
$(".chat-body").replaceWith("<div class='chat-body'>" + data + "</div>");
/* default calling of timer with repeating */
if (dotimer) { contactTimeout = setTimeout(function(){ contact(true); }, 2000); }
}
});
}
function inbox() {
var user = $('#from').val();
$.ajax('chat/get-chat-inbox.php', {
data: ({ user: user}),
type: "POST",
success: function(data) {
$(".chat-body").replaceWith("<div class='chat-body'>" + data + "</div>");
inboxTimeout = setTimeout(inbox, 2000);
}
});
}
// Load inbox when chat box is opened
$(".chat-arrow").click(function(){
clearTimeout(contactTimeout);
inbox();
});
// Load chat from contact name
$(".contact-name").click(function() {
clearTimeout(inboxTimeout);
var contactName = $(this).attr('id');
$("#to").val(contactName);
/* call function without TIMER, default one will work as it works */
contact(false);
});
});

Stop form from submitting until modal is open in ajax

I am getting data from a form and on submit button if data ios not valid it returns false and if data is valid am sending an email through ajax in its success method am showing a modal for sent or not I want window.location.href to be change after modal is hidden as form submits before even modal is displayed so I used event.preventdefault to stop it from submit but now have two issues
browser gets stuch until modal is open
after modal window.location is not being changed.
here is my code for submit button
<input type="submit" class="button btn btn-primary" onclick ="return SendEmail();" />
here is SendEmail()
function SendEmail()
{
if (!CheckContactUsFormValidation()) {
return false;
}
else{
var l_strEmail = document.getElementById('txtEmail').value;
var l_strComents = document.getElementById('txtComments').value;
var l_strEventLocation = document.getElementById('txtEventLocation').value;
var l_strStartDate = document.getElementById('txtStartDate').value;
var l_strOrganization = document.getElementById('txtOrganization').value;
var l_strPhone = document.getElementById('txtPhone').value;
var l_strLastName = document.getElementById('txtLastName').value;
var l_strFirstName = document.getElementById('txtFirstName').value;
var rent = document.getElementById("inlineRadio1").value;
var lease = document.getElementById("inlineRadio2").value;
if (rent.checked == true) {
var l_strCheck = 'rent';
}
else {
if (lease.checked == true) {
var l_strCheck = 'lease';
}
}
var l_strTitle = "Contact Us";
var l_strContents = 'Hi, ' + l_strFirstName + ' ' + l_strLastName + '\n';
l_strContents += 'he is mail for requesting product on ' + l_strCheck + ' and start date is ' + l_strStartDate + ' for organization ' + l_strOrganization + '\n';
l_strContents += 'his cell #' + l_strPhone + ' and his coments are as follows \n';
l_strContents += l_strComents + '\n' + 'You can contact him on email: ' + l_strEmail;
l_strContents += 'End here!';
var l_strtoEmail = 'abc#yahoo.com';
SendEmailWithCustomTitle(l_strtoEmail, l_strContents, l_strTitle);
}
return true;
}
function CheckContactUsFormValidation() {
var m_boolValidator = true;
if (!CheckRequiredFieldValidation('FirstName', 'Enter first name')) {
m_boolValidator = false;
}
if (!CheckRequiredFieldValidation('LastName', 'Enter last name')) {
m_boolValidator = false;
}
if (!CheckRequiredFieldValidation('Organization', 'Enter Organization')) {
m_boolValidator = false;
}
if (!CheckRequiredFieldValidation('Email', 'Enter Email')) {
m_boolValidator = false;
}
else
{
if (!CheckEmailValidation('Email', 'Enter valid email address')) {
m_boolValidator = false;
}
}
if (!CheckRequiredFieldValidation('Phone', 'Enter phone#')) {
m_boolValidator = false;
}
if (!CheckRequiredFieldValidation('StartDate', 'Enter start date')) {
m_boolValidator = false;
}
return m_boolValidator;
}
and here is ajax function being called inside SendEmail()
function SendEmailWithCustomTitle(txtEmail, txtContents, l_strTitle) {
event.preventDefault();
$.ajax({
async:false,
type: "POST",
url: "PTServiceRoutines.aspx/AjaxSendEmail",
data: "{'p_strEmail':'" + txtEmail + "','p_strTitle':'" + l_strTitle + "','p_strContents':'" + txtContents + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successAjaxSendEmailWithCustomTitleHandler,
failure: failureAjaxSendEmailWithCustomTitleHandler,
error: errorAjaxSendEmailWithCustomTitleHandler
});
return false;
}
function successAjaxSendEmailWithCustomTitleHandler(data) {
ShowAlert(data.d);
//ShowAlert is method used to open modal showing data.a
};
function failureAjaxSendEmailWithCustomTitleHandler(data) {
};
function errorAjaxSendEmailWithCustomTitleHandler(data, status) {
};
I have already tried event.preventdefault,event.soppropogation but I could not find any easy way to return true from ajax success function SendEmail call.
Remove async:false, from you ajax to stop the browser from waiting for the ajax to complete
Use the following event to redirect when the modal is closed
$('#myModal').on('hidden.bs.modal', function () {
window.location.href = "desired-page.php"
})
You can create a button in modal and in that button click event, at first hide the modal and the call the ajax call. And window.location.href will not work inside a html form. To make window.location.href work you can move your submit button out of the form.
To open modal in success follow one of following two methods.
.done(function() {
$("#yourmodal").modal();
});
Or
success: function(data) {
$("#yourmodal").modal();
}
To stop ajax call until modal hide use following. Place your ajax call inside a function for an example "submitForm()". call this in following.
$('#yourmodal').on('hidden.bs.modal', function (e) {
// do something...
})

Fire jQuery event on enter key press?

I'm trying to submit a rails form using jQuery (Which I know little about) and have had success in setting up a form to submit on clicking the submit button and run a callback(I believe this is the correct terminology?), but I would also like to make it work when just hitting enter.
As it stands, hitting enter will submit data to the database but will not run the commands to append the div or clear the text field. How could I make this happen so it works the same for the enter key as it does the submit button? I've tried to wrap the code inside a function that will run when enter is hit but having no luck!
function runScript(e) {
if (e.keyCode == 13) {
msg = json.msg;
foreign = json.foreign_speaker;
msg_translated = json.msg_translated;
//The HTML that we will append to the document.
html = "<div class='msg msg" + foreign + "'>" + msg +
"</div> <div class='msg msg" + foreign + "-translation'>" + msg_translated + "</div>"
// Append new message.
$('.chatmessages').append(html).fadeIn('fast');
scrollToBottom(500)
// Clear form with jquery.
$('#message_msg').val('');
$('#message_foreign_speaker').attr('checked', false);
}
}
I tried that with no luck.
My current, button-working, JS file:
var scrollToBottom = function(anim){
var myDiv = $(".wrap");
myDiv.animate({ scrollTop: myDiv[0].scrollHeight - myDiv.height() }, anim);
};
$(document).ready(function(){
scrollToBottom(0)
//JS to POST form
$('.submit').click(function() {
var valuesToSubmit = $('.msgform').serialize();
$.ajax({
type: 'POST',
url: window.location.href + '/messages', //sumbits it to the given url of the form
data: valuesToSubmit,// { chat_id, <%= #chat.id %> },
dataType: "JSON", // you want a difference between normal and ajax-calls
})
.done(refresherFunc)
.fail(function(){
alert("Error sending message. It would be nice to make this a flash error.");
});
return false; // prevents normal behaviour
})
});
var refresherFunc = function(json) {
// Get debugging goodies.
console.log(json);
// Set variables with JSON object data
msg = json.msg;
foreign = json.foreign_speaker;
msg_translated = json.msg_translated;
//The HTML that we will append to the document.
html = "<div class='msg msg" + foreign + "'>" + msg +
"</div> <div class='msg msg" + foreign + "-translation'>" + msg_translated + "</div>"
// Append new message.
$('.chatmessages').append(html).fadeIn('fast');
scrollToBottom(500)
// Clear form with jquery.
$('#message_msg').val('');
$('#message_foreign_speaker').attr('checked', false);
}
Catch your form submit event with jQuery's submit() function and return false inside it. This function will be called any way you submit the form (clicking on submit button or pressing enter key). Returning false will prevent the browser from completing the form sumbittion which lets you do whatever you want with it.
See example: http://jsfiddle.net/vgk4wu46/

Comment reply not display properly by JS

For prevent the refresh of the page after submitting the form I want to add return false;
Also have default browser behavior problem to refresh this page.
But if I add return false; or e.preventDefault(); reply of any comment show duplicate under only last/top/new comment AND after a refresh Its show original comment. not only that delete comment show loader continuously.
Now I think my problem either my html structure or JavaScript.
HTML of index.php:
<div class="content"><comment>
<div class="post'.$id.'">
//here main comment goes on
</div>
<div class="reply'.$id.'" id="replynext"><ul>
//here reply goes on
</ul></div>
<comment></div>
HTML of Reply.php:
<div class="reply'.$id.'" id="replynext"><ul>
//new reply goes here
</ul></div>
JS for reply without return false;:
var inputAuthor = $("#author");
var inputComment = $("#comment");
var inputReplycom = $(".replycom");
var inputImg = $("#img");
var inputUrl = $("#url");
var inputTutid = $("#tutid");
var inputparent_id = $("#parent_id");
var commentList = $(".content > comment");
function updateReplybox(){
var tutid = inputTutid.attr("value");
//just for the fade effect
$.ajax({
type: "POST", url: "reply.php", data: "action=update&tutid="+ tutid,
complete: function(data){
var RID = $(this).attr('class').replace('reply','');
$(".reply"+RID).append(data.responseText);
$(".reply"+RID).fadeIn(2000);
}
});
}
//on submit reply
$(".repfrm").click(function(){
error.fadeOut();
var author = inputAuthor.attr("value");
var url = inputUrl.attr("value");
var img = inputImg.attr("value");
var replycom = inputReplycom.attr("value");
var parent_id = inputparent_id.attr("value");
var tutid = inputTutid.attr("value");
$(".loader").fadeIn(400).html('<br><img src="loaders.gif" align="absmiddle"> <span class="loading">Loading Update...</span>');
//send the post to submit.php
$.ajax({
type: "POST",
url: "reply.php",
data: "action=insert&author="+ author + "&replycom="+ replycom + "&url="+ url + "&img="+ img + "&parent_id="+ parent_id + "&tutid="+ tutid,
complete: function(data){
error.fadeOut();
$(".reply"+RID).append(data.responseText);
updateReplybox();
//reactivate the send button
}
});
error_message();
//we prevent the refresh of the page after submitting the form
});

Deselect a text box in jQuery after page reload if content is active

I have a Google Instant style jQuery search script that queries a PHP file then parses the results into an HTML div. When no query is active the text box is automatically selected but when a query is active I want it not to be automatically selected. I know this is possible to do by using the .blur(); function, but how can I make it only use the .blur(); function when a query is active and the page has been reloaded? I hope everyone can understand my question.
My jQuery code is:
$(document).ready(function () {
$('[id^=type_]').click(function () {
type = this.id.replace('type_', '');
$('[id^=type_]').removeClass('selected');
$('#type_' + type).addClass('selected');
return false;
});
$('#query').focus();
if (window.location.hash != "") {
var full = window.location.hash.replace('#', '');
var queryType = full.substring(0, full.indexOf("/"));
$('#type_' + queryType).click();
} else {
$('#type_search').click();
}
$('#query').keyup(function () {
var query = $(this).val();
var url = '/' + type + '/' + query + '/';
window.location.hash = '' + type + '/' + query + '/';
document.title = $(this).val() + ' - My Search Script';
$('#results').show();
if (query == '') {
window.location.hash = '';
document.title = 'My Search Script';
$('#results').hide();
}
$.ajax({
type: 'GET',
url: url,
dataType: 'html',
success: function (results) {
$('#results').html(results);
}
});
});
if (window.location.hash.indexOf('#' + type + '/') == 0) {
query = window.location.hash.replace('#' + type + '/', '').replace('/', '');
$('#query').val(decodeURIComponent(query)).keyup();
}
});
after reviewing the source I found that my suspicion was correct. Because there is only one text box on the page, once you blur the query one, it just goes back to it. You can make another input node on your html page e.g.
<input type="text" style="display:none" id="invisible">
and then use this code
if ($('#query').val().length) {
$('#invisible').focus();
}
and that should get you there :)
Ahha! I see what you mean. You can check if the textbox has anything in it with the .val() function in JQuery. Assuming that '#query' is the textbox, you can change that part to
if($('#query').val().length == 0)
$('#query').focus();

Categories