button click delete dom hide element preventing me to show it - javascript

I'm doing a simple thing but I do not understand why it occurs the following problem: when I enter a value in the form and click the button to execute the function the 'loading' the element disappears and can not be shown.
The Javascript is the following:
<div>
<input id="magLog" name="magLog" type="text" style="width: 500px;"/>
<button id="StartITSMcheck">Check</button>
</div>
<div>
<div id="logContainer" class="filtersUNoBorder" style="padding-left: 8px; height:auto">
<div id="loading" class="clear loading">
Caricamento in corso...</div>
<!--Add text after check-->
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#loading").hide();
});
$("#StartITSMcheck").click(function () {
if ($("#magLog").val() != "" && $("#magLog").val() != undefined) {
$('#loading').show(); // show the loading message.
$.ajax({
type: "GET",
url: '<%= Url.Action("StartITSMcheck", "Integration") %>',
async: false,
data: { "magLog": $("#magLog").val() },
datatype: "html",
success: function (result) {
$("#logContainer").html(result);
$('#loading').hide(); // hide the loading message
},
error: function (req, status, error) {
if (req.responseText.indexOf('12017') != -1) {
alert("CATCH: Status: " + status + " Error " + req.responseText);
}
else {
alert("Error getting data.com -> Req.responseText: " + req.responseText + "Req.status: " + req.status + " status: " + status + " error: " + error);
}
}
});
} else $("#logContainer").html("<p>Gentilmente inserire un magazzino logico</p>");
});
</script>

$("#logContainer").html(result);
This is probably the cause of the problem. You're replacing everything inside the div with your response, that includes your loading element. Try placing it outside the div, like this:
<div id="logContainer" class="filtersUNoBorder" style="padding-left: 8px; height:auto">
<!--Add text after check-->
</div>
<div id="loading" class="clear loading">Caricamento in corso...</div>

Related

Button disappears when clicked in javascript

In case that chosen attributes are the same, after clicking "Save button" - button disappears.
(it disappears from code, got deleted)
[Image before clicking][1]
[Image after clicking][2]
Most confusing thing is that, add button was coded the same but it works well...
I've got no clue what might be the case here.
Button:
<input type="button" height="20" class="btn btn-warning" onclick="return saveEdit()" value="Save" />
function saveEdit() {
var elem = $('#Domain_Edit');
$.ajax({
url: "/Domain/DomainEdit",
type: "post",
data: elem.serialize(),
cache: false,
success: function (result) {
if (result.redirectTo) {
alert(window.location.href = result.redirectTo + '?siteMessage=' + result.siteMessage);
}
else
{
$(elem).html(result);
}
},
error: function (xhr, status, error) {
$(elem).html('<div class="alert alert-danger" role="alert">' + xhr.status + " " + xhr.statusText + '</div>');
}
});
}
Code of button on page:
<input type="button" height="20" class="btn btn-warning" onclick="return btnSave('89515a0b-a671-4eff-a0eb-61c1d268f696')" value="Save">
function btnSave(id) {
var elem = $("." + id).closest('#DomainTrust_Edit');
$.ajax({
url: "/Domain/DomainTrustEdit",
type: "post",
data: $("." + id).closest('#DomainTrust_Edit').serialize(),
cache: false,
success: function (result) {
if (result.redirectTo) {
// The controller action returned a JSON object with the redirectTo property
window.location.href = result.redirectTo + '?siteMessage=' + result.siteMessage;
} else {
// The controller action returned a partial view with the form and the errors so update of the containing FORM with it is needed.
$(elem).html(result);
}
},
error: function (xhr, status, error) {
$(elem).html('<div class="alert alert-danger" role="alert">' + xhr.status + " " + xhr.statusText + '</div>');
}
});
}
Is your button located inside the #Domain_Edit element?
Since .html(result) replaces all html inside #Domain_Edit so if your button is inside that element, that would explain why it got removed.

How to use php session inside jQuery?

I'm facing with this problem : I have made a button report on every comment in a website to let people to report comment. I want if someone click on the button to be redirected to the popup window to let the people to login or register. I want after login/register is done this request(count) is send to database.
My problem is how can I perform this inside jQuery code :
if(isset($_SESSION['session_user'])) { /*do something*/ }.
Here is the code of what I already do :
return this.each(function (i) {
var count = 0;
$(this).append("<button class='" + parametres.button + " report" + i + "''><span class='glyphicon glyphicon-alert'> </span>" + parametres.textBtn + "</button>").on('click', function () {
// if ("<%php !$_SESSION['user_session'] %>") {
// Popup window
$('#myModal').modal('show');
// pane register
$('.btnReg').on('click', function () {
$.ajax({
url: 'includes/register.php',
data: {name: $('#nameReg').val(), email: $('#emailReg').val(), password: $('#passwordReg').val()},
type: 'POST',
beforeSend: function () {
//$('#error').fadeOut();
$("#error").html('<div class="alert alert-info"> <span class="glyphicon glyphicon-transfer">Envoi en Cours ...</span></div>');
},
success: function (data) {
if (data == 'exist') {
$("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span>Ce mail n\'est pas disponible !</div>');
} else if (data == 'success') {
$("#error").html('<div class="alert alert-success"> <span class="glyphicon glyphicon-info-sign"></span>Inscripton effectuée !</div>');
} else {
$("#error").fadeIn(1000, function () {
$("#error").html('<div class="alert alert-danger"><span class="glyphicon glyphicon-info-sign"></span>' + data + ' !</div>');
});
}
}
});
});
// pane login
$('.btnLog').on('click', function (elem, i) {
//event.preventDefault();
$.ajax({
url: 'includes/login.php',
data: {email: $('#emailLog').val(), password: $('#passwordLog').val()},
type: 'POST',
success: function (data) {
if (data == 'success') {
$("#error").html('<div class="alert alert-info"> <span class="glyphicon glyphicon-transfer">Connexion en Cours...</span></div>');
setTimeout(' window.location.href = "index.php"; ', 4000);
} else { //alert(data);
$("#error").fadeIn(1000, function () {
$("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span>' + data + ' !</div>');
});
}
}
});
});
//}
//This is the thing to be done after login, where to put it ?
count = count + 1;
if (count >= parametres.juge) {
var content = $(this).text();
var click = count;
var tag = "<button class='" + parametres.button + " report" + i + "''>" + parametres.textBtn + "</button>";
$.ajax({
url: 'includes/controller.php',
data: {content: content,
click: click,
tag: tag},
type: 'POST',
success: function (data) {
if (!data.error) {
//alert(data);
alert('Success!');
}
}
});
$(this).animate({'opacity': 0}, 1000, function () {
$(this).text(parametres.textReplace).css('color', parametres.colorTex);
}).animate({'opacity': 1}, 1000);
}
});
});
You can use php to determine whether or not the user is logged in, and if they are print their id into a hidden input variable.
<?php isset($_SESSION['session_user']): ?>
<input type="hidden" id="session_user_id" value="<?php echo $_SESSION['session_user_id']; ?>">
<?php endif; ?>
Then in js when you need the id, you can use jquery to find it:
var session_user_id = $('#session_user_id').val();
Have you tried like this
if( <?php isset($_SESSION['session_user']) ?>) { do something }.

textarea update not working with ajax submit

I have a textarea field where some data already exist
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea name="message" id="editor1">There is some lines with basic html tags like strong,underline</textarea>
If I change above to like this
<textarea name="message" id="editor1">Some new lines with basic html tags like strong,underline</textarea>
But after submit action Everything works fine but I always get old textarea data not new updated data.
While js code
$(document).on('click', ".send-mail", function (e) {
e.preventDefault();
var s_message=$("textarea[name=message]").val();
$('#send_mail').modal({backdrop: 'static', keyboard: false}).one('click', '#sendmail', function () {
sendMail(s_message);
});
});
function sendMail(s_message) {
jQuery.ajax({
url: 'request/sendmail.php',
type: 'POST',
data: s_message,
dataType: 'json',
success: function (data) {
if (data.status == "Success") {
$("#notify .message").html("<strong>" + data.status + "</strong>: " + data.message);
$("#notify").removeClass("alert-danger").addClass("alert-success").fadeIn();
$("html, body").scrollTop($("body").offset().top);
} else {
$("#notify .message").html("<strong>" + data.status + "</strong>: " + data.message);
$("#notify").removeClass("alert-success").addClass("alert-danger").fadeIn();
$("html, body").scrollTop($("body").offset().top);
}
}
});
}
</script>
I need new updated data to a PHP Post variable. Why it is not working?

jQuery validation submitHandler not work in $.ajax post form data

I have Send data using $.ajax and validation with jQuery validation plugin like this :
<div class="" id="ajax-form-msg1"></div>
<form id="myform" action="load.php">
<input type="input" name="name" id="name" value="" />
<input type="hidden" name="csrf_token" id="my_token" value="MkO89FgtRF^&5fg#547#d6fghBgf5" />
<button type="submit" name="submit" id="ajax-1">Send</button>
</form>
JS:
jQuery(document).ready(function ($) {
$('#myform').validate({
rules: {
name: {
required: true,
rangelength: [4, 20],
},
},
submitHandler: function (form) {
$("#ajax-1").click(function (e) {
e.preventDefault(); // avoid submitting the form here
$("#ajax-form-msg1").html("<img src='http://www.drogbaster.it/loading/loading25.gif'>");
var formData = $("#myform").serialize();
var URL = $("#myform").attr("action");
$.ajax({
url: URL,
type: "POST",
data: formData,
crossDomain: true,
async: false
}).done(function (data, textStatus, jqXHR) {
if (data == "yes") {
$("#ajax-form-msg1").html(' < div class = "alert alert-success" > ' + data + ' < /div>');
$("#form-content").modal('show');
$(".contact-form").slideUp();
} else {
$("#ajax-form-msg1").html('' + data + '');
}
}).fail(function (jqXHR, textStatus, errorThrown) {
$("#ajax-form-msg1").html(' < div class = "alert alert-danger" >AJAX Request Failed < br / > textStatus = ' + textStatus + ', errorThrown = ' + errorThrown + ' < /code></pre > ');
});
});
}
});
});
In action my form validate using jQuery validation but after validation not submit and not send data.
how do fix this problem?!
DEMO HERE
The submitHandler is expecting a submit and you have a click event inside it and then an ajax call.
If you have a button type="submit" inside a form you don't even need a click event, the plugin will do the validation automatically. So just make the ajax call inside the submitHandler.
If you need to bind the action to a button using the click event, the proper approach should be something like this:
$('#button').click(function(){
var form = $('#myform').validate({...}); #store the validator obj
if (form.is_valid()){
// submit using ajax
} else {
// dont do anything
}
});
Call form.submit() at the end of your done function.
See: http://jqueryvalidation.org/validate/
Also, you do not need $("#ajax-1").click() because the submitHandler will be called automatically when you click on that button anyways. You can test this yourself by putting a console.log as the first line of submitHandler. Then fill out the form and press the button. See if it prints out your log message.
In submitHandler you are handling the submit , then again why did you write click event?
Here is the fix.
jQuery(document).ready(function($) {
$('#myform').validate({
rules: {
name: {
required: true,
rangelength: [2, 20],
},
},
submitHandler: function(a, e) {
//a is form object and e is event
e.preventDefault(); // avoid submitting the form here
$("#ajax-form-msg1").html("<img src='http://www.drogbaster.it/loading/loading25.gif'>");
var formData = $("#myform").serialize();
var URL = $("#myform").attr("action");
$.ajax({
url: URL,
type: "POST",
data: formData,
crossDomain: true,
async: false,
success: function(data) {
console.log(data)
},
error: function(err) {
console.log(err)
}
}).done(function(data, textStatus, jqXHR) {
if (data == "yes") {
$("#ajax-form-msg1").html(' < div class = "alert alert-success" > ' + data + ' < /div>');
$("#form-content").modal('show');
$(".contact-form").slideUp();
} else {
$("#ajax-form-msg1").html('' + data + '');
}
}).fail(function(jqXHR, textStatus, errorThrown) {
$("#ajax-form-msg1").html(' < div class = "alert alert-danger" >AJAX Request Failed < br / > textStatus = ' + textStatus + ', errorThrown = ' + errorThrown + ' < /code></pre > ');
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.validation/1.14.0/jquery.validate.min.js"></script>
<form id="myform" action="load.php">
<input type="input" name="name" id="name" value="" />
<input type="hidden" name="csrf_token" id="my_token" value="MkO89FgtRF^&5fg#547#d6fghBgf5" />
<button type="submit" name="submit" id="ajax-1">Send</button>
</form>
Use success and error call backs to get data or error messages.
Note: Here (In StackOverflow) you will get 404 Page Not Found error when you submit. So try in your local.

jQuery .hide() and .show() not working

I have this code generate dynamically using php code:-
<div class="mailList" id="M_6">
<div class="mailListHeader" id="H_6">
<img style="float:right; display:none;" class="loaderIMG" id="LOADER_6" src="images/preloader.gif">
Sent by <strong>Admin</strong> on <strong>Oct 03 2013 02:53 PM</strong> to <strong>Received Response</strong> for Quarter <strong>3</strong> Year <strong>2013</strong>.<br>
Subject: <strong>Test Mail</strong><br>
</div>
<div class="mailListContent" id="C_6">
<div class="closeContent" id="CC_6">Close [x]</div>
<span id="SPAN_6"></span>
</div>
<div class="mailListFooter" id="F_6">
<span class="mailContentBtn" id="MCBTN_6" style="font-size:11px; color:#09C; cursor:pointer;">
View Content
</span>
<span class="mailListBtn" id="MLBTN_6" style="float:right; font-size:11px; color:#C06; cursor:pointer;">
Successfull-[0] Failed-[4]
</span>
</div>
</div>
Then, user can click View Content or Successfull-[0] Failed-[4] that will make a ajax request than display result in div mailListContent. Below is code for the jquery ajax request:-
$(".mailContentBtn, .mailListBtn").click(function(){
var currentId = $(this).attr('id');
currentId = currentId.split("_");
var actualId = currentId[1];
if($("#C_"+actualId).is(":visible")) {
$("#C_"+actualId).hide("slow","swing");
}
$("img#LOADER_"+actualId).show();
if(currentId[0]=="MCBTN") {
var dataString ="action=getMailContentByID&mailID="+actualId;
} else {
var dataString ="action=getMailListByID&mailID="+actualId;
}
$.ajax({
type: "POST",
url: "include/getMail.php",
data: dataString,
cache: false,
async: false,
success: function(html) {
$("#SPAN_"+actualId).empty();
$("#SPAN_"+actualId).append(html);
$("#C_"+actualId).show("slow","swing");
$("img#LOADER_"+actualId).hide();
}
});
});
The request and the events works fine, the problem is every time user click at View Content or Successfull-[0] Failed-[4] the loading image is not display. As you can see, I give a unique ID for every loading image than only 1 loading image will display on clik. There is no error in inspect code in Google Chrome. How can I solve this?
Thank you.
In your call to $.ajax, change the "async" option to "true". Because in your case, the $.ajax is blocking the ui thread in displaying the loading image as it is executed synchronously.
You have missed:
$(document).ready(function () {
});
try this:
<script>
$(document).ready(function () {
$(".mailContentBtn, .mailListBtn").click(function () {
var currentId = $(this).attr('id');
currentId = currentId.split("_");
var actualId = currentId[1];
if ($("#C_" + actualId).is(":visible"))
$("#C_" + actualId).hide("slow", "swing");
$("img#LOADER_" + actualId).show();
if (currentId[0] == "MCBTN") {
var dataString = "action=getMailContentByID" +
"&mailID=" + actualId;
}
else {
var dataString = "action=getMailListByID" +
"&mailID=" + actualId;
}
$.ajax({
type: "POST",
url: "include/getMail.php",
data: dataString,
cache: false,
async: false,
success: function (html) {
$("#SPAN_" + actualId).empty();
$("#SPAN_" + actualId).append(html);
$("#C_" + actualId).show("slow", "swing");
$("img#LOADER_" + actualId).hide();
}
});
});
})
</script>

Categories

Resources