jquery hide div on server response - ajax

I have this jquery script for showing a div on server response
function valLogin(){
//testing regular expression
var var1 = $("#username").val();
var var2 = $("#password").val();
$.ajax({ //Make the Ajax Request
type: "POST",
url: "login.php", //file name
data: "username="+var1+"&password="+var2, //data
success: function(server_response){
$("#logform").ajaxComplete(function(event, request){
if (server_response == 1){
window.location.reload();
return false
} else if (server_response == 0){
$('#logmess').show;
return false
}
}); //ajaxcomplete
}
}); //$.ajax
}
<div id="logmess" style="display:none;" align="right">Wrong UserID or password! <img src="/img/close.gif" onClick="$('#logmess').hide();" style="cursor:pointer;"/></div>
if server_response==0 then I show the div. I have a close button inside div with onClick="$('#logmess').hide();". the div is hiding but is appearing again after few seconds and this happens again and again. why the div is appearing again? Is something in my script that makes a loop?

Related

Not able to submit a form via Ajax

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

How to completely hide bootstrap modal after getting ajax response

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

Polling jQuery ajax for each. Check if element does not exist, if so prepend to div

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.

Jquery ready function with click and ajaxForm calls

I m really new working with JQuery and I have an error in my code. The next piece of code was working perfect when a user click a "Button", it load a file in a content div.
$(document).ready(function() {
$('.Button').click(function() {
var href = $(this).attr('href');
if( typeof href != "undefined" && href != ""){
$.ajax({
url: href,
dataType: 'text',
success: function(data) {
$('#content').html(data);
ultXML = href;
}
});
}
});
});
But now I m trying to use JQuery Form plugin (with this example http://www.malsup.com/jquery/form/) And it doesnt work (the ajaxForm call), I cant understand how to merge the next code in my orignal code. I try many ways, for example making 2 ready function but it also doesnt work,
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#myForm').ajaxForm(function() {
alert("Thank you for your comment!");
});
});
Where I must put the next piece of code in my original ready function? How can meger both?
$('#myForm').ajaxForm(function() {
alert("Thank you for your comment!");
});
Like this, work?
$(document).ready(function() {
$('.Button').click(function() {
var href = $(this).attr('href');
if( typeof href != "undefined" && href != ""){
$.ajax({
url: href,
dataType: 'text',
success: function(data) {
$('#content').html(data);
ultXML = href;
}
});
}
});
$('#myForm').ajaxForm(function() {
alert("Thank you for your comment!");
});
});

how to implement onpopstate? confused after reading so many things

I am loading content using AJAX, and changing URL by using pushastate, below is my code, can anybody tell me how to implement onpopstate to enable back button in my case.
HTML
<div id="tabs" style="margin:1px 0px 0px 15px;">
<ul class="tabs-ul">
<li id="boardLi" class="current-tab"><a class="current-tab" href="board.jsp">Board</a></li>
<li id="aboutLi">Info</li>
<li id="photoLi">Photo Albums</li>
</ul>
</div>
JS
$(document).ready(function() {
function loadContent(path,c,pageName){
$.ajax({ url: path, success: function(html) {
$('#ajax-content').empty().append(html);
window.history.pushState({path:''},'',pageName+'?tab='+c);
}
});
}
function checkC(target){
var c='';
if(target=='aboutme.jsp')
{c='info';}
else if(target=='board.jsp')
{c='board';}
else if(target=='photo.jsp')
{c='photo';}
else if(target=='tab.jsp')
{c='ht';}
return c;
}
$(".tabs-ul li a").on('click', function(e) {
e.preventDefault();
$('#ajax-content').empty().append("<div id='loading'><img src='images/preloader.gif' alt='Loading' /></div>");
$('.tabs-ul li a').removeClass('current-tab');
$('.tabs-ul li').removeClass('current-tab');
$(this).addClass('current-tab');
$(this).parent().addClass('current-tab');
var url = window.location.pathname;
var pageName = url.substring(url.lastIndexOf('/') + 1);
var target=$(this).attr('href');
var c=checkC(target);
loadContent(target,c,pageName);
return false;
});
var loaded = false;
window.onpopstate = function(e) {
if (!loaded) {
loaded = true;
return;
} else {
alert(window.loacation.back().pathname);
loadContent();
}
};
});
When user clicks on link, first of all I am adding removing class for loading then I am getting URL and getting the page name from that URL(saved in 'pageName'), 'target' is href attr of clicked link and 'c' is the value I will be showing in url(for example, example.com/profile.jsp?tab=info, here if the href is info.jsp then 'c' would be info), finally I am calling 'loadContent' function which loads ajax content and changes URL using pushState.

Resources