how to edit the alert success submission in JavaScript - javascript

Hi I am editing a website, there is the form submission there, where I use formspree to submit forms (names, email, comments). then click the send button.
Everything works well, expect the successful alert looks weird... see picture below:
I am trying to edit this, but couldn't figure out how. I want it to show "Thanks, your submission is successful!".
I found the javascript code for this part:
// Form Validation !Plugin #v1.0
NioApp.Plugins.submitform = function () {
var $form = $('.nk-form-submit');
if( !$().validate && !$().ajaxSubmit ) {
console.log('jQuery Form and Form Validate not Defined.');
return true;
}
if ($form.exists()) {
$form.each(function(){
var $self = $(this), _result = $self.find('.form-results');
$self.validate({
ignore: [],
invalidHandler: function () { _result.slideUp(400); },
submitHandler: function(form) {
_result.slideUp(400);
$(form).ajaxSubmit({
target: _result, dataType: 'json',
success: function(data) {
var type = (data.result==='error') ? 'alert-danger' : 'alert-success';
_result.removeClass( 'alert-danger alert-success' ).addClass( 'alert ' + type ).html(data.message).slideDown(400);
if (data.result !== 'error') { $(form).clearForm().find('input').removeClass('input-focused'); }
}
});
}
});
$self.find('.select').on('change', function() { $(this).valid(); });
});
}
};
NioApp.components.docReady.push(NioApp.Plugins.submitform);
and the code in css:
.alert-success { color: #29cf77; background: #cef5e1; }
.alert-success .close { background: #64e09e; }
.alert-success-alt { background: #39d884; }
.alert-success-alt .close { background: #25b96b; }
can anyone give me some hints how to change it? Thanks.

I will take a part of the javascript in the question to focus
$(form).ajaxSubmit({
target: _result, dataType: 'json',
success: function(data) {
var type = (data.result==='error') ? 'alert-danger' : 'alert-success';
_result.removeClass( 'alert-danger alert-success' ).addClass( 'alert ' + type ).html(data.message).slideDown(400);
if (data.result !== 'error') { $(form).clearForm().find('input').removeClass('input-focused'); }
}
});
This part is the ajax part, which is responsible to submit the data after validation, the return after successful submission is stored in the object data which has two attributes. data.result gives the submission status, and data.message carry the message to be displayed in a div. this div which has a class name .form-results, which is pointed by the object _result ( _result = $self.find('.form-results'))
The line below changes the class of the div according to data.status and display the message sent after submition
_result.removeClass( 'alert-danger alert-success' ).addClass( 'alert ' + type ).html(data.message).slideDown(400);
Therefore, either the message to be sent after submission or make a short modification for the case of success or failure.
if we go to make this modification, so just before mentioned line above we add:
if (data.result !== 'error') {data.message="Thanks, your submission is successful!";}
else { data.message = "Submition failed";}
so the code becomes
$(form).ajaxSubmit({
target: _result, dataType: 'json',
success: function(data) {
var type = (data.result==='error') ? 'alert-danger' : 'alert-success';
/////////////////////////////////////////////
if (data.result !== 'error') {data.message="Thanks, your submission is successful!";}
else { data.message = "Submition failed";}
//////////////////////////////////////////////
_result.removeClass( 'alert-danger alert-success' ).addClass( 'alert ' + type ).html(data.message).slideDown(400);
if (data.result !== 'error') { $(form).clearForm().find('input').removeClass('input-focused'); }
}
});
as clear now it is not important to get the solution but also so important to understand the code.

Related

e.PreventDefault and ajx submit not working together [return true] is not working

I have a function to check whether email exist, but I want to submit the form only if the email doesn't exist
So I wrote following function:
$("#form-1").on("submit",function(e){
e.preventDefault();
var given_email=document.getElementById("email");
var data = $("#form-1").serialize();
$.ajax({
type : 'POST',
url : 'check.php',
data : data,
beforeSend: function() {
$(".submit").val('sending ...');
},
success : function(response) {
var response = JSON.parse(response);
if(response.status=='error'){
alert("Sorry This Email Already Used ");
return false;
} if(response.status=='true') {
return true;
$(this).submit();
}
}
});
});
Now if it return true also i cant submit the form . Please help.
i saw this question and answer e.preventDefault doesn't stop form from submitting . But no effect
Notes
even i tried
if(response.status=='true') { $("#form-1").submit(); } .
But this also not working
The return statement is returning before the form is submitted
if(response.status == 'true') {
//return true; // returns before the form is submitted
$(this).submit();
return true; // move return after submit
}
Suggestion
You are thinking about this, the wrong way, let PHP handle the checking and insert in the backend.
First Solution
In your PHP do something like
$querycheck = mysqli_query($con,"SELECT * FROM Persons");
$countrows = mysqli_num_rows($querycheck );;
if($countrows == '1')
{
echo json_encode(['message' => 'Sorry This Email Already Used']);
}
else
{
// insert statement here
echo json_encode(['message' => 'Submitted']);
}
In your JS
$("#form-1").on("submit",function(e){
e.preventDefault();
var given_email=document.getElementById("email");
var data = $("#form-1").serialize();
$.ajax({
type : 'POST',
url : 'check.php',
data : data,
beforeSend: function() {
$(".submit").val('sending ...');
},
success : function(response) {
var response = JSON.parse(response);
alert(response.message); // display the message here to the user.
}
});
});
Second Solution
save the form in a variable.
$("#form-1").on("submit",function(e){
e.preventDefault();
const form = $(this); // get the current form
var given_email=document.getElementById("email");
var data = $("#form-1").serialize();
$.ajax({
type : 'POST',
url : 'check.php',
data : data,
beforeSend: function() {
$(".submit").val('sending ...');
},
success : function(response) {
var response = JSON.parse(response);
if(response.status=='error'){
alert("Sorry This Email Already Used ");
return false;
} if(response.status=='true') {
form.submit(); // submit the form here
return true;
}
}
});
});

jQuery AJAX post returns 403 error

I have the following script for AJAX to do login, but with some passwords that contain characters like "!##" it will return 403 error and will not submit to the PHP.
$(document).ready(function () { // When the document is ready
$('#login').click(function (e) { // We attach the event onchange to the select element
e.preventDefault();
var form_info = "";
$('#login_form *').filter(':input').each(function(){
if(this.value !== ""){
form_info += this.name;
form_info += "=";
form_info += encodeURIComponent(this.value);
form_info += "&";
}
});
form_info += "function_name=login";
var form = $('#login_form').serialize() + "&function_name=login";
$.ajax({
url: "function_ajax.php", // path to you php file
type: "post", // We want a POST request
dataType: 'html',
data: form_info,
statusCode:
{
404: function () {
alert('Could not contact server.');
},
500: function () {
alert('A server-side error has occurred.');
}
},
error: function ()
{
alert('A problem has occurred.');
},
beforeSend: function ()
{
alert(form_info);
alert(form);
},
complete: function ()
{
},
success: function (data) { // The function to execute if the request is a -success-,
if(data === "1"){
if (document.referrer !== "") {
window.location.href = document.referrer;
}
else{
window.location.href = "some_domain"
}
}
else if (data === "2")
{
alert("invalid");
}
else {
alert("empty");
}
}
});
});
});
You will find that I'm trying both ways to encode each element and the serialize just to check if I'm getting the same result, and I'm getting the same result, but still, it's getting this error.
If I try to encode the whole serialize, then I will not get the error but in PHP, the $_POST array will have the first key as the data I'm sending with no value.
encodeURIComponent($('#login_form').serialize()) + "function_name=login"
then the $_POST will be like
array(
[email=email#gmail.com&password=pass123!##&function_name=login]=>
)
which will not be useful for me.

Bootstrap modal ajax form submited many times

I call form in modal using ajax, and using a modal button .save-modal the form is submitted using ajax. There are many submissions for the form and I don't know why?
The following code in the page -form- requested by the modal:
```
#section('content')
<h1>kk</h1>
<div id="modal">
{!! Form::model('App\Solution',['url' => $actionPath, 'id' => 'sForm', 'class' => 'form-inline']) !!}
<div class="form-group">
{!! Form::label('title', __('Title')) !!}
{!! Form::text('title',$solution->title,['class' =>'form-control']) !!}
#php ($eleE = $errors->first('title'))
{{-- #include('layouts.form-ele-error') --}}
</div>
<div class="form-group">
{!! Form::label('description', __('Description')) !!}
{!! Form::textarea('description',$solution->description,['class' =>'form-control']) !!}
#php ($eleE = $errors->first('description'))
{{-- #include('layouts.form-ele-error') --}}
</div>
{!! Form::close() !!}
<script>
$(document).ready(function(){
$(".save-modal").click(function(e){
alert('many time alert') //
e.preventDefault();
$.ajax({
url: '{{$actionPath}}'+'/?'+Math.random(),
type: "POST",
data: $("#sForm").serialize(),
success: function(data){
$("#modal-body").html($(data).find('#flash-msg'))
$("#actions-modal").modal('hide')
//return true;
},
error: function(xhr, status, response){
if ( status == "error" ) {
var msg = "Sorry but there was an error: ";
// $( "#modal-body" ).html( msg + xhr.status + " " + xhr.statusText );
errors = xhr.responseJSON
console.log(errors)
$("#errors").html('');
$.each(errors,function(key, val){
console.log(key)
$("#errors").append('<span class="has-error help-block">'+val+'</sapn>')
//return false;
})
xhr.responseJSON = null;
}
return false;
}
})
return false;
})
});
</script>
</div>
#endsection
The alert after $(".save-modal").click(function(e){... is alerted many time, specially when closing the modal and open it again with repeating trying of save invalidated entries the increase in alert is not fixed i.e it is the sum of invalidated data submission trying in the previous opening of the modal.
The following is the modal code on the base page:
$(".action-create").click(function(e){
e.preventDefault();
alert($(this).attr('href'))
mhd = $(this).attr('title');//$(this).text()+' {{__("for Cavity")}}'+' '+$(this).attr('title');
href = $(this).attr('href')
//console.log(href)
$("#actions-modal").on('show.bs.modal', function(){
$("#modal-hd").html('<h4 style="display: inline">'+mhd+'</h4>');
$("#modal-body").html('<h4>{{__('Loading')}}<img src="/imgs/loading.gif" /></h4>')
gg(href)
})
$("#actions-modal").modal({
backdrop: 'static',
keyboard: false
});
});
$("#actions-modal").on('hidden.bs.modal', function(){
$("#modal-body").html('');
$(this).data('bs.modal', null);
//$(this).children('#errors').html('');
$("#errors").html('');
return false;
});
gg = function gg(){
$.ajax({
type: "GET",
url: href,
dataType: 'html',
success: function(data){
//console.log(data)
required = $(data).find("#modal");
$("#modal-body").html(required);
},
error: function(xhr, status, response ){
if ( status == "error" ) {
var msg = "Sorry but there was an error: ";
$( "#modal-body" ).html( msg + xhr.status + " " + xhr.statusText+ " With custom message:<br> "+ xhr.responseText );
//console.log(xhr)
}
}
});
return false;
}
I have tried to add return false in many parts of the code to cut any extra evaluation, I also tried to add random number to the ajax URL Math.random() but It seems that it executed many times.
There is also another form call on the same page called using the modal, and sometimes it be saved in addition to the called form!
When you call form using ajax then you should keep in mind that javascript/jquery code of document ready is executed every time you receive response.
so, when you first open you model ".save-modal" click event is binded. when close and reopen the model. again request goes to server ajax content loaded in browser window and again a click event is binded. This way you end up with multiple anonymous function binded to single event. all will execute on same event.
solution 1 (recomanded): Declare function in saperate js file or inline which is included in main page (not ajax). Then instead of binding click event using jQuery. call function from onclick property of your ".save-modal" button.
solution 2: declare a global variable "IsAjaxExecuting". Test if this variable is true then return from you save function (this will stop mutliple execution). if it is not true then make it true. execute you ajax function. when response received then make it false again. eg.
var IsAjaxExecuting= false; // new code
$(document).ready(function() {
$(".save-modal").click(function(e) {
if(IsAjaxExecuting) return; // new code
IsAjaxExecuting = true; // new code
alert('many time alert');
e.preventDefault();
$.ajax({
url: '{{$actionPath}}' + '/?' + Math.random(),
type: "POST",
data: $("#sForm").serialize(),
success: function(data) {
IsAjaxExecuting = false; // new code
$("#modal-body").html($(data).find('#flash-msg'))
$("#actions-modal").modal('hide')
//return true;
},
error: function(xhr, status, response) {
IsAjaxExecuting = false; // new code
if (status == "error") {
var msg = "Sorry but there was an error: ";
// $( "#modal-body" ).html( msg + xhr.status + " " + xhr.statusText );
errors = xhr.responseJSON
console.log(errors)
$("#errors").html('');
$.each(errors, function(key, val) {
console.log(key)
$("#errors").append('<span class="has-error help-block">' + val + '</sapn>')
//return false;
})
xhr.responseJSON = null;
}
return false;
}
})
return false;
})
});

Not working return in jquery ajax

this is my code:
$("#MainContent_btnSave").click(function () {
if (($("#MainContent_txtFunc").val() == "") || ($("#MainContent_cmbLoc").val() == "")) {
alert("Please fill options.");
return false;
}
else {
$("#msgbox-loading").show();
$.ajax({
type: "POST",
url: "Ajax.aspx",
data: { func: "getexist", catfunc: $("#MainContent_txtFunc").val(), catdes: $("#MainContent_txtDesc").val() },
success: function (data) {
var parsed = $(data);
var exist = parsed.filter("[id=exist]").text();
if (exist == "NO") {
return true;
}
if (exist == "Yes") {
alert("already defined.");
$("#msgbox-loading").hide();
return false;
}
},
error: function (xhr, ajaxOptions, thrownError) {
$("#msgbox-loading").hide();
HidePopup('popup');
alert(xhr.status + " " + thrownError);
}
});
};
});
My code is check mandatory and If empty mandatory, an error message display and or if not empty mandatory, first display the loading and then Ajax run.
After running Ajax i want if page send "NO" run button postback and if page send "Yes" stop button postback.
but Unfortunately, after run ajax and page send "Yes" run button post back.
please help.
you can use .ajaxComplete() for commands that you want to fire after ajax completed

Jquery Form on submit show success message

I have a form that uses Jquery to show a message for
*field required error message
I am trying to get it to show a success message if the form is submitted.
The form submits as long as the req fields are filled in.
Does anyone know how I can modify this code to show the "success" div if
all the "req" fields are filled out?
Thanks
$(function() {
function validateform() {
var valid = true;
$(".req").css("border","1px solid #ccc");
$(".req").each(function() {
if ( $(this).val() == "" || $(this).val().replace(/\s/g, '').length == 0 ) {
$(this).css("border","1px solided");$(".required").css("display","block");
valid = false;
}
});
return valid;
}
$("#submit").click( function() {
$('#myform').submit( validateform );
$('$name').submit();
});
});
submitHandler: function(form){
$(form).ajaxSubmit({
target: '#preview',
success: function() {
$('#form id').slideDown('slow'),
<!-- RESET THE FORM FIELDS AFTER SUBMIT STARTS HERE-->
$("#form")[0].reset();
<!--RESET THE FORM FIELDS AFTER SUBMIT ENDS HERE--->
}
});
}
There are two simple ways that will allow you to render a success message. You can either use ajax with the callback success function, or if you want a full post, you you can check at the top of your file if a certain POST was set, and if so, render a success message.
Here is an example of checking POST:
if(isset($_POST['name attribute posting'])) {
$util->showSuccessMessage();
//OR echo "<div class='popup'></div>"
}
And here is an example of using Ajax's success callback function:
function submitForm() {
$.ajax({
url : 'this_file.php',
type: 'POST',
success : showSuccessMessage //function call
})
}
$(function() {
function validateform() {
var valid = true;
$(".req").css("border","1px solid #ccc");
$(".req").each(function() {
if ( $(this).val() == "" || $(this).val().replace(/\s/g, '').length == 0 ) {
$(this).css("border","1px solided");
$(".required").css("display","block");
valid = false;
}
});
return valid;
}
$("#submit").click( function() {
$('#myform').submit(function()
{
if( validateform)
{
$('$name').submit();
}
} );
});
});
reference submit

Categories

Resources