Hiding a modal on clicking off in bootstrap - javascript

I have a button that turns on and off a connection. When the button is in on state and the user clicks on it. In order to turn it off, a modal pops up and asks for confirmation. But when the button is in off state, no modal should pop up. The problem is that its the same button that is being toggled to display "On" and "Off" and a modal element is attached to it. Even when the off button is clicked the modal pops up which I don't want. Please help me out.
if(status == 'On'){
var url = "/streams/status";
$('button[id="modal-'+ streamId + '"]').click(function(){
console.log("close modal function")
$('myModal-'+ streamId).modal('hide');
$.ajax({
type: "POST",
url: url,
data: "streamId="+streamId,
success: function(res){
$('button[id="profile-'+ res.streamId + '"]').toggleClass('btn-success btn-danger');
$('button[id="profile-'+ res.streamId + '"]').text(function (){
console.log($(this).text())
return 'Off';
});
},
error: function (res){
console.log('there was an error', res);
}
});
})
}
else{
console.log("button is off currently");
$('myModal-' + streamId).modal('hide');
var url = "/streams/status";
$.ajax({
type: "POST",
url: url,
data: "streamId="+streamId,
success: function(res){
$('button[id="profile-'+ res.streamId + '"]').toggleClass('btn-success btn-danger');
$('button[id="profile-'+ res.streamId + '"]').text(function (){
console.log($(this).text())
return 'On';
});
},
error: function (res){
console.log('there was an error', res);
}
});
}
})

i think you should add a rel attribute (off or on), detect onclick event and check this attribute :
$('#myModal-' + streamId).click(function(event){
if($('#myModal-' + streamId).attr('rel') == 'on'){
//do ajax request ON here
//on success ajax, replace return 'off' by
$('#myModal-' + streamId).attr('rel', 'off');
}
else{
//do ajax request OFF here
//on success ajax, replace return 'on' by
$('#myModal-' + streamId).attr('rel', 'on');
}
}
it should be works

Here is the correct way to do it:
script.
function toggleStatus (streamId, statusBefore){
$.ajax({
type: "POST",
url: "/streams/status",
data: "streamId="+streamId,
success: function(res){
$('button[id="profile-'+ res.streamId + '"]')
.toggleClass('btn-success btn-danger')
.attr('data-toggle', statusBefore == true ? "": 'modal');
$('#profile-glyphicon-'+ res.streamId).toggleClass('glyphicon-ok glyphicon-remove');
},
error: function (res){
console.log('there was an error', res);
}
});
}
$('button[id^="modal-"]').click(function(){
var streamId = this.id.split('-')[1];
toggleStatus(streamId, true);
$('myModal-'+streamId).modal('hide');
})
$('button[id^="profile-"]').on("click", function(e){
var streamId = this.id.split('-')[1];
var statusBefore;
var dataToggleStatus = $('#profile-' + streamId).attr("data-toggle");
if(dataToggleStatus=='modal'){
statusBefore = true;
e.preventDefault();
} else {
statusBefore = false;
toggleStatus(streamId, statusBefore);
}
})

Related

How to refresh the page with updated data when click update button

function update(){
var name= document.getElementById("TextBox").value;
$.ajax({
url: '....',
type: 'post',
data: {....//many data include// 'name' : name, ....},
success: function(data) {
var replacevalue=data.replace(/[\[\]']/g,'' );
alert(replacevalue);
var stringstatus=replacevalue.replace(/['"]+/g, '');
alert(stringstatus);
if(stringstatus == "success"){
alert ("Successfully Update ")
}
else{
alert("Failed!");
return ;
}
returnToDisplayPage();
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
});
}
function returnToDisplayPage(){
var id = document.getElementById("TextBox").text;
window.location = './DisplayPage.php?Name='+id;
}
Please suggest me. How should I do to get the updated data when click update button and refresh or reload page ? In function returnToDisplayPage() methods. I got only the name of update data and other related fields data didn't get back.
Try something like this:
$.post('url', {params}, function(response){
//Here you check if you got response from url
// And then you can do whatever you like to do with received data
if(response == 'ok'){
//do your stuff
//then
window.location.reload();
}
}
When we will get result in response then After 5 seconds page will be refresh..
success: function(data){
if(data.success == true){ // if true (1)
setTimeout(function(){// wait for 5 secs(2)
location.reload(); // then reload the page.(3)
}, 5000);
}
}

ajax & load are not working togeher

I want to check each time user access when page loading, sessions.php is working and return true or false but load is not working with ajax...
var section = $("#header a");
section.on('click', function() {
$.ajax({
type: "POST",
url: "/particley/global/post/sessions.php",
success: function(html) {
if (html == 'true') {
$('#load').load(section.id + ' #load');
window.history.pushState(this.id, this.id, this.id);
if (this.id == '/p/sign-out') {
window.location.assign("/p");
}
} else {
window.location.assign("/p/sign-out");
}
}
});
});
var section = $("#header a");
section.click(function(){
$('#load').load(this.id + ' #load', function() {
$.ajax({
type: "POST",
url: "/particley/global/post/sessions.php",
success: function(html)
{
if (html != 'true') {
window.location.assign("/p/sign-out");
}
}
});
});
window.history.pushState(this.id, this.id, this.id);
if (this.id == '/p/sign-out') {
window.location.assign("/p/sign-out");
}
});
for this line
$('#load').load(section.id + ' #load');
did you mean:
$('#load').load(section.attr("id") + ' #load');
to retrieve the attribute id ?
2 cents ;)

showing loader image with submition using ajax

$(document).ready(function(){
$('#registration_form').on('submit',function(e){
/// e.preventDefault();
$("#loading").show();
var email = $('#email').val();
var checkEmail = $("#email").val().indexOf('#');
var checkEmailDot = $("#email").val().indexOf('.');
if(email == ''){
$("#email").addClass('error');
error_flag = 1;
}
if(checkEmail<3 || checkEmailDot<9){
$("#email").addClass('error');
error_flag = 1;
}
$.ajax({
url: "<?=base_url('controller/registration_ajax')?>",
// url: "<?=base_url('controller/register')?>",
type: "POST",
datatype: "JSON",
data: {email: email},
success: function(res){
var data = $.parseJSON(res);
var status = data.status;
var message = data.message;
if(status == 'true'){
// $('#myModal').modal('hide');
$('#message').html('');
$('#message').html(message);
$('#message').css('color',"green");
$("loading").hide();
}
else{
$('#message').html('');
$('#message').html(message);
$('#message').css('color',"red");
}
}
});
e.preventDefault();
});
});
how to use loader with ajax when message is success the load stop when message is or error loader is stop how to use loader image image in this stiuation. if submition is true loading hide if false loading also hide.
how to use loader with ajax when message is success the load stop when message is or error loader is stop how to use loader image image in this stiuation. if submition is true loading hide if false loading also hide.
You can use the always handler to do that.
Also note that, you should so the loader only if the ajax is sent, so in your case only after the validations are done it should be done.
$(document).ready(function() {
$('#registration_form').on('submit', function(e) {
/// e.preventDefault();
var email = $('#email').val();
var checkEmail = $("#email").val().indexOf('#');
var checkEmailDot = $("#email").val().indexOf('.');
if (email == '') {
$("#email").addClass('error');
error_flag = 1;
}
if (checkEmail < 3 || checkEmailDot < 9) {
$("#email").addClass('error');
error_flag = 1;
}
$.ajax({
url: "<?=base_url('controller/registration_ajax')?>",
// url: "<?=base_url('controller/register')?>",
type: "POST",
datatype: "JSON",
data: {
email: email
},
beforeSend: function() {
//show it only if the request is sent
$("#loading").show();
},
success: function(res) {
var data = $.parseJSON(res);
var status = data.status;
var message = data.message;
if (status == 'true') {
// $('#myModal').modal('hide');
$('#message').html('');
$('#message').html(message);
$('#message').css('color', "green");
$("loading").hide();
} else {
$('#message').html('');
$('#message').html(message);
$('#message').css('color', "red");
}
}
}).always(function() {
//irrespective of success/error hide it
$("#loading").hide();
});
e.preventDefault();
});
});
Have a loading image like this:
<img src="loader.gif" id="loader" />
And in the script, before the AJAX call, show it:
$("#loader").fadeIn(); // You can also use `.show()`
$.ajax({
// all your AJAX stuff.
// Inside the success function.
success: function (res) {
// all other stuff.
// hide the image
$("#loader").fadeOut(); // You can also use `.hide()`
} // End success
}); // End AJAX
Solution to your Problem
You are missing # in your call:
$("loading").hide();
//-^ Add a # here.
Change it to:
$("#loading").hide();
I'd do it this way:
function loadsth(){
$('#load_dialog').show();
$.ajax({
method: "POST",
url: "?ajax=ajax_request",
data: { data:"test"},
success:function(data) {
$('#load_dialog').hide();
}
});
});
Try using jquery's ajax function beforeSend
$.ajax({
method: "POST",
url: "/url",
data: { data:"test"},
beforeSend: function() {
//SHOW YOUR LOADER
},
success:function(data) {
//HIDE YOUR LOADER
}
});
});
I hope this has given you some idea.
try this its work for u
$.ajax({
url: "<?=base_url('controller/registration_ajax')?>",
type: 'POST',
beforeSend: function(){
$("#loaderDiv").show();
},
success: function(data) {
$('#output-json-inbox').jJsonViewer(data);
$("#loaderDiv").hide();
},
error: function() {
alert("error");
}
});

Javascript breaks after div refresh

I have an ajax function, which submits the data and refreshes the div after the data has been updated. The problem is that the jQuery elements within the div breaks after the form has been submitted, and the div has been refreshed.
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null
}
tournamentid = getURLParameter('id');
$(document).ready(function () {
$(document).on('click', "button#submit" ,function(){
$.ajax({
type: "POST",
url: "test.php?page=tourneys&id=" + tournamentid + "&action=teams&submit=true", //process to mail
data: $('#swapteams').serialize(),
success: function(msg){
createNoty('The teams has been updated!', 'success');
// Refresh the div after submission
$("#refresh").load("test.php?page=tourneys&id=" + tournamentid + "&action=teams #refresh");
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
return false;
});
});
// the plugins and jQuery variables within the refresh div
$(document).ready(function() {
$('a[id^="teamname"]').editable({
ajaxOptions : {
type : 'post'
}
});
});
$(document).ready(function() {
$('select[id="swap"]').change(function(){
$( "#saveprogress" ).show("fade");
});
});
You need to use event delegation to support dynamically added elements also you need to initialize the plugin again once the div is refreshed
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [, ""])[1].replace(/\+/g, '%20')) || null
}
tournamentid = getURLParameter('id');
$(document).ready(function () {
$(document).on('click', "button#submit", function () {
$.ajax({
type: "POST",
url: "test.php?page=tourneys&id=" + tournamentid + "&action=teams&submit=true", //process to mail
data: $('#swapteams').serialize(),
success: function (msg) {
createNoty('The teams has been updated!', 'success');
// Refresh the div after submission and pass a callback which will initialize the plugins
$("#refresh").load("test.php?page=tourneys&id=" + tournamentid + "&action=teams #refresh", createEditable);
},
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
return false;
});
});
// the plugins and jQuery variables within the refresh div
$(document).ready(createEditable);
function createEditable() {
$('a[id^="teamname"]').editable({
ajaxOptions: {
type: 'post'
}
});
}
$(document).ready(function () {
//use event delegation
$(document).on('change', 'select[id="swap"]', function () {
$("#saveprogress").show("fade");
});
});

Ajax request not being sent from JQuery

I am using the following code for sending ajax request but the request is not being sent. Can anyone help me to find the problem?
$("input.ub").click(function () {
console.log("I am here");
var id = $(this).attr('id');
var pid = "p" + id.substring(1, 2);
var text = $("#" + pid).text();
$("#" + pid).html('<input type="text" id="up" value="' + text + '" /><input type="button" id="req" value="Submit" />');
//Ajax request to be sent
$("#req").one("click", function () {
//var action = $("#postform").attr('action');
console.log("I am Second");
var form_data1 = {
post: $("#up").val(),
is_ajax: 1,
update: parseInt(id.substring(1, 2))
};
console.log($("#up").val());
$.ajax({
type: "POST",
url: "updatePosts.php",
data: form_data1,
success: function (response) {
if (response == "success") {
console.log("Succes MEssage");
$(location).attr('href', 'viewPosts.php');
} else console.log("You are failed here instead");
}
});
console.log("Request not sent");
return false;
});
I am getting the failure console messages. But i don't see any problem in the code.
You're returning "request not sent" even when it is successful. You need to use the error setting in your AJAX call.
http://api.jquery.com/jquery.ajax/
It looks like you may have forgotten a bracket after else...
$("input.ub").click(function(){
console.log("I am here");
var id = $(this).attr('id');
var pid="p"+id.substring(1,2);
var text=$("#"+pid).text();
$("#"+pid).html('<input type="text" id="up" value="'+text+'" /><input type="button" id="req" value="Submit" />');
//Ajax request to be sent
$("#req").one("click",function(){
//var action = $("#postform").attr('action');
console.log("I am Second");
var form_data1 = {
post: $("#up").val(),
is_ajax: 1,
update:parseInt(id.substring(1,2))
};
console.log($("#up").val());
$.ajax({
type: "POST",
url: "updatePosts.php",
data: form_data1,
success: function(response){
if(response == "success"){
console.log("Succes MEssage");
$(location).attr('href','viewPosts.php');
}
else { <=====HERE
console.log("You are failed here instead");
}
});
console.log("Request not sent");
return false;
});

Categories

Resources