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");
});
});
Related
I have a problem with jQuery calling an AJAX function, basically everytime a user changes a select box, I want it to call the getSubCategories function, but for some reason, nothing is happening. Any ideas?
If I load the page and add console.log inside the getSubCategories function it logs it, should that even be happening?
function getSubCategories() {
var id = $("#category").prop('selectedIndex');
var selectedCategory = $("#category").val();
//should change this into a response from AJAX and grab the slug from there, this is fine for now.
var slugOfCategory = convertToSlug(selectedCategory);
id++;
console.log('here');
$.ajax({
method: 'GET', // Type of response and matches what we said in the route
url: '/product/get_subcategories', // This is the url we gave in the route
data: {
'id': id
}, // a JSON object to send back
success: function(response) { // What to do if we succeed
$("#sub_category option").remove(); //Remove all the subcategory options
$.each(response, function() {
$("#sub_category").append('<option value="' + this.body + '">' + this.body + '</option>'); //add the sub categories to the options
});
$("#category_slug").attr('value', slugOfCategory);
},
error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
}
function getCategories() {
var id = $("#type").prop('selectedIndex');
var selectedType = $("#type").val();
//should change this into a response from AJAX and grab the slug from there, this is fine for now.
var slugOfType = convertToSlug(selectedType);
console.log(slugOfType);
//add one to the ID because indexes dont start at 0 as the id on the model
id++;
$.ajax({
method: 'GET', // Type of response and matches what we said in the route
url: '/product/get_categories', // This is the url we gave in the route
data: {
'id': id
}, // a JSON object to send back
success: function(response) { // What to do if we succeed
$("#category option").remove(); //Remove all the subcategory options
$.each(response, function() {
$("#category").append('<option value="' + this.name + '">' + this.name + '</option>'); //add the sub categories to the options
});
$("#type_slug").attr('value', slugOfType);
},
error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
}
function convertToSlug(Text) {
return Text
.toLowerCase()
.replace(/ /g, '_')
.replace(/[^\w-]+/g, '');
}
$(document).ready(function() {
var firstCatgegory = $("#category").val();
var slugOfFirstCategory = convertToSlug(firstCatgegory);
$("#category_slug").attr('value', slugOfFirstCategory);
var firstType = $("#type").val();
var slugOfFirstType = convertToSlug(firstType);
$("#type_slug").attr('value', slugOfFirstType);
$("#type").change(getCategories());
$("#category").change(getSubCategories());
});
Thanks for any help. (Sorry the code is a little messy, i've just been trying to get it to work so far)
This is due to the fact that the ajax call you are trying to make is asynchronous. When you call getSubCategories() it returns undefined which is why your code is not working.
To make this work you need to put your code within the success callback function instead.
<script>
function getSubCategories()
{
var id= $("#category").prop('selectedIndex');
$.ajax({
method: 'GET',
url: '/product/get_subcategories',
data: {'id' : id},
success: function(response){
// DO SOMETHING HERE
},
error: function(jqXHR, textStatus, errorThrown) { }
});
}
$( document ).ready(function() {
// This is also wrong. Currently you're passing
// whatever is returned from getSubCategories
// (which is undefined) as the callback function
// that the "change" event will call. This instead
// should be the reference to the function. Which
// in this case is getSubCategories
$("#category").change(getSubCategories);
});
Please put getCategories() and getSubCategories() Methods inside Change function like this.Sorry for not code formatting.
<script>
$(document).ready(function(){
$("#category").change(function(){
getSubCategories();
});
$("#type").change(function(){
getCategories();
});
});
</script>
Sorry for the question, but I need a little help with my code in JQuery / Javascript
I Have this code emulate a Button from
Code
<i class="fa fa-plus"></i> Add
I need this code call a function in my <script></script> declaration
Declaration
<script type="text/javascript" src="~/Scripts/jquery-1.11.0.js"></script>
<script type="text/javascript">
function clearErrors() {
$('#msgErrorNewTourist').html('');
$('#msgError').html('');
}
function writeError(control, msg) {
var err_msg = '<div class="alert-message error"><a class="close" href="#">×</a><p>' + msg + '</p></div>';
$('#' + control).html(err_msg);
}
$(document).ready(function () {
$('.closeModal').live('click', function () {
this.remove();
$('#Modal-Tourist').modal('hide');
});
$('#Modal-Tourist form').live('submit', function () {
clearErrors();
$.post($(this).attr('action'), $(this).serialize(), function (data, status) {
$('#Modal-Tourist').modal('hide');
$("#eventsDetailsList").html(data);
}).error(function (error, status, a, b) {
writeError('msgError', 'Error processing request. Please check errors and try again!');
$('.modal-body div.alert').html(error.responseText);
});
return false;
});
function getRequest(url) {
$.ajax({
url: url,
context: document.body,
success: function (data) {
$('.modal-content p.body').html(data);
$(this).addClass("done");
$('#Modal-Tourist').modal('show');
$('#Name').focus();
},
error: function (err) {
writeError('msgErrorNewTourist', err.responseText);
}
});
}
$('a.newTourist').live('click', function () {
alert('Ingreso');
clearErrors();
var id = $(this).attr("eventsid");
var url = '#Url.Content("~/Tourist/Create")/' + id;
getRequest(url);
return false;
});
});
</script>
But doesn't work, My code running in perfectly state and in certainly moments I put an alert('working'); in the entire body of the script to verify the code is charge and running...
Sorry for my bad english, anyone can help me and show me the error of my code and why doesn't work the call for the function
$('a.newTourist').live('click', function () {
alert('Ingreso');
clearErrors();
var id = $(this).attr("eventsid");
var url = '#Url.Content("~/Tourist/Create")/' + id;
getRequest(url);
return false;
});
Thanks to Stephen Muecke and Frank Fajardo for the Help
I Change my <script></script>, replace .live() for .on() and the code work perfectly, I have other issue but I think open other post for that... Thanks guys
<script type="text/javascript" src="~/Scripts/jquery-2.1.4.js"></script>
<script type="text/javascript">
function clearErrors() {
$('#msgErrorNewTourist').html('');
$('#alert').html('');
}
function writeError(control, msg) {
var err_msg = '<div class="alert-message error"><a class="close" href="#">×</a><p>' + msg + '</p></div>';
$('#' + control).html(err_msg);
}
$(document).ready(function () {
$('#Modal-Tourist form').on('submit', function () {
if ($(this).valid()) {
$.ajax({
url: '#Url.Action("Create","Tourist")',
data: $(this).serialize(),
success: function (result) {
$('#Modal-Tourist').modal('hide');
$("#eventsDetailsList").html(result);
},
failure: function (err) {
writeError('body', 'Wrong Data');
}
});
}
return false;
});
function getRequest(url) {
jQuery.noConflict();
$.ajax({
url: url,
context: document.body,
success: function (data) {
$('.modal-content p.body').html(data);
$('#Modal-Tourist').modal('show');
$('#Name').focus();
},
error: function (err) {
writeError('msgErrorNewTourist', err.responseText);
}
});
}
$('a.newTourist').click(function () {
var id = $(this).attr("eventsid");
var url = '#Url.Content("~/Tourist/Create")/' + id;
getRequest(url);
return false;
});
});
</script>
I hired a developer to help with some work, he was mostly PHP focused and attempted this javascript. The following AJAX script breaks the page whenever it reloads the HTML into the DOM. It called a function via Codenigniter to reload the view within the page. Once this happens, all of the javascript no longer works.
I can't seem to find a solution that helps solve this issue. Please help.
Note: Ideally I would of rather the code only loaded the data and not refresh the HTML, but for now this will need to do as I am up against a timeline.
The code:
$(document).ready(function () {
// Ajax Form Submit
$('body').on('click', '.submitForm', function () {
var formid = $(this).parents('form').attr('id');
var validationResult = $('#' + formid).validationEngine('validate');
if (!validationResult) {
return false;
}
var url = $('#' + formid).attr('action');
var formdata = $('#' + formid).serialize();
if ($('#' + formid).find('.submitForm').hasClass('loading')) {
$(this).hide();
$('#' + formid).find('.loader').show();
}
$.ajax({
type: "POST",
cache: false,
url: url,
data: formdata,
dataType: 'json',
success: function (data) {
if ($('#' + formid).find('.submitForm').hasClass('loading')) {
$('#' + formid).find('.submitForm').css('display', 'inline');
$('#' + formid).find('.loader').hide();
}
if (data.type == 'add') {
if (data.html) {
var newhtml = "<tr>" + data.html + "</tr>";
$('.tab-pane.active table').append(newhtml);
}
$('#' + formid).find('.message').html(data.msg).show();
$('#' + formid).trigger('reset');
setInterval(function () {
$('#' + formid).find('.message').hide();
}, 5000);
} else {
if (data.error) {
$('#' + formid + ' .message').show().html(data.error);
} else {
$('#' + formid + ' .message').show().html(data.msg);
if (data.reload_loc) {
window.setTimeout(function () {
window.location.href = data.reload_loc;
}, 4 * 1000);
}
}
}
}
});
});
// Generic Save Form Data
$('body').on('click', '#saveFormdata', function () {
var formid = $(this).parents('form').attr('id');
var validationResult = $('#' + formid).validationEngine('validate');
if (!validationResult) {
return false;
}
$('#' + formid).submit();
});
});
You just do something like this:
function bindEvent()
{
$('body').on('click', '.submitForm', function () { //Your code });
$('body').on('click', '#saveFormdata', function () { //Your code});
}
function unblindEvent()
{
$('body').off('click', '.submitForm'); //Something like this, please read Jquery.off
$('body').off('click', '#saveFormdata');
}
Before you replace these element, call unblindEvent(). And after you replace these elements call bindEvent().
I have a form being sent over ajax with event.preventdefault on it so it doesn't send automatically but this then stops the check boxes from functioning...
How do I get around this...
JSfiddle
$('[name="id"]').each(function (index, el) {
var getval = $(this).val();
console.log(getval);
$('#form_pub_priv_' + getval).on('click', function (event) {
event.preventDefault();
var arr_unchecked_values = $('input[type=checkbox]:not(:checked)').map(function () {
return this.value;
}).get();
var formvalues = $('#form_pub_priv_' + getval + ' [name="id"]').serialize();
var dataJoin = '&mod=' + arr_unchecked_values + '&' + formvalues;
console.log(dataJoin);
$.ajax({
url: 'unpublish-Lyst.html',
type: 'POST',
data: dataJoin
})
.done(function (data) {
console.log(data);
})
.fail(function () {
console.log("error");
})
.always(function () {
console.log("complete");
});
});
});
You're stopping the click event indirectly in your checkboxes, that's why your checkboxes don't work.
$('#form_pub_priv_' + getval).on('click', function (event) {
event.preventDefault(); //Remove this!
var arr_unchecked_values = ...
To prevent the form from being submited, you should do it in tye submit form event.
$('#form_pub_priv_' + getval).submit(function(event){
...
event.preventDefault(); //Here it's ok
});
Cheers
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);
}
})