jQuery animated message after form submit - javascript

I have a form and after user is successfully filled the form I want the actual message
to "bounce" from the top about 30px and show the actual message. The problem is that my
form's height is huge, about 900px so I'll never see the actual message unless I scroll on top of my page which is impossible because the page reloads itself after 3 seconds. How should I implement this? Here's my AJAX code for now:
<script type="text/javascript">
$(document).ready(function() {
// Process the form with AJAX
$("form").on('submit', function(e)
{
e.preventDefault();
var from = $("form");
$.ajax({
url: from.attr('action'),
type: from.attr('method'),
data: $(from).serialize(),
}).done(function(data) {
if(data.result == 0) {
$("#new_survey_success").hide();
for (var key in data.error) {
var value = data.error[key];
var output = '<p>' + value + '</p>';
}
$("#new_survey_error").fadeIn(1000).show().html(output);
}
if(data.result == 1) {
$("#new_survey_error").hide();
$("#new_survey_success").fadeIn(200).show().html("<p>" + data.success + "</p>");
window.setTimeout(function(){location.reload()},3000)
}
}, 'json');
return false;
});
});
</script>
Thanks in advance!

Related

How can I start a jquery function on clicking a button and on pressing enter

I have a function that sends some data from a form using Ajax.
To prevent the form from posting it without Ajax I use preventDefault(); this also stops the form from submitting when pressing enter.
How can I make sure the function below is started when clicking the button (as it is now) and also when pressing the enter button?
jQuery:
$("body").on("click",".login-button",function(e){
e.preventDefault();
loginform = $(".login-form").serialize();
$.ajax({
type:'post',
url:"includes/inloggen.php",
data:({loginform: loginform}),
success:function(data){
var obj = JSON.parse(data);
var arrayspot = 0;
for (var i = 0; i < obj.length; i++) {
var status = obj[i].status;
var field = obj[i].field;
if(status == 'error'){
var message = obj[i].message;
$( 'input[name="' + field + '"]' ).parent().addClass('invalid-input');
var errorveld = $( 'input[name="' + field + '"]' ).parent();
$( 'input[name="' + field + '"]' ).parent().next('.inputerror').remove();
errorveld.after('<div class="inputerror"><i class="fas fa-arrow-up"></i> ' + message + '</div>');
}else if(status == 'success'){
$( 'input[name="' + field + '"]' ).parent().next('.inputerror').remove();
$( 'input[name="' + field + '"]' ).parent().removeClass('invalid-input');
}
var arrayspot = parseInt(i);
}
if(obj[arrayspot].totalstatus == 'error'){
$( "#loginresult" ).removeClass('positiveresult');
$( "#loginresult" ).show().empty().append( obj[arrayspot].totalmessage );
}else if(obj[arrayspot].totalstatus == 'success'){
window.location.replace("https://website.nl/new/");
}
}
});
});
I've tried copying the entire function but this time start it on enter press but there must be another way with fewer lines of code? Without sending double ajax requests.
You get this behaviour for free when you have your controls contained within a <form>. From the context of your code using serialize() it appears this is already the case. As such you can simply amend your logic to listen for the submit event of the form instead of the click of the submit button. Try this:
$("body").on("submit", ".login-form", function(e) {
e.preventDefault();
loginform = $(this).serialize();
$.ajax({
type: 'post',
url: "includes/inloggen.php",
data: {
loginform: loginform
},
success: function(data) {
var obj = JSON.parse(data);
var arrayspot = 0;
for (var i = 0; i < obj.length; i++) {
var status = obj[i].status;
var field = obj[i].field;
var $errorveld = $('input[name="' + field + '"]').parent();
if (status == 'error') {
var message = obj[i].message;
$errorveld.addClass('invalid-input');
$errorveld.next('.inputerror').remove();
$errorveld.after('<div class="inputerror"><i class="fas fa-arrow-up"></i> ' + message + '</div>');
} else if (status == 'success') {
$errorveld.next('.inputerror').remove();
$errorveld.removeClass('invalid-input');
}
var arrayspot = parseInt(i);
}
if (obj[arrayspot].totalstatus == 'error') {
$("#loginresult").removeClass('positiveresult').show().empty().append(obj[arrayspot].totalmessage);
} else if (obj[arrayspot].totalstatus == 'success') {
window.location.replace("https://website.nl/new/");
}
}
});
});
Also note that I tidied the logic a little by removing the unnecessary () around the data property and also caching the $('input[name="' + field + '"]').parent() selector.
Finally, if the MIME type of the response is set correctly you shouldn't need to manually call JSON.parse(data)

How can I set loading image during post data jquery ajax and change alert msg to div error?

I want to show a div if the comment field is empty out instead of showing an alert. How can I do this? My other question is, the data is displayed after some seconds. During that loading period is possible to to add a loading image?
<script type="text/javascript">
$(function () {
// on post comment click
$('.bt-add-com').click(function () {
var theCom = $('.the-new-com');
var theName = $('#name-com');
var theMail = $('#mail-com');
if (!theCom.val()) {
alert('You need to write a comment!');
} else {
$.ajax({
type: "POST",
url: "ajax/add-comment.php",
data: 'act=add-com&id_post=' + <? php echo $id_post; ?> +'&name=' + theName.val() + '&email=' + theMail.val() + '&comment=' + theCom.val(),
success: function (html) {
theCom.val('');
theMail.val('');
theName.val('');
$('.new-com-cnt').hide('fast', function () {
$('.new-com-bt').show('fast');
$('.new-com-bt').after(html);
})
}
});
}
});
});
</script>

Load Twitter Box in Jquery box via Ajax

I would like to load a twitter popup box in jquery using (ajax?)
Here is my original code, which loads the twitter box in a new window:
function twitter_click() {
var twtTitle = document.title;
var twtUrl = location.href;
var maxLength = 140 - (twtUrl.length + 1);
if (twtTitle.length > maxLength) {
twtTitle = twtTitle.substr(0, (maxLength - 3)) + '...';
}
var twtLink = 'http://twitter.com/home?status=' + encodeURIComponent(twtTitle + ' ' + twtUrl);
window.open(twtLink,'','width=565, height=540');
}
Here is the code for the jquery popup box.
function showUrlInDialog(url, options){
options = options || {};
var tag = $("<div></div>"); //This tag will the hold the dialog content.
$.ajax({
url: url,
type: (options.type || 'GET'),
beforeSend: options.beforeSend,
error: options.error,
complete: options.complete,
success: function(data, textStatus, jqXHR) {
if(typeof data == "object" && data.html) { //response is assumed to be JSON
tag.html(data.html).dialog({modal: options.modal, title: data.title}).dialog('open');
} else { //response is assumed to be HTML
tag.html(data).dialog({modal: options.modal, title: options.title}).dialog('open');
}
$.isFunction(options.success) && (options.success)(data, textStatus, jqXHR);
}
});
}
<img src="twitter_button.jpg>
I don't know anything about coding so if someone can please combine these two scripts so that the twitter content of the first script loads into the jquery popup script that would make my day! Thanks. Pia
Start by changing this:
window.open(twtLink,'','width=565, height=540');
to this:
showUrlInDialog(twtLink, {error: function() { alert('Could not load form') }});
Then to run it, use this:
<img src="twitter_button.jpg>

How to keep track of actions called by a jQuery dialog box?

I have a bit of a dillema :)
I have a link for users to vote on an item. A click on a link generated a jQuery AJAX call checking if the person is logged in. If not, the dialog box displays a form to login.
But the problem is that the jQuery call to log in and the whole bit with the popup box is in a different place.
What I need to do is check if user got logged in successfully, and update the vote count.
I am doing it on this site: http://www.problemio.com
Here is my jQuery code so far:
<script type="text/javascript">
$(document).ready(function()
{
var $dialog = $('#loginpopup')
.dialog({
autoOpen: false,
title: 'Login Dialog'
});
$("#newprofile").click(function () {
$("#login_div").hide();
$("#newprofileform").show();
});
$('.vote_up').click(function()
{
problem_id = $(this).attr("data-problem_id");
var dataString = 'problem_id='+ problem_id + '&vote=+';
$.ajax({
type: "POST",
url: "/problems/vote.php",
dataType: "json",
data: dataString,
success: function(data)
{
// ? :)
alert (data);
},
error : function(data)
{
errorMessage = data.responseText;
if ( errorMessage == "not_logged_in" )
{
// Try to create the popup that asks user to log in.
$dialog.dialog('open');
// prevent the default action, e.g., following a link
return false;
}
else
{
alert ("not");
}
//alert(JSON.stringify(data));
}
});
//Return false to prevent page navigation
return false;
});
$('.vote_down').click(function()
{
alert("down");
problem_id = $(this).attr("data-problem_id");
var dataString = 'problem_id='+ problem_id + '&vote=-';
//Return false to prevent page navigation
return false;
});
});
</script>
It all works except right after the line $dialog.dialog('open'); - I don't know how to
Get a signal back for success of fail, and don't know exactly how to
Update the very item that was voted on since it is just one of many items that can be voted on in the page.
How can I do these two things?
Try this approach:
Have a hidden input within the div that is your login dialog.
Set that with the problem_id before you do the .dialog('open')
On the success callback of the Login button click, retrieve problem_id from the hidden input and perform vote-up or vote-down.
Hope that helps
EDIT: (Trying to code a workable example after OP's second comment)
<script type="text/javascript">
$(document).ready(function() {
var $dialog = $('#loginpopup')
.dialog({
autoOpen: false,
title: 'Login Dialog'
});
var $problemId = $('#theProblemId', '#loginpopup');
$("#newprofile").click(function () {
$("#login_div").hide();
$("#newprofileform").show();
});
$('.vote_up').click(function() {
var problem_id = $(this).attr("data-problem_id");
voteUp(problem_id);
//Return false to prevent page navigation
return false;
});
var voteUp = function(problem_id) {
var dataString = 'problem_id=' + problem_id + '&vote=+';
$.ajax({
type: "POST",
url: "/problems/vote.php",
dataType: "json",
data: dataString,
success: function(data) {
// ? :)
alert(data);
},
error : function(data) {
errorMessage = data.responseText;
if (errorMessage == "not_logged_in") {
//set the current problem id to the one within the dialog
$problemId.val(problem_id);
// Try to create the popup that asks user to log in.
$dialog.dialog('open');
// prevent the default action, e.g., following a link
return false;
}
else {
alert("not");
}
//alert(JSON.stringify(data));
}
});
};
$('.vote_down').click(function() {
alert("down");
problem_id = $(this).attr("data-problem_id");
var dataString = 'problem_id=' + problem_id + '&vote=-';
//Return false to prevent page navigation
return false;
});
$('#loginButton', '#loginpopup').click(function() {
$.ajax({
url:'url to do the login',
success:function() {
//now call cote up
voteUp($problemId.val());
}
});
});
});
</script>

How to POST these variables?

The script called New script is suppose to output 2 integer variables anchor and signed.
I would like to replace Old script with New script, but as you can see, they are very different.
Question
How do I submit/post anchor and signed in New script?
New script
$(window).load(function() {
$('form').delegate('input:submit', 'click', function() {
var anchor = this.name;
var checkboxState = $('#' + anchor).find('input:checkbox').is(':checked');
var signed = 0;
if (checkboxState == true) {
signed = 1;
}
alert(anchor + ' ' + signed);
return false;
});
});
Old script
// sends the form content to server side, and stay on page
$('form').live('submit', function() {
$.post($(this).attr('action'), $(this).serialize(), function(response) {
// do something here on success
}, 'json');
// don't redirect
return false;
});
HTML
<form action="/cgi-bin/receiver.pl" method="post">
Put this
$.post($(this).prop('action'), {anchor: anchor, signed: signed}, function(response) {
// do something here on success
}, 'json');
in place of alert
Here is the proper one, and running ok.
http://jsfiddle.net/ergec/pJgyu/16539/

Categories

Resources