Bootstrap modal ajax form submited many times - javascript

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;
})
});

Related

how to edit the alert success submission in 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.

Error part in jQuery is missing

I build following JavaScript part and everything works fine. But I'm not sure if the code is completely right. Because in my script I only use success: function() but I don't use error. Is it a MUST to have error in a jQuery AJAX call?
Currently I'm catching the errors in my php controller function and echo them in the success part.
$(document)
.ready(function() {
var groupName = '';
var groupid = '';
$(".grp")
.click(function() {
$('.text-danger')
.html('');
groupName = $(this)
.data('groupname');
groupid = $(this)
.attr('id');
$('.text')
.html(groupName);
$('#dataModal')
.modal({
show: true
});
});
jQuery(".grpval")
.click(function(e) {
e.preventDefault();
jQuery.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]')
.attr('content')
}
, });
jQuery.ajax({
url: "{{ route('request_group') }}"
, method: 'post'
, data: {
'Gruppe': groupid
}
, success: function(data) {
if (typeof data.successsuccess != 'undefined') {
jQuery('.alert-success')
.show();
jQuery('.alert-success')
.html('<p>' + data.successsuccess + '</p>');
$('#dataModal')
.modal('toggle');
window.scrollTo(500, 0);
} else if (typeof data.successdberror != 'undefined') {
jQuery('.alert-danger')
.show();
jQuery('.alert-danger')
.html('<p>' + data.successdberror + '</p>');
$('#dataModal')
.modal('toggle');
window.scrollTo(500, 0);
} else {
jQuery.each(data.errors, function(key, value) {
jQuery('.alert-danger')
.show();
jQuery('.alert-danger')
.html('<p>' + value + '</p>');
$('#dataModal')
.modal('toggle');
window.scrollTo(500, 0);
});
}
}
});
});
});
EDIT: Here is the function from my Controller:
public function setGroupRequest(Request $request){
$validator = \Validator::make($request->all(), [
'Gruppe' => [new ValidRequest]
]);
$groupid = $request->input('Gruppe');
if ($validator->fails())
{
return response()->json(['errors'=>$validator->errors()->all()]);
}
try{
$groups_request = new GroupRequest();
$groups_request->idgroups = $groupid;
$groups_request->iduser = Auth::id();
$groups_request->request_active = 1;
$groups_request->save();
$db_status = 'success';
}catch(\Exception $e){
$db_status = 'error';
}
if($db_status == 'success'){
return response()->json(['successsuccess'=>'Record is successfully added']);
}else{
return response()->json(['successdberror'=>'DB Error! Values could not be saved.']);
}
}
Error handling is required as you never know different things on the internet might result in failure of request for example,
Network failure.
Lost database connection
Unauthorised access/access denied
Any variable being not defined
There is nothing wrong in your way of writing PHP error in success, but writing it in $ajax error callback function is preferred as it helps in separating error & success logic.
In fact you can add a jquery error callback function as well to your $ajax which will handle all the errors originating from above mentioned internet failures.
You can add error function, which will receive any type of error coming from backend.
jQuery.ajax({
url: "{{ route('request_group') }}",
method: 'data: {
'Gruppe': groupid
},
success: function(data) {
//code here
},
error: function (jqXHR, exception) {
//error handling
}
})
In your PHP file,
if ($query) {
echo "success"; //whatever you want to show on success.
} else {
die(header("HTTP/1.0 404 Not Found")); //Throw an error on failure
}
This way you can catch PHP error as well as any internet Network errors in your jquery ajax.

Ajax PHP Follow Script - Nothing stored in the database

I recently discovered a treehouse blog on ajax for beginners http://blog.teamtreehouse.com/beginners-guide-to-ajax-development-with-php I've been looking for a follow script for a while and I've hit a dead end. Currently the follow button fades as it should do, yet no values are stored in the database as of yet.
Profile.php (follow button):
<div id="followbtncontainer" class="btncontainer">Follow</div>
Ajax.js
$(function(){
$('#followbtn').on('click', function(e){
e.preventDefault();
$('#followbtn').fadeOut(300);
$.ajax({
url: '../ajax-follow.php',
type: 'post',
data: {'action': 'follow'},
success: function(data, status) {
if(data == "ok") {
$('#followbtncontainer').html('<p><em>Following!</em></p>');
var numfollowers = parseInt($('#followercnt').html()) + 1;
$('#followercnt').html(numfollowers);
}
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
}); // end ajax call
});
$('body').on('click', '#morefllwrs', function(e){
e.preventDefault();
var container = $('#loadmorefollowers');
$(container).html('<img src="images/loader.gif">');
var newhtml = '';
$.ajax({
url: 'ajax-followers.php',
type: 'post',
data: {'page': $(this).attr('href')},
cache: false,
success: function(json) {
$.each(json, function(i, item) {
if(typeof item == 'object') {
newhtml += '<div class="user"> <img src="'+item.profile_pic+'" class="avi"> <h4>'+item.username+'</h4></div>';
}
else {
return false;
}
}) // end $.each() loop
if(json.nextpage != 'end') {
// if the nextpage is any other value other than end, we add the next page link
$(container).html('Load more followers');
} else {
$(container).html('<p></p>');
}
$('#followers').append(newhtml);
},
error: function(xhr, desc, err) {
console.log(xhr + "\n" + err);
}
}); // end ajax call
});
});
ajax.php
<?php require 'database.php' //<?php include 'session-check-index.php' ?>
<?php include 'authentication.php' ?>
<?php
session_start();
$follower=$_SESSION['id'];
$sql = "SELECT * FROM users WHERE username='$username'";
$result = mysqli_query($database,$sql);
$rws = mysqli_fetch_array($result);
$following=$rws['id'];
/**
* this script will auto-follow the user and update their followers count
* check out your POST data with var_dump($_POST)
**/
if($_POST['action'] == "follow") {
$sql=" INSERT INTO `user_follow` (`follower`, `following`, `subscribed`) VALUES ('$follower', '$following', CURRENT_TIMESTAMP);"
/**
* we can pass any action like block, follow, unfollow, send PM....
* if we get a 'follow' action then we could take the user ID and create a SQL command
* but with no database, we can simply assume the follow action has been completed and return 'ok'
**/
mysqli_query($database,$sql) or die(mysqli_error($database));
}
?>
I'm not sure if the actual $following and $follower values are causing the problem, and just not passing any data. Any help would be much appreciated, thanks!
try to change in ajax.js
$(function(){
$('#followbtn').on('click', function(e){
e.preventDefault();
$('#followbtn').fadeOut(300);
$.ajax({
url: '../ajax-follow.php',
...
the url parameter to :
url: 'ajax-follow.php',
See if it will work that way

Creating error handling in jQuery

I am trying to create an error message from jquery for my document.
I have populated a <select> menu with JSON data, they link to external HTML files to display weather for their Location, what I need is for an error message to appear if there is no HTML file for the option.
For example the locations are London, New York, Paris and Rome, all except Rome have an HTML file that has weather data in it and displays fine but when Rome is selected...Nothing happens! and when Rome is selected after another location has been selected it stays on the current data!
I am using jQuery to pull the data etc. its my gut feeling that it needs an if() statement but I'm not sure of the conditions of the statement!
My jQuery code is here...
$(document).ready(function () {
// The below function pulls in the data from the external JSON file
$.getJSON('json/destinations.json', function (data) {
// attaches it to a variable
var destinations = data.Destinations;
$(destinations).each(function (id, destination) {
$('#destinations').append('<option value="' + destination.destinationID + '">' + destination.destinationName + '</option>');
});
$("#destinations").change(function () {
$('#weatherForecasts').load('raw_html/' + $(this).val() + '_weather.html .ngtable', function () {
$('#weatherForecasts').show("slow");
});
});
});
// Hide statements for our extra fields and also the weather forecast DIV
$('#weatherForecasts').hide();
$('#extraFields').hide();
$('.errorMessage').hide();
// Function that allows us to see the extraFields when a radio button is checked!
$("input[name='survey1']").change(function () {
$("#extraFields").show("slow");
});
$("input[name='survey1']:checked").change(); //trigger correct state onload
});
http://api.jquery.com/load/
at the bottom of the page there is an example for handling errors:
$( "#success" ).load( "/not-here.php", function( response, status, xhr ) {
if ( status == "error" ) {
var msg = "Sorry but there was an error: ";
$( "#error" ).html( msg + xhr.status + " " + xhr.statusText );
}
});
So in your case
$("#destinations").change(function () {
$('#weatherForecasts').load('raw_html/' + $(this).val() + '_weather.html .ngtable', function (response, status, xhr) {
if (status == 'error'){
// do error things
}else{
$('#weatherForecasts').show("slow");
}
});
});

How to retain a particular item id through various calls?

I am trying to do this:
Have the user click some action. The action checks whether the user is logged in or not. If not, open a login dialog box, and if the user logs in correctly, update the original page.
I got almost all this working except the part of after successful login. The problem is that the code seems to not have access to the item_id which I was trying to update. Instead, when I try to set the item id (problem_id in this case) in the login form of the popup box, the id is the number of the id that is the last one on the page, and not the one that was clicked.
Here is what I am trying to do in the jQuery:
<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();
});
// Called right away after someone clicks on the vote up link
$('.vote_up').click(function()
{
var problem_id = $(this).attr("data-problem_id");
//alert ("In vote up click, problem_id: " + problem_id );
voteUp(problem_id);
//Return false to prevent page navigation
return false;
});
var voteUp = function(problem_id)
{
alert ("In vote up function, problem_id: " + problem_id );
var dataString = 'problem_id=' + problem_id + '&vote=+';
$.ajax({
type: "POST",
url: "/problems/vote.php",
dataType: "json",
data: dataString,
success: function(data)
{
alert ("vote success, data: " + data);
// ? :)
},
error : function(data)
{
alert ("vote error");
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');
alert ("after dialog was open");
// prevent the default action, e.g., following a link
return false;
}
else
{
alert ("not");
}
//alert(JSON.stringify(data));
} // Closing error case
}); // Closing AJAX call.
};
$('.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()
{
alert("in login button fnction");
$.ajax({
url:'url to do the login',
success:function() {
//now call cote up
voteUp($problemId.val());
}
});
});
});
</script>
and here is the login form:
<div id="login_div">
<form id="login_form" method="post" action="">
<p>
<label for="name"><span>Your Email:</span></label> <input type="text" name="email" id="email" />
</p>
<p>
<label for="name"><span>Your Password:</span></label> <input type="password" name="user_pass" id="user_pass">
</p>
<input type="hidden" id="problem_id" name="problem_id" value="<?php echo $problem_id; ?>" />
<span class="no_such_user" style="color: red; display:none">The login and password does not match our records.</span>
<span class="password_error" style="color: red; display:none">The password much be 5 characters or more.</span>
<span class="login_success" style="color: green; display:none">You successfully logged in.</span>
<p>
<input type="submit" value="Log In" />
</p>
</form>
</div>
But the problem_id which is being set in this form isn't the one being clicked on, even though I am trying to save it in my jQuery.
Also, here is the code that gets executed for login:
$(function()
{
$("#login_div input[type=submit]").click(function()
{
var email = $("#email").val();
var password = $("#user_pass").val();
//alert("Email: " + email);
//alert("password: " + password);
var dataString = 'email='+ email + '&password=' + password;
if( !email )
{
alert ("1");
$('.login_success_email_empty').fadeOut(200).hide();
$('.login_error_email_empty').fadeOut(200).show();
}
else
if( !password || password.length < 5)
{alert ("2");
$('.password_success').fadeOut(200).hide();
$('.password_error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "../auth/login_ajax.php",
dataType: "json",
data: dataString,
success: function(json)
{
$('.password_error').fadeOut(200).hide();
$('.no_such_user').fadeOut(200).hide();
$('.login_success_email_empty').fadeOut(200).hide();
$('.login_success').fadeIn(200).show();
// Closing the dialog bosx
$('#loginpopup').dialog('close');
// Swapping out the header div
$('#header_logged_out').hide();
$('#header_logged_in').show();
// Now also need to retrieve the problem_id
problem_id = $("#problem_id").val();
//$problemId = $('#theProblemId', '#loginpopup').val();
var $problemId = $('#theProblemId', '#loginpopup');
alert ("After login, problem_id: " + problem_id + " and problemId was: " + $problemId);
},
error : function(json)
{
alert ("error");
// Output the result.
errorMessage = json.responseText;
alert ("ErrorMessage: " + errorMessage );
if ( errorMessage == 'no_such_user' )
{
$('.no_such_user').fadeOut(200).hide();
$('.no_such_user').fadeOut(200).show();
}
}
});
}
return false;
});
});
and I am just not sure how to get that problem_id which was set in the original jQuery code to be recognized in the jQuery code that executes after login.
Because what I really need to do is update that particular problem depending on whether the user was logged in.
And how do I know in the original code that processes the votes, whether the login in the dialog box was successful or not?
By the way, I am working on this page: http://www.problemio.com
It seems that you might be better served using the jquery forms /ajax submit plugin:
http://be.twixt.us/jquery/formSubmission.php
$('loginDiv > form').submit(function() {
var options = {
url = "../auth/login_ajax.php",
[...]
};
$(this).ajaxSubmit(options);
return false; //this line is required to make sure that the page doesn't get redirection to /auth/login_ajax.php
});
This way it won't reload any of the javascript, preserving any variables that have already been set. You can therefore set the problem ID before the login, and then do stuff with it afterward.

Categories

Resources