I am trying to display a success or failure message after submit with this AJAX code but it's not working. The form submits successfully, but the messages do not appear.
My code:
$('#frm-create-vessel').on('submit', function (e) {
e.preventDefault();
var data = $(this).serialize();
var url = $(this).attr('action');
$.post(url, data, function (data) { //submit to table
if(data == true ){ //if the form submits successfully
$('#createvesselmessages').removeClass('hide').addClass('alert alert-success alert-dismissible').slideDown().show();
$('#createvesselmessages_content').html('<h4>Vessel Created Successfully</h4>');
$('#modal').modal('show');
$("#createvesselmessages").fadeOut(4000);
} else { //if the form fails
alert('false')
}
showVesselInfo(data.vessel_name);
});
$(this).trigger('reset');
})
Related
EDIT
the code below seems to works as long as the form is valid.
but when it is not the case (clean method in django form) h1 text of form is removed (????) and the error messages are not displayed...
I guess that an empty popup.html is return via ajax and as there is no button to interact with nothing happen but why h1 text is removed...???
var prevent_edit = false;
var prevent = false;
// popup d'informations indiquant que la levée d'insue a déjà été faite
// pour ce patient
$("#form_unblind_edit").submit(function (event) {
console.log('form_unblind_edit click - first')
console.log('prevent_edit - first', prevent_edit)
if (!prevent_edit) {
event.preventDefault();
}
});
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
// affichage des informations sur le patient sélectionné pour la ré-allocation
$("#unblind_edit").on("click", function (event) {
console.log('click unblind edit');
var csrftoken = getCookie('csrftoken');
var patient = $("#id_pat").val();
$.ajax({
type: "POST",
url: '/unblind/already_unblind/',
data: {
csrfmiddlewaretoken: csrftoken,
'patient': patient,
},
dataType: 'html',
success: function (data) {
console.log('success');
// var prevent_edit = false;
$("#can_unblind").html(data);
$('#unblindconfirm').modal('show');
$('body').on('click', '#edit_button_OK', function (event) {
console.log('edit_button_OK')
$('#edit_button_OK').attr("disabled", "disabled");
prevent_edit = true;
console.log('prevent_edit', prevent_edit);
$("#form_unblind_edit").submit();
})
},
error: function (resultat, statut, erreur) {
console.log('error');
}
});
});
i need some help for popup with ajax
User complete the form and submit the form by clicking a button
I prevent submit with event.preventDefault(); to display a popup.
But I need to ask database for informations to display on popup, so I use an ajax query
when ajax success, popup is displayed with informations from database and I want the form t be submited by clicking on "OK" button of the popup
but it failed, I think, because event (submit) is attached to a button that is not present in DOM when page load...
JS
$(document).ready(function () {
var prevent_edit = false;
// prevent submission
$("#form_unblind_edit").submit(function (event) {
if (!prevent_edit) {
event.preventDefault();
}
});
// ajax query that display popup
$("#unblind_edit").on("click", function (event) {
var csrftoken = getCookie('csrftoken');
var patient = $("#id_pat").val();
$.ajax({
type: "POST",
url: '/unblind/already_unblind/',
data: {
csrfmiddlewaretoken: csrftoken,
'patient': patient,
},
dataType: 'html',
success: function (data) {
$("#can_unblind").html(data); //popup html attach to DOM
$('#unblindconfirm').modal('show'); //popup displayed
$('body').on('click', '#edit_button_OK', function (event) {
console.log('edit_button_OK'); // WORKING
prevent_edit = true;
$("#form_unblind_edit").trigger('submit'); //form submission = NOT WORKING
})
}
});
});
Maybe change the type of the submit button in the form to "button"
<button type="button">Submit</button>
This way the submit action is not executed when the user clicks submit and instead you display the popup. Then you should be able to submit the form using JQuery.
$("#form_unblind_edit").trigger('submit');
// From Ctp
hcp_btn.on('click', function(){
var value = hcp_field.val();
if(value != '')
{
$.ajax(
{
type: 'POST',
url: ajax_url+'users/add_hcp_type/'+value,
success:function(response)
{
if(response == 'exist')
{
$("#hcp_error").show();
hcp_btn.addClass('disabled');
}
else{
$("#hcp_type_modal").modal('hide');
$("#hcp_type").html(response);
}
}
});
}
});
// For Controller
$this->autoRender = false;
$this->layout = 'ajax';
$this->viewPath = 'Elements';
$this->render('hcp_types');
![This type of background left after modal close in ajax success function][1]
I am using cakephp and rendering an element using ajax and dynamically loading data inside the ctp. But after getting ajax response inside ajax success function i am trying to close bootstrap modal nut modal is not completely close some transparent background is left.
Use this to clean the left background
//when hidden
$('#hcp_type_modal').on('hidden.bs.modal', function(e) {
$('.modal-backdrop').remove();
});
I am getting HTTP error 405 verb not allowed. As sometimes code works and sometimes throws http 405 error, I need to understand whether this is programming problem or server configuration problem. I am using ajax with jquery. I have gone through all related posts here and tried all recommended options related with the code. Please help.
my javascript code is as follows
$(function() {
$('.error').hide();
$(".button").click(function() {
// validate and process form
// first hide any error messages
$('.error').hide();
var name = $("input#name").val();
if (name == "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
var email = $("input#email").val();
if (email == "") {
$("label#name_error").show();
$("input#email").focus();
return false;
}
var textquery = $("textarea#textquery").val();
if (textquery == "") {
$("label#name_error").show();
$("textarea#textquery").focus();
return false;
}
var dataString = name + email + textquery;
// alert (dataString);return false;
$.ajax({
type: "POST",
url: "samplemail.aspx",
data: dataString,
success: function() {
$('#contact_form').html("<div id='message'></div>");
$('#message').html("<h2>Contact Form <br> Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
.fadeIn(1500, function() {
$('#message').append("<img id='checkmark' src='images/check.png' />");
});
}
});
return false;
});
});
runOnLoad(function(){
$("input#name").select().focus();
});
Problem solved
the way Of passing parameter was wrong i.e.data : datastring .
The correct way is data : { name : name, email: email, textquery: textquery}
I have a div #notification-data which on $(document).ready gets populated with multiple <li></li> from $.post.
The $.post then gets called setTimeout(poll_n,9000); so data is up-to-date.
So im not updating all the data every time, I would like to do check if the <li></li> already exists in #notification-data, if it does not exist then I would like to prepend() it to #notification-data.
The data comes in the form of:
<li id="new_notification_1" class="seen_0 li_notification">blah</li>
<li id="new_notification_2" class="seen_0 li_notification">bleh</li>
As an extra question, is this the correct way of long polling?
Here is my code:
function poll_n(){
$.post('<?php echo $siteUrl ?>notifications.php?x=' + (new Date()).getTime() +'', function(data) {
$(data).find(".li_notification").each(function () {
var li_id = $(this).attr('id');
if ($(li_id).closest('#notification-data').length) {
//do nothing
} else {
$('#notification-data').append(??not_sure_what_goes_here??); // process results here
}
});
setTimeout(poll_n,9000);
});
}
EDIT - After answer I have now got this but it does not work (I get nothing in the console).
success: function(data){
$(data).find(".li_notification").each(function() {
var id = $(this).attr('id'),
notification = $('#notification-data');
console.log(id);
console.log('hello');
if (notification.find('#' + id).length === 0) {
// notification doesn't exists yet then lets prepend it
notification.prepend('#' + id);
}
});
},
You can try this:
function poll_n() {
$.ajax({
type: 'POST',
url: 'your url',
success: function(data){
var notification = $('#notification-data');
$.each($(data), function(){
var id = this.id;
if (notification.find('#' + id).length === 0) {
// notification doesn't exists yet then lets prepend it
notification.prepend(this);
}
});
},
complete: function(jqXHR, status) {
if (status === 'success') {
setTimeout(poll_n, 9000);
}
}
});
}
You must call poll_n() again after the request has been completed.
So I have been playing around with the Anti Forgery Token, making progress thanks to you guys.
I have figured out a solution to merge form values anf get my ActionMethods to not puke on the AntiForgery token... I have unfortunately broken validation in the process. The AJAX post fires before client side validation / client side validation is ignored. Server side works however I would dig some validation before the post.. Here is the code I am using.
$(document).ready(function () {
$('input[type=submit]').live("click", function (event) {
event.preventDefault();
// Form with the AntiForgeryToken in it
var _tokenForm = $(this).parents().find("#__AjaxAntiForgeryForm");
// Current Form we are using
var _currentForm = $(this).closest('form');
// Element to update passed in from AjaxOptions
var _updateElement = $(_currentForm).attr("data-ajax-update");
// Serialize the array
var arr = $(_currentForm).serializeArray();
//Merge TokenForm with the CurrentForm
$.merge(arr, $(_tokenForm).serializeArray());
// The AJAX Form Post stuff
$.ajax({
type: "POST",
url: $(_currentForm).attr('action'),
data: arr,
success: function (data) {
$(_updateElement).html(data);
}
});
return false;
});
});
So I am thinking that I need to handle the client side validation some way before the $.ajax goo... Any suggestions would possibly save me some time.
Call this:
var formValid = $("#FormId").validate().form();
if (!formValid) return false;
Added into your code:
$(document).ready(function () {
$('input[type=submit]').live("click", function (event) {
event.preventDefault();
// Form with the AntiForgeryToken in it
var _tokenForm = $(this).parents().find("#__AjaxAntiForgeryForm");
// Current Form we are using
var _currentForm = $(this).closest('form');
var isValid = $(_currentForm).validate().form();
if (!isValid) return false;
// Element to update passed in from AjaxOptions
var _updateElement = $(_currentForm).attr("data-ajax-update");
// Serialize the array
var arr = $(_currentForm).serializeArray();
//Merge TokenForm with the CurrentForm
$.merge(arr, $(_tokenForm).serializeArray());
// The AJAX Form Post stuff
$.ajax({
type: "POST",
url: $(_currentForm).attr('action'),
data: arr,
success: function (data) {
$(_updateElement).html(data);
}
});
return false;
});
});